SSM framework - detailed integration tutorial (Spring + spring MVC + mybatis)

Recently, I was learning the integration of Spring + spring MVC + mybatis. The following is the detailed steps of your own practical operation with reference to the information on the Internet.

1. Basic concepts

1.1,Spring 

Spring is an open source framework. Spring is a lightweight java Development framework rising in 2003. It is derived from some concepts and prototypes elaborated by Rod Johnson in his book Expert one on one J2EE Development and Design. It is created to solve the complexity of enterprise application Development. Spring uses basic JavaBean s to do things that previously could only be done by EJB s. However, the use of spring is not limited to server-side Development. From the perspective of simplicity, testability and loose coupling, any Java application can benefit from spring. Simply put, spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework.

1.2,SpringMVC     

Spring MVC is a follow-up product of spring framework and has been integrated into spring Web Flow. Spring MVC separates the roles of controller, model object, dispatcher and handler object, which makes them easier to customize.

1.3,MyBatis

MyBatis was originally an open source project iBATIS of apache. In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis. MyBatis is a Java based persistence layer framework. The persistence layer framework provided by iBATIS includes SQL ^ Maps and Data ^ Access ^ Objects (DAO) MyBatis ^ which eliminates the manual setting of almost all JDBC codes and parameters and the retrieval of result sets. MyBatis ^ uses simple ^ XML or annotations for configuration and original mapping, and connects the interface with ^ Java ^ POJOs (Plain Old Java Objects, ordinary Java Objects) are mapped to records in the database.

2. Build development environment and create Maven Web project

See previous posts: http://www.cnblogs.com/zyw-205520/p/4767633.html

3. SSM integration

The following mainly introduces the integration of the three frameworks. For the construction of the environment and the creation of the project, please refer to the above blog. This integration is divided into two configuration files: spring -mybatis.xml, including spring and mybatis configuration files, spring MVC configuration files, and two resource files: JDBC Propertis and log4j properties. The complete directory structure is as follows (the source code download address is attached at the end):

Version of framework used:

       Spring 4.0.2 RELEASE

       Spring MVC 4.0.2 RELEASE

       MyBatis 3.2.6

3.1. Maven introduces the required JAR package

