SpringMVC + MyBatis (latest)

The current mainstream Web MVC framework, in addition to Struts, there is Spring MVC, mainly because Spring MVC is relatively simple to configure, very clear to use, very flexible, integrates well with Spring, and supports RESTful APIs better than struts. Be good.
MyBatis is an upgraded version of ibatis. As an old rival of hibernate, it is a persistence layer framework that can customize SQL, stored procedures and advanced mapping.
The main difference with hibernate is that mybatis is semi-automatic, while hibernate is fully automatic, so when the application requirements become more and more complex, automated sql seems clumsy.
Since I took a project some time ago to do it with springmvc, I played the game of integrating the framework with the attitude of practicing my hands. People who often build frameworks should know that the core of framework construction is configuration files. So I mainly paste the code of several configuration files. Again, after I wrote the configuration file, I ran the error and added the jar. Here is a list of the jar packages I use (should be the least):

Note: There are some additional jars in the picture above. For example, the database connection pool I use is Alibaba's druid and log framework logback, so related jars are introduced. The use and configuration of these two frameworks are very simple, so I won't go into details here.
1. Integrate SpringMVC
springMybatis-servlet.xml:

[html] view plain copy



 

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/ beans" xmlns:xsi="http://www.w3.  
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       xsi:schemaLocation="http://www.springframework .org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context http://www.springframework.org/schema/ context/spring-context.xsd 
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
     
        <!-- enable spring mvc annotations- -> 
    <mvc:annotation-driven>  
    </mvc:annotation-driven> 
     
    <!-- Automatically scanned package name, so that Spring supports automatic detection of components, such as annotated Controller--> 
    <context:  component-scan base-package="com.alibaba.controller" /> 
    <context:component-scan base-package="com.alibaba.service"/> 
     
     
    <!-- View resolver: Define the prefix and suffix of the file to be jumped-->   
    <bean id="viewResolver" class="org. springframework.web.servlet.view.InternalResourceViewResolver">   
        <property name="prefix" value="/WEB-INF/jsp/" />   
        <property name="suffix" value=".jsp" /> <!-- Can be empty, it is convenient to implement your own logic to select the view interpretation class based on the extension --> 
    </bean>   
 
    <!--Configure interceptors, multiple interceptors, execute sequentially -->  
    <mvc:interceptors>   
        <mvc :interceptor>   
            <!-- matches the url path --> 
            <mvc:mapping path="/" /> 
            <mvc:mapping path="  /user/**" /> 
            <mvc:mapping path="/test/**" /> 
             
            <bean class="com.alibaba.interceptor.CommonInterceptor"></bean>   
        </mvc:interceptor> 
        <!-- When setting multiple interceptors, call the preHandle method in order, and then call each interceptor in reverse order The postHandle and afterCompletion methods --> 
    </mvc:interceptors> 
       
</beans>    


2. Integrate Mybatis

spring-dao.xml:

[html] view plain copy



 

<?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:mybatis="http:// mybatis.org/schema/mybatis-spring" 
       xmlns:context="http://www.springframework.org/schema/context" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
     
    < !-- The classes under this package support annotations, which means that they will be treated as {@code mybatis mapper}. After configuration, it means that the mapper class can be automatically imported --> 
    <mybatis:scan base-package="com.alibaba.dao" /> 
    <!--Introduce properties file--> 
    <context:property-placeholder location="classpath:configuration.properties"/> 
     
    <!--Database connection--> 
    <bean id="dataSource" class="com. alibaba.druid.pool.DruidDataSource"   init-method="init" destroy-method="close">  
        <property name="url" value="${jdbc.url}" /> 
        <property name="username" value="${jdbc.username}"/> 
        <property name="password" value="${jdbc.password}"/> 
        <!-- 配置初始化大小、最小、最大 --> 
        <property name="initialSize"><value>1</value></property> 
        <property name="maxActive"><value>5</value></property> 
        <property name="minIdle"><value>1</value></property> 
        <!-- 配置获取连接等待超时的时间 --> 
        <property name="maxWait"><value>60000</value></property> 
        <!-- Configure the filters for monitoring and statistics interception -->          <!-- How long is the configuration interval to perform detection and detect idle connections that need to be closed, The unit is milliseconds --> 
        <property name="filters"><value>stat</value></property> 

        <property name="timeBetweenEvictionRunsMillis"><value>60000</value></property> 
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> 
        <property name="minEvictableIdleTimeMillis"><value>300000</value></property> 
        <!-- 
        <property name="validationQuery"><value>SELECT 'x'</value></property> 
        <property name="testWhileIdle"><value>true</value></property> 
        <property name="testOnBorrow"><value>false</value></property> 
        <property name="testOnReturn"><value>false</value></property> 
        <property name="poolPreparedStatements"><value>true</value></property> 
        <property name="maxOpenPreparedStatements"><value>20</value></property> 
         --> 
    </bean> 
     
    <!-- mybatis配置 --> 
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
        <property name="dataSource" ref="dataSource" /> 
    </bean>  
</beans>    


3.web.xml整合SpringMVC和Mybatis

