• 搭建SpringMVC+Mybatis框架并实现数据库的操作


    User类

    public class User {
        private Integer id;
        private String userName;
        private String password;
        private String tel;
        private String email;
        public String getTel() {
            return tel;
        }
        public void setTel(String tel) {
            this.tel = tel;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    
    }

    dao

    public interface UserMapper {
        public List<User> getUserList();
        public User getUser(User user);
        public int insertUser(User user);
        public int deleteUser(User user);
        public int updateUser(User user);
        
    }

    mybatis的映射

    <?xml version="1.0" encoding="UTF-8"?>  
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="org.project.dao.user.UserMapper">
        
        <!-- getUserList -->
        <select id="getUserList" resultType="user" parameterType="user">
            select * from user order by id desc
        </select>
        
        <!-- getUser -->
        <select id="getUser" resultType="user" parameterType="user">
            select * from user where username = #{userName} and password = #{password}
        </select>
        
        <!-- insertUser -->
        <insert id="insertUser" parameterType="user">
            insert into user (username,password,tel,email) values (
                #{userName},#{password},#{tel},#{email}
            )
        </insert>
        
        <!-- deleteUser -->
        <delete id="deleteUser" parameterType="user">
            delete from user where id = #{id}
        </delete>
        
        
        <!-- updateUser -->
        <update id="updateUser" parameterType="user">
            update user set password = #{password}, tel = #{tel}, email = #{email}
            where id = #{id}
        </update>
    </mapper>  

    service

    public interface UserService {
        /**
         * getUserList
         * @return
         */
        public List<User> getUserList();
        /**
         * getUser
         * @param user
         * @return user
         */
        public User getUser(User user);
        /**
         * insertUser
         * @param user
         * @return int
         */
        public int insertUser(User user);
        /**
         * deleteUser
         * @param user
         * @return int
         */
        public int deleteUser(User user);
        /**
         * updateUser
         * @param user
         * @return int
         */
        public int updateUser(User user);
    }

    service实现类(注解的方式)

    @Service
    public class UserServiceImpl implements UserService {
    
        @Resource
        private UserMapper mapper;
        
        
        public int deleteUser(User user) {
            // TODO Auto-generated method stub
            return mapper.deleteUser(user);
        }
    
        public User getUser(User user) {
            // TODO Auto-generated method stub
            return mapper.getUser(user);
        }
    
        public List<User> getUserList() {
            // TODO Auto-generated method stub
            return mapper.getUserList();
        }
    
        public int insertUser(User user) {
            // TODO Auto-generated method stub
            return mapper.insertUser(user);
        }
    
        public int updateUser(User user) {
            // TODO Auto-generated method stub
            return mapper.updateUser(user);
        }
    
    }

    控制器

    @Controller //类似Struts的Action
    public class IndexController {
        private Logger loger = Logger.getLogger(IndexController.class);
        @Resource
        private UserService userService;
        
        @RequestMapping("/index.html")  // 请求url地址映射,类似Struts的action-mapping
        public String index() {
            loger.debug("IndexController index.userService:" +userService );
            return "index";
        }
        @RequestMapping("/register.html")
        public String register(){
            return "register";
        }
        @RequestMapping("/exit.html")  // 请求url地址映射,类似Struts的action-mapping
        public String exit() {
            loger.debug("IndexController exit.");
            return "exit";
        }
        @RequestMapping("/login.html")
        public String login(){
            return "login";
        }
        @RequestMapping("/loginsuccess.html")  // 请求url地址映射,类似Struts的action-mapping
        public ModelAndView  loginsuccess(User user) {
            loger.debug("IndexController login.username : " + user.getUserName()
                    + " --- password:"+user.getPassword());
            
            user = userService.getUser(user);
            
            loger.debug("select username : " + user.getUserName()
                    + " --- password:"+user.getPassword());
            return new ModelAndView("loginsuccess");
        }
        
        @RequestMapping("/regsuccess.html") 
        public ModelAndView regsuccess(User user){
             loger.debug("IndexController register.username : " + user.getUserName()
                     + "---- password: " + user.getPassword());
              int f = userService.insertUser(user);
              if(f > 0){
                   user = userService.getUser(user);
              }
              return new ModelAndView("regsuccess");
        }
        
        
    }

    mybatis的配置文件

    <?xml version="1.0" encoding="UTF-8"?>  
        <!DOCTYPE configuration   
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
            "http://mybatis.org/dtd/mybatis-3-config.dtd">  
        <configuration>  
            <settings>  
                <!-- changes from the defaults -->  
                <setting name="lazyLoadingEnabled" value="false" />  
            </settings>  
           <typeAliases>  
               <!--这里给实体类取别名,方便在mapper配置文件中使用--> 
               <!-- <typeAlias alias="user" type="org.project.pojo.User"/>  -->
               <package name="org.project.pojo"/>
           </typeAliases>  
       </configuration>  

    spring-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    
        
        <!-- 使spring扫描包下的所有类,让标注spring注解的类生效 -->
        <context:component-scan base-package="org.project"/>
        
        <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        
        
    
    </beans> 

    applicationContext-mybatis.xml

    <?xml version="1.0" encoding="UTF-8"?>  
        <beans xmlns="http://www.springframework.org/schema/beans"  
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
                xmlns:aop="http://www.springframework.org/schema/aop"  
                xmlns:p="http://www.springframework.org/schema/p"  
                xmlns:tx="http://www.springframework.org/schema/tx"  
                xmlns:context="http://www.springframework.org/schema/context"  
                xsi:schemaLocation="   
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
                    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd   
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
               
            <!-- Properties文件读取配置,base的properties -->  
            <context:property-placeholder location="classpath:jdbc.properties"/>  
               
            <!-- JNDI获取数据源(使用dbcp连接池) destroy-mehod = "close"我们使用的数据库是采用dbcp,连接池只有一个,当你的服务停止的时候,要把dataSource关了。
              scope=“singleton”
    连接池只有一个,并且读取数据池是非常消耗系统性能的,所以要用单例模式-->
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
            <property name="driverClassName" value="${driverClassName}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${uname}"/>
            <property name="password" value="${password}"/>
             </bean> 
    
            <!-- enable transaction demarcation with annotations -->  
            <tx:annotation-driven /> 
               
            <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
            <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
                <property name="dataSource" ref="dataSource" />  
            </bean> 
             
            <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->  
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
                <property name="dataSource" ref="dataSource" />  
                <property name="configLocation" value="classpath:mybatis-config.xml" />  
            </bean> 
            <!-- scan for mappers and let them be autowired 
            MapperScannerConfigurer Mybatis-Spring 会自动为我们注册Mapper对应的MapperFactoryBean对象-->  
            <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
                <property name="basePackage" value="org.project.dao" />  
            </bean>
             
        
                
        </beans>  

    mysql的数据库文件

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/springmvcdb
    uname=root
    password=bdqn
    minIdle=10
    maxIdle=50
    initialSize=5
    maxActive=100
    maxWait=100
    removeAbandonedTimeout=180
    removeAbandoned=true

    日志文件

    log4j.rootLogger=debug,CONSOLE,file
    #log4j.rootLogger=ERROR,ROLLING_FILE
    
    log4j.logger.org.project=error
    log4j.logger.org.apache.ibatis=debug
    log4j.logger.org.mybatis.spring=debug
    log4j.logger.java.sql.Connection=debug
    log4j.logger.java.sql.Statement=debug
    log4j.logger.java.sql.PreparedStatement=debug
    log4j.logger.java.sql.ResultSet=debug
    
    ######################################################################################
    # Console Appender  u65e5u5fd7u5728u63a7u5236u8f93u51fau914du7f6e
    ######################################################################################
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.Threshold=debug
    log4j.appender.CONSOLE.Target=System.out
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - [%p] %d %c - %m%n
    
    ######################################################################################
    # Rolling File  u6587u4ef6u5927u5c0fu5230u8fbeu6307u5b9au5c3au5bf8u7684u65f6u5019u4ea7u751fu4e00u4e2au65b0u7684u6587u4ef6
    ######################################################################################
    #log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
    #log4j.appender.ROLLING_FILE.Threshold=INFO
    #log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
    #log4j.appender.ROLLING_FILE.Append=true
    #log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
    #log4j.appender.ROLLING_FILE.MaxBackupIndex=100
    #log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
    #log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    ######################################################################################
    # DailyRolling File  u6bcfu5929u4ea7u751fu4e00u4e2au65e5u5fd7u6587u4ef6uff0cu6587u4ef6u540du683cu5f0f:log2009-09-11
    ######################################################################################
    log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.file.DatePattern=yyyy-MM-dd
    log4j.appender.file.File=${springMVCProject.root}/logs/log.log
    log4j.appender.file.Append=true
    log4j.appender.file.Threshold=debug
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
    
    #DWR u65e5u5fd7
    #log4j.logger.org.directwebremoting = ERROR
    
    #u663eu793aHibernateu5360u4f4du7b26u7ed1u5b9au503cu53cau8fd4u56deu503c
    #log4j.logger.org.hibernate.type=DEBUG,CONSOLE 
    
    #log4j.logger.org.springframework.transaction=DEBUG
    #log4j.logger.org.hibernate=DEBUG
    #log4j.logger.org.acegisecurity=DEBUG
    #log4j.logger.org.apache.myfaces=TRACE
    #log4j.logger.org.quartz=DEBUG
    
    #log4j.logger.com.opensymphony=INFO  
    #log4j.logger.org.apache.struts2=DEBUG  
    log4j.logger.com.opensymphony.xwork2=debug

     web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        
        <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-*.xml</param-value>
        </context-param>
            
        <!-- spring字符编码过滤器start-->
        <filter>
            <!--① Spring 编码过滤器 -->
            <filter-name>encodingFilter</filter-name>
            <filter-class>
                org.springframework.web.filter.CharacterEncodingFilter
            </filter-class>
            <!--② 编码方式  -->
            <init-param> 
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <!--③ 强制进行编码转换 -->
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <!-- ② 过滤器的匹配 URL -->
        <filter-mapping> 
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- spring字符编码过滤器end-->
        
        
        <!-- Spring MVC配置 -->
        <!-- ====================================== -->
        <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
          
        
        
        <!-- Spring配置 -->
        <!-- ====================================== -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- log4j配置start -->
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>classpath:log4j.properties</param-value>
        </context-param>
        <!-- Spring 加载 Log4j 的监听 -->
        <listener>
            <listener-class>
                org.springframework.web.util.Log4jConfigListener
            </listener-class>
        </listener>
        <!-- log4j配置end -->
        
        
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    jar包

    jar包:
    spring-core-3.2.3.RELEASE.jar
    spring-webmvc-3.2.3.RELEASE.jar
    spring-web-3.2.3.RELEASE.jar
    spring-jdbc-3.2.3.RELEASE.jar
    spring-context-3.2.3.RELEASE.jar
    spring-beans-3.2.3.RELEASE.jar
    spring-context-support-3.2.3.RELEASE.jar
    spring-tx-3.2.3.RELEASE.jar
    spring-aop-3.2.3.RELEASE.jar
    aopalliance-1.0.jar
    spring-expression-3.2.3.RELEASE.jar
    
    
    mysql-connector-java-5.1.0-bin.jar
    mybatis-3.2.2.jar
    mybatis-spring-1.0.2.jar
    commons-dbcp.jar
    commons-pool.jar
    commons-logging-1.1.1.jar
    log4j-1.2.16.jar

    sql语句

    /*
    SQLyog 企业版 - MySQL GUI v7.14 
    MySQL - 5.0.22-community-nt-log : Database - springmvcdb
    *********************************************************************
    */
    
    
    /*!40101 SET NAMES utf8 */;
    
    /*!40101 SET SQL_MODE=''*/;
    
    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
    /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
    
    CREATE DATABASE /*!32312 IF NOT EXISTS*/`springmvcdb` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;
    
    USE `springmvcdb`;
    
    /*Table structure for table `user` */
    
    DROP TABLE IF EXISTS `user`;
    
    CREATE TABLE `user` (
      `id` bigint(20) unsigned NOT NULL auto_increment,
      `username` varchar(50) collate utf8_unicode_ci NOT NULL,
      `password` varchar(70) collate utf8_unicode_ci NOT NULL,
      `tel` int(50),
      `email` varchar(50) COLLATE utf8_unicode_ci,
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    /*Data for the table `user` */
    
    /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
    /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

    页面就省略了

  • 相关阅读:
    sql server 2005 时间转化获取年,有一个时间如20090715,现在要分别查出年、月、日,
    在服务器上使用第三方独立组件对Word/Excel进行编程
    Session的配置
    sql 2005判断某个表或某个表中的列是否存在
    GridView中FooterTemplate模板下内容不显示
    asp.net 按钮单击事件问题(自动弹出新窗口)
    NameValueCollection详解
    System.Web.HttpException: 类型“TextBox”的控件“ctl02_TextBox2”必须放在具有 runat=server 的窗体标记内。
    SqlBulkCopy批量复制数据
    使用嵌入式关系型SQLite数据库存储数据
  • 原文地址:https://www.cnblogs.com/xuerong/p/5000496.html
Copyright © 2020-2023  润新知