In POM Introducing jar package into XML

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javen.maven01</groupId>
    <artifactId>maven01</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>maven01 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    
    <properties>  
        <!-- spring Version number -->  
        <spring.version>4.0.2.RELEASE</spring.version>  
        <!-- mybatis Version number -->  
        <mybatis.version>3.2.6</mybatis.version>  
        <!-- log4j Log file management pack version -->  
        <slf4j.version>1.7.7</slf4j.version>  
        <log4j.version>1.2.17</log4j.version>  
    </properties> 
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
             <!-- Indicates that the package will be imported during development and will not be loaded during publishing -->  
            <scope>test</scope>
        </dependency>
        <!-- <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency> -->
        
         <!-- spring Core package -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-oxm</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-tx</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <!-- mybatis Core package -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>${mybatis.version}</version>  
        </dependency>  
         <!-- mybatis/spring package -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        
         <!-- Import java ee jar package -->  
        <dependency>  
            <groupId>javax</groupId>  
            <artifactId>javaee-api</artifactId>  
            <version>7.0</version>  
        </dependency>  
        
         <!-- Import Mysql Database link jar package -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.36</version>  
        </dependency>  
        <!-- Import dbcp of jar Bag, used in applicationContext.xml Configuration database in -->  
        <dependency>  
            <groupId>commons-dbcp</groupId>  
            <artifactId>commons-dbcp</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        
        <!-- JSTL Label class -->  
        <dependency>  
            <groupId>jstl</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
        </dependency>  
        <!-- Log file management pack -->  
        <!-- log start -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>${log4j.version}</version>  
        </dependency>  
          
          
        <!-- Format the object to facilitate the output of logs -->  
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>fastjson</artifactId>  
            <version>1.1.41</version>  
        </dependency>  
  
  
        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-api</artifactId>  
            <version>${slf4j.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-log4j12</artifactId>  
            <version>${slf4j.version}</version>  
        </dependency>  
        <!-- log end -->  
        <!-- Reflect JSON -->  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.13</version>  
        </dependency>  
        <!-- Upload component package -->  
        <dependency>  
            <groupId>commons-fileupload</groupId>  
            <artifactId>commons-fileupload</artifactId>  
            <version>1.3.1</version>  
        </dependency>  
        <dependency>  
            <groupId>commons-io</groupId>  
            <artifactId>commons-io</artifactId>  
            <version>2.4</version>  
        </dependency>  
        <dependency>  
            <groupId>commons-codec</groupId>  
            <artifactId>commons-codec</artifactId>  
            <version>1.9</version>  
        </dependency>  

    </dependencies>
    
    <build>
        <finalName>maven01</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.8.v20150217</version>
                <configuration>
                    <httpConnector>
                        <port>80</port>
                    </httpConnector>
                    <stopKey>shutdown</stopKey>
                    <stopPort>9966</stopPort>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I only heard the voice from the mountains: The Tibetan and Han break the news, die, grow and leave. Who will match the first couplet or the second couplet?

3.2. Integrating spring MVC

3.2. 1. Configure spring MVC xml

The annotations in the configuration are also very detailed, mainly including automatic scanning controller, view mode and annotation startup.

This code is by Java Architect must see network-Architecture sorting
<?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:p="http://www.springframework.org/schema/p"  
    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-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- Automatically scan the package so that SpringMVC I think the bag is used@controller The annotated class is the controller -->  
    <context:component-scan base-package="com.javen.controller" />  
    <!-- Annotation driven is extended to bind request parameters to controller parameters -->
    <mvc:annotation-driven/>
    <!-- Static resource processing  css js imgs -->
    <mvc:resources location="/resources/**" mapping="/resources"/>
    
    <!--avoid IE implement AJAX When, return JSON The download file appears -->  
    <bean id="mappingJacksonHttpMessageConverter"  
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/html;charset=UTF-8</value>  
            </list>  
        </property>  
    </bean>  
    <!-- start-up SpringMVC Annotation function to complete requests and annotations POJO Mapping of -->  
    <bean  
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON converter -->  
            </list>  
        </property>  
    </bean>  
      
    <!-- For profile upload, if you do not use file upload, you can not configure it. Of course, if you do not, you do not need to import the upload component package into the configuration file -->  
    <bean id="multipartResolver"    
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- Default encoding -->  
        <property name="defaultEncoding" value="utf-8" />    
        <!-- Maximum file size -->  
        <property name="maxUploadSize" value="10485760000" />    
        <!-- Maximum value in memory -->  
        <property name="maxInMemorySize" value="40960" />    
        <!-- Enabled to delay file parsing in order to catch file size exceptions -->
        <property name="resolveLazily" value="true"/>
    </bean>   
    
    <!-- to configure ViewResolver . Multiple available ViewResolver . use order Attribute sorting.   InternalResourceViewResolver Put last-->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1"></property>
        <property name="mediaTypes">
            <map>
                <!-- Tell the view parser that the returned type is json format -->
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
                <entry key="htm" value="text/htm" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <!-- ModelAndView The data in the becomes JSON -->
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
        <property name="ignoreAcceptHeader" value="true"></property>
    </bean>
    
   <!-- Defines the prefix of the file to jump to, and the view mode configuration-->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!-- I understand that the configuration here is automatically given to the back action Method of return The string, plus the prefix and suffix, becomes an available string url address -->  
        <property name="prefix" value="/WEB-INF/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
</beans>  

3.2. 2. Configure web XML file

The spring MVC Servlet is configured to complete the integration of spring MVC + Maven.

web.xml  

<?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"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    version="3.0">  
    <display-name>Archetype Created Web Application</display-name>  
    <!-- Spring and mybatis Configuration file for -->  
   <!--  <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring-mybatis.xml</param-value>  
    </context-param>   -->
    <!-- Coding filter -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <!-- Spring monitor -->  
   <!--  <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>   -->
    <!-- prevent Spring Memory overflow listener -->  
    <!-- <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  --> 
  
    <!-- Spring MVC servlet -->  
    <servlet>  
        <servlet-name>SpringMVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- Here you can configure*.do,corresponding struts Suffix habit -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  
  
</web-app>  

3.2. 3. Configuration of Log4j

In order to facilitate debugging, logs are generally used to output information. Log4j is an open source project of Apache. By using log4j, we can control that the destination of log information transmission is console, files, GUI components, even socket server, NT event recorder, UNIX Syslog daemon, etc; We can also control the output format of each log; By defining the level of each log information, we can control the log generation process in more detail.

The configuration of Log4j is simple and universal. A basic configuration is given below, and there is no need to make much adjustment in other projects. If you want to make adjustment or want to understand various configurations of Log4j, please refer to a blog post I reprint, which is very detailed: http://blog.csdn.net/zhshulin/article/details/37937365

The configuration file directory is given below:

log4j.properties

This code is by Java Architect must see network-Architecture sorting
log4j.rootLogger=INFO,Console,File  
#Define the log output destination as the console  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#You can flexibly specify the log output format. The following line specifies the specific format  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
  
#When the file size reaches the specified size, a new file is generated  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#Specify output directory  
log4j.appender.File.File = logs/ssm.log  
#Define maximum file size  
log4j.appender.File.MaxFileSize = 10MB  
# Output all logs. If it is replaced with DEBUG, it means that logs above DEBUG level are output  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  

3.2. 4. Using Jetty test

package com.javen.model;

public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    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 == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password="
                + password + ", age=" + age + "]";
    }
    
    
}
package com.javen.controller;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;
import com.javen.model.User;
  
  
@Controller  
@RequestMapping("/user")  
// /user/**
public class UserController {  
    private static Logger log=LoggerFactory.getLogger(UserController.class);
      
    
    // /user/test?id=1
    @RequestMapping(value="/test",method=RequestMethod.GET)  
    public String test(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user=null;
        if (userId==1) {
             user = new User();  
             user.setAge(11);
             user.setId(1);
             user.setPassword("123");
             user.setUserName("javen");
        }
       
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "index";  
    }  
}  