[html] view plain copy



 

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> 
    <!-- This servlet is provided for tomcat, jetty and other containers, and the static resource mapping is changed from / to /static/ directory, such as visiting http://localhost/foo.css originally, and now http://localhost/static/foo .css --> 
    <!-- Do not intercept static files --> 
    <servlet-mapping> 
        <servlet-name>default</servlet-name> 
        <url-pattern>/js/*</url-pattern> 
        <url -pattern>/css/*</url-pattern> 
        <url-pattern>/images/*</url-pattern> 
        <url-pattern>/fonts/*</url-pattern> 
    </servlet-mapping> 
     
    < !-- Configure character set--> 
    <filter> 
        <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> 
    <filter-mapping> 
        <filter-name>encodingFilter</filter-name> 
        <url-pattern>/*</url-pattern > 
    </filter-mapping> 
     
    <!-- When DispatcherServlet is initialized, the framework looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of the web application, 
            and defines the relevant Beans there, Override any beans defined in the global --> 
    <servlet>   
        <servlet-name>springMybatis</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>springMybatis</servlet-name> 
        <!-- 所有的的请求,都会被DispatcherServlet处理 --> 
        <url-pattern>/</url-pattern> 
    </servlet-mapping> 
      
    <context-param> 
        <param-name>contextConfigLocation</param-name> 
        <param-value>/WEB-INF/config/spring-*.xml</param-value> 
    </context-param> 
    <listener> 
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 
    <!-- druid web 监控 --> 
    <servlet> 
        <servlet-name>DruidStatView</servlet-name> 
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>DruidStatView</servlet-name> 
        <url-pattern>/druid/*</url-pattern> 
    </servlet-mapping> 
     
    <error-page> 
        <error-code>404</error-code> 
        <location>/error/404.jsp</location> 
    </error-page> 
    <error-page> 
        <error-code>500</error-code> 
        <location>/error/500.jsp</location> 
    </error-page> 
</web-app> 

4.logback.xml日志配置

[html] view plain copy



 

<?xml version="1.0" encoding="UTF-8"?> 
<configuration> 
 
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
    <encoder>   
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> 
    </encoder> 
  </appender> 
   
  <logger name="test.LogbackTest" level="TRACE"/> 
   
  <logger name="com.alibaba.controller.TestController" level="TRACE"/> 
   
  <logger name="org.springframework.web.servlet.DispatcherServlet" level="DEBUG" /> 
  <logger name="druid.sql" level="INFO" /><!-- If slf4j is not configured in spring-config, the sql log will not be displayed, logback is just an implementation of slf4j--> 
  <root level="debug"> 
    <appender-ref ref="STDOUT" /> 
  </root> 
</configuration> 


5.configuration.properties configuration

[html] view plain copy



 

jdbc.url=jdbc\:mysql\://localhost\:3306/druid? useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull 
jdbc.username=root 
jdbc.password=123456 


6. Test whether the build is successful, the background code is the

first to log in, use encryption, you can remove

[java] view plain copy



 

package com. alibaba.controller; 
 
 
import javax.annotation.Resource; 
import javax.servlet.http.HttpServletRequest; 
 
import org.apache.commons.codec.digest.DigestUtils; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
 
import com.alibaba.model.User; 
import com.alibaba.service.UserService; 
import com.alibaba.util.RequestUtil; 
 
/**
* @author tfj
* 2014-7-26
*/ 
@Controller 
public class SystemController { 
    private final Logger log = LoggerFactory.getLogger(SystemController.class); 
    @Resource 
    private UserService userService; 
     
    @RequestMapping(value = "/",method = RequestMethod.GET) 
    public String home() { 
        log.info("返回首页!"); 
        return "index"; 
    } 
     
    @RequestMapping(value = "/test/hello",method = RequestMethod.GET) 
    public String testHello() { 
        log.info("执行了testHello方法!"); 
        return "testHello"; 
    } 
     
    @RequestMapping(value = "/login",method = RequestMethod.POST) 
    public String testLogin(HttpServletRequest request,@RequestParam String username, @RequestParam String password) { 
        log.info("执行了testLogin方法!"); 
        User user = userService.findUserByName(username); 
        if(user!=null){ 
            if(user.getPassword().equals(DigestUtils.md5Hex(password))){ 
                request.getSession().setAttribute("userId", user.getId());   
                request.getSession().setAttribute("user", username);   
                return "redirect:" + RequestUtil.retrieveSavedRequest();//Jump to the access page 
            }else{ 
                log.info("password error");   
                request.getSession().setAttribute("message", "Username Incorrect password, please log in again"); 
                return "login";  
            } 
        }else{ 
            log.info("Username does not exist");   
            request.getSession().setAttribute("message", "Username does not exist, please re-login Log in");   
            return "login";  
        } 
    } 


关于service和model就不写了,写一下mybatis的mapper类映射

[html] view plain copy



 

<?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="com.alibaba.dao.UserMapper">     
    <select id="findUserByName" resultType="com.alibaba.model.User"> 
        select id, username , password from sysuser where username = #{username}  
    </select> 
</mapper> 



源码来源: minglisoft.cn/technology

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326457795&siteId=291194637