Enter in the browser: http://localhost/user/test?id=1

This completes the integration of spring MVC + Maven

3.3 integration of spring and MyBatis

Cancel 3.2 2 web. Annotated code in XML

3.3. 1. Create JDBC properties file

jdbc.properties (the file code is modified to utf-8)

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/maven
username=root
password=root
#Defines the number of initial connections  
initialSize=0  
#Define the maximum number of connections  
maxActive=20  
#Define maximum idle  
maxIdle=20  
#Define minimum idle  
minIdle=1  
#Define maximum wait time  
maxWait=60000  

The directory structure is

3.3. 2. Create spring mybatis XML configuration file

This file is used to complete the integration of spring and mybatis. There are not many lines of configuration, mainly automatic scanning, automatic injection and database configuration. The notes are also very detailed. Let's see.

spring-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:p="http://www.springframework.org/schema/p"  
    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-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- Automatic scanning -->  
    <context:component-scan base-package="com.javen" />  
    
    <!-- Import profile -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        <!-- Initialize connection size -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- Maximum number of connection pools -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- Connection pool maximum idle -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- Connection pool minimum idle -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- Gets the maximum connection wait time -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </bean>  
  
    <!-- spring and MyBatis Perfect integration, no need mybatis Configuration mapping file for -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- Automatic scanning mapping.xml file -->  
        <property name="mapperLocations" value="classpath:com/javen/mapping/*.xml"></property>  
    </bean>  
  
    <!-- DAO Package name of the interface, Spring The class under it is automatically found -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.javen.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
  
    <!-- (transaction management)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
  
</beans>  

3.4 JUnit test

After the above steps, we have completed the integration of Spring and mybatis, so we can write a piece of test code to try whether it is successful.

3.4. 1. Create test table

Since we need to test, we need to establish a test table in the database. The table is very simple. The SQL statement is:

-- ----------------------------
-- Table structure for `user_t`
-- ----------------------------
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(40) NOT NULL,
  `password` varchar(255) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES ('1', 'test', '345', '24');
INSERT INTO `user_t` VALUES ('2', 'javen', '123', '10');

3.4. 2. Automatic code creation with MyBatis Generator

Reference blog: http://blog.csdn.net/zhshulin/article/details/23912615

This can automatically create entity classes, MyBatis mapping files and DAO interfaces according to the table. Of course, I am used to changing the generated interface name to IUserDao instead of directly using the UserMapper generated by it. If you don't want trouble, you can't change it. When finished, copy the file to the project. As shown in the figure:

3.4. 3. Establish Service interface and implementation class

Specific contents are given below:

IUserService.jave

package com.javen.service;  

import com.javen.model.User;
  
  
public interface IUserService {  
    public User getUserById(int userId);  
}  

UserServiceImpl.java

package com.javen.service.impl;
import javax.annotation.Resource;  

import org.springframework.stereotype.Service;  
import com.javen.dao.IUserDao;
import com.javen.model.User;
import com.javen.service.IUserService;
  
  
@Service("userService")  
public class UserServiceImpl implements IUserService {  
    @Resource  
    private IUserDao userDao;  
    
    public User getUserById(int userId) {  
        // TODO Auto-generated method stub  
        return this.userDao.selectByPrimaryKey(userId);  
    }  
  
}  

3.4. 4. Create test class

The test class is established in src/test/java. The part commented out in the test class below is a general test method when Spring is not used; If Spring is used, you can use annotations to introduce configuration files and classes, and then inject service interface objects for testing.

If the test is successful, it means that Spring and Mybatis have been integrated successfully. The output information is printed to the console using Log4j.

package com.javen.testmybatis;

import javax.annotation.Resource;  

import org.apache.log4j.Logger;  
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
import com.alibaba.fastjson.JSON;  
import com.javen.model.User;
import com.javen.service.IUserService;
  
@RunWith(SpringJUnit4ClassRunner.class)     //Indicates that it inherits the SpringJUnit4ClassRunner class  
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})  
  
public class TestMyBatis {  
    private static Logger logger = Logger.getLogger(TestMyBatis.class);  
//  private ApplicationContext ac = null;  
    @Resource  
    private IUserService userService = null;  
  
//  @Before  
//  public void before() {  
//      ac = new ClassPathXmlApplicationContext("applicationContext.xml");  
//      userService = (IUserService) ac.getBean("userService");  
//  }  
  
    @Test  
    public void test1() {  
        User user = userService.getUserById(1);  
        // System.out.println(user.getUserName());  
        // logger.info("value:" + user.getUserName());  
        logger.info(JSON.toJSONString(user));  
    }  
}  

Test results

3.4. 5. Create UserController class

UserController.java} controller

package com.javen.controller;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.javen.model.User;
import com.javen.service.IUserService;
  
  
@Controller  
@RequestMapping("/user")  
// /user/**
public class UserController {  
    private static Logger log=LoggerFactory.getLogger(UserController.class);
     @Resource  
     private IUserService userService;     
    
    // /user/test?id=1
    @RequestMapping(value="/test",method=RequestMethod.GET)  
    public String test(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user=null;
        if (userId==1) {
             user = new User();  
             user.setAge(11);
             user.setId(1);
             user.setPassword("123");
             user.setUserName("javen");
        }
       
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "index";  
    }  
    
    
    // /user/showUser?id=1
    @RequestMapping(value="/showUser",method=RequestMethod.GET)  
    public String toIndex(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "showUser";  
    }  
    
 // /user/showUser2?id=1
    @RequestMapping(value="/showUser2",method=RequestMethod.GET)  
    public String toIndex2(@RequestParam("id") String id,Model model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "showUser";  
    }  
    
    
    // /user/showUser3/{id}
    @RequestMapping(value="/showUser3/{id}",method=RequestMethod.GET)  
    public String toIndex3(@PathVariable("id")String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.put("user", user);  
        return "showUser";  
    }  
    
 // /user/{id}
    @RequestMapping(value="/{id}",method=RequestMethod.GET)  
    public @ResponseBody User getUserInJson(@PathVariable String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return user;  
    }  
    
    // /user/{id}
    @RequestMapping(value="/jsontype/{id}",method=RequestMethod.GET)  
    public ResponseEntity<User>  getUserInJson2(@PathVariable String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return new ResponseEntity<User>(user,HttpStatus.OK);  
    } 
    
    //File upload
    @RequestMapping(value="/upload")
    public String showUploadPage(){
        return "user_admin/file";
    }
    
    @RequestMapping(value="/doUpload",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        if (!file.isEmpty()) {
            log.info("Process file:{}",file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
        return "succes";
    }
}  

3.4. 6. New jsp page

file.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Upload file</h1>
    <form method="post" action="/user/doUpload" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" value="Upload file"/>
        
    </form>
</body>
</html>

index.jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

showUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <title>test</title>  
  </head>  
    
  <body>  
    ${user.userName}  
  </body>  
</html>  

So far, the integration of Spring+SpingMVC+mybatis has been completed.

3.4. 7. Deployment project

Enter address: http://localhost/user/jsontype/2

Project download address: https://github.com/Javen205/SSM

Reference blog: http://blog.csdn.net/gebitan505/article/details/44455235

Added by neller on Mon, 20 Dec 2021 11:51:15 +0200