SSM Framework Integration

Reprint: http://blog.csdn.net/zhshulin


Using SSM( spring Spring MVC, Spring MVC and Mymatis have been more than three months. There are no technical difficulties in the project. Based on the existing technology, we can achieve the desired functions. Of course, there must be many areas for improvement. The integration process of SSM was not recorded before. This time, it was rebuilt based on a small project of its own, and it was better than the project. In the past, the process and methods of solving problems were not recorded in time. I will reorganize and share them when I meet in my own small projects. This time, let's talk about the integration process of the three frameworks. Personally, I think it is not difficult to use the framework. The key is to understand its ideas, which is very helpful for us to improve our programming level. Nevertheless, if you can't use it, talking about ideas becomes talking about soldiers on paper!!! First technology, then thought. True knowledge comes from practice. (Blog addresses can be viewed through image watermarking)


1. Basic concepts


1.1,Spring


Spring is an open source framework, and Spring was a lightweight one that emerged in 2003 Java The development framework 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 accomplish things previously only possible with EJB s. However, Spring's use is not limited to server-side development. From simplicity to feasibility test From a sexual and loosely coupled perspective, any Java application can benefit from Spring. In short, Spring is a lightweight control inversion (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 is separated Controller Model object The separation of roles of dispatchers and handler objects makes them easier to customize.


1.3,MyBatis


MyBatis apache An open source project iBatis In 2010, the project was moved from apache software foundation to google code and renamed MyBatis. MyBatis is a Java-based Persistence Layer Framework. iBATIS Persistence Layer The framework includes SQL Maps and Data Access Objects (DAO) MyBatis, which eliminates manual settings of almost all JDBC codes and parameters and retrieval of result sets. MyBatis uses simple XML or annotations to configure and map interfaces and Java POJOs (Plain Old Java Objects, plain Java objects) to original mappings data base Records in.



2. Construction of Development Environment



If necessary, refer to the previous blog: http://blog.csdn.net/zhshulin/article/details/30779873



3. Maven Web Project Creation


If necessary, refer to the previous blog: http://blog.csdn.net/zhshulin/article/details/37921705



4. SSM Integration

      

The integration of the three frameworks is introduced below. For the construction of the environment and the creation of the project, see the above blog. This integration I divided into two configuration files, spring-mybatis.xml, including spring and mybatis configuration files, and a spring-mvc configuration file, in addition to two resource files: jdbc. properties and log4j.properties. The full directory structure is as follows (the source code download address is attached at the end, and it is not recommended to use the source code directly because the tutorial already has all the code):


The frameworks used are newer versions:

       Spring 4.0.2 RELEASE

       Spring MVC 4.0.2 RELEASE

       MyBatis 3.2.6


4.1. Maven introduces the required JAR packages

For the convenience of not introducing JAR packages when I say later, I will give all the JAR packages needed directly. These are basic JAR packages. Every package has comments on what it does, so I won't say much more.

pom.xml

  1. <properties>  
  2.         <!-- spring version number -->  
  3.         <spring.version>4.0.2.RELEASE</spring.version>  
  4.         <!-- mybatis version number -->  
  5.         <mybatis.version>3.2.6</mybatis.version>  
  6.         <!-- log4j Log File Management Package Version -->  
  7.         <slf4j.version>1.7.7</slf4j.version>  
  8.         <log4j.version>1.2.17</log4j.version>  
  9.     </properties>  
  10.   
  11.     <dependencies>  
  12.         <dependency>  
  13.             <groupId>junit</groupId>  
  14.             <artifactId>junit</artifactId>  
  15.             <version>4.11</version>  
  16.             <!-- Represents that the package was introduced at development time and will not be loaded at publication time. -->  
  17.             <scope>test</scope>  
  18.         </dependency>  
  19.         <!-- spring Core package -->  
  20.         <dependency>  
  21.             <groupId>org.springframework</groupId>  
  22.             <artifactId>spring-core</artifactId>  
  23.             <version>${spring.version}</version>  
  24.         </dependency>  
  25.   
  26.         <dependency>  
  27.             <groupId>org.springframework</groupId>  
  28.             <artifactId>spring-web</artifactId>  
  29.             <version>${spring.version}</version>  
  30.         </dependency>  
  31.         <dependency>  
  32.             <groupId>org.springframework</groupId>  
  33.             <artifactId>spring-oxm</artifactId>  
  34.             <version>${spring.version}</version>  
  35.         </dependency>  
  36.         <dependency>  
  37.             <groupId>org.springframework</groupId>  
  38.             <artifactId>spring-tx</artifactId>  
  39.             <version>${spring.version}</version>  
  40.         </dependency>  
  41.   
  42.         <dependency>  
  43.             <groupId>org.springframework</groupId>  
  44.             <artifactId>spring-jdbc</artifactId>  
  45.             <version>${spring.version}</version>  
  46.         </dependency>  
  47.   
  48.         <dependency>  
  49.             <groupId>org.springframework</groupId>  
  50.             <artifactId>spring-webmvc</artifactId>  
  51.             <version>${spring.version}</version>  
  52.         </dependency>  
  53.         <dependency>  
  54.             <groupId>org.springframework</groupId>  
  55.             <artifactId>spring-aop</artifactId>  
  56.             <version>${spring.version}</version>  
  57.         </dependency>  
  58.   
  59.         <dependency>  
  60.             <groupId>org.springframework</groupId>  
  61.             <artifactId>spring-context-support</artifactId>  
  62.             <version>${spring.version}</version>  
  63.         </dependency>  
  64.   
  65.         <dependency>  
  66.             <groupId>org.springframework</groupId>  
  67.             <artifactId>spring-test</artifactId>  
  68.             <version>${spring.version}</version>  
  69.         </dependency>  
  70.         <!-- mybatis Core package -->  
  71.         <dependency>  
  72.             <groupId>org.mybatis</groupId>  
  73.             <artifactId>mybatis</artifactId>  
  74.             <version>${mybatis.version}</version>  
  75.         </dependency>  
  76.         <!-- mybatis/spring package -->  
  77.         <dependency>  
  78.             <groupId>org.mybatis</groupId>  
  79.             <artifactId>mybatis-spring</artifactId>  
  80.             <version>1.2.2</version>  
  81.         </dependency>  
  82.         <!-- Import java ee jar package -->  
  83.         <dependency>  
  84.             <groupId>javax</groupId>  
  85.             <artifactId>javaee-api</artifactId>  
  86.             <version>7.0</version>  
  87.         </dependency>  
  88.         <!-- Import Mysql Database Links jar package -->  
  89.         <dependency>  
  90.             <groupId>mysql</groupId>  
  91.             <artifactId>mysql-connector-java</artifactId>  
  92.             <version>5.1.30</version>  
  93.         </dependency>  
  94.         <!-- Import dbcp Of jar Packet, used in the ____________ applicationContext.xml Configure database in -->  
  95.         <dependency>  
  96.             <groupId>commons-dbcp</groupId>  
  97.             <artifactId>commons-dbcp</artifactId>  
  98.             <version>1.2.2</version>  
  99.         </dependency>  
  100.         <!-- JSTL Label class -->  
  101.         <dependency>  
  102.             <groupId>jstl</groupId>  
  103.             <artifactId>jstl</artifactId>  
  104.             <version>1.2</version>  
  105.         </dependency>  
  106.         <!-- Log File Management Package -->  
  107.         <!-- log start -->  
  108.         <dependency>  
  109.             <groupId>log4j</groupId>  
  110.             <artifactId>log4j</artifactId>  
  111.             <version>${log4j.version}</version>  
  112.         </dependency>  
  113.           
  114.           
  115.         <!-- Format objects to facilitate log output -->  
  116.         <dependency>  
  117.             <groupId>com.alibaba</groupId>  
  118.             <artifactId>fastjson</artifactId>  
  119.             <version>1.1.41</version>  
  120.         </dependency>  
  121.   
  122.   
  123.         <dependency>  
  124.             <groupId>org.slf4j</groupId>  
  125.             <artifactId>slf4j-api</artifactId>  
  126.             <version>${slf4j.version}</version>  
  127.         </dependency>  
  128.   
  129.         <dependency>  
  130.             <groupId>org.slf4j</groupId>  
  131.             <artifactId>slf4j-log4j12</artifactId>  
  132.             <version>${slf4j.version}</version>  
  133.         </dependency>  
  134.         <!-- log end -->  
  135.         <!-- Reflect JSON -->  
  136.         <dependency>  
  137.             <groupId>org.codehaus.jackson</groupId>  
  138.             <artifactId>jackson-mapper-asl</artifactId>  
  139.             <version>1.9.13</version>  
  140.         </dependency>  
  141.         <!-- Upload component packages -->  
  142.         <dependency>  
  143.             <groupId>commons-fileupload</groupId>  
  144.             <artifactId>commons-fileupload</artifactId>  
  145.             <version>1.3.1</version>  
  146.         </dependency>  
  147.         <dependency>  
  148.             <groupId>commons-io</groupId>  
  149.             <artifactId>commons-io</artifactId>  
  150.             <version>2.4</version>  
  151.         </dependency>  
  152.         <dependency>  
  153.             <groupId>commons-codec</groupId>  
  154.             <artifactId>commons-codec</artifactId>  
  155.             <version>1.9</version>  
  156.         </dependency>  
  157.           
  158.           
  159.     </dependencies>  

4.2. Integration of Spring and MyBatis

After all the required JAR packages are introduced, the integration of Spring and MyBatis is carried out first, and then the JUnit test is carried out. First, a project structure diagram is shown.


4.2.1. Establishing JDBC Property File

jdbc.properties (file code changed to utf-8)

  1. driver=com.mysql.jdbc.Driver  
  2. url=jdbc:mysql://10.221.10.111:8080/db_zsl  
  3. username=demao  
  4. password=demao  
  5. #Define the number of initial connections
  6. initialSize=0  
  7. #Define the maximum number of connections
  8. maxActive=20  
  9. #Define maximum idleness
  10. maxIdle=20  
  11. #Define minimum idleness
  12. minIdle=1  
  13. #Define the longest waiting time.
  14. maxWait=60000  

4.2.2. Establish spring-mybatis.xml configuration file

This file is used to integrate spring and mybatis. There are not many lines of configuration, the main thing is automatic scanning, automatic injection, configuration database. The annotations are also very detailed, you can see by looking at them.

spring-mybatis.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.                         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
  8.                         http://www.springframework.org/schema/context    
  9.                         http://www.springframework.org/schema/context/spring-context-3.1.xsd    
  10.                         http://www.springframework.org/schema/mvc    
  11.                         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
  12.     <!-- Automatic Scanning -->  
  13.     <context:component-scan base-package="com.cn.hnust" />  
  14.     <!-- Introducing configuration files -->  
  15.     <bean id="propertyConfigurer"  
  16.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  17.         <property name="location" value="classpath:jdbc.properties" />  
  18.     </bean>  
  19.   
  20.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
  21.         destroy-method="close">  
  22.         <property name="driverClassName" value="${driver}" />  
  23.         <property name="url" value="${url}" />  
  24.         <property name="username" value="${username}" />  
  25.         <property name="password" value="${password}" />  
  26.         <!-- Initialize connection size -->  
  27.         <property name="initialSize" value="${initialSize}"></property>  
  28.         <!-- Maximum number of connection pools -->  
  29.         <property name="maxActive" value="${maxActive}"></property>  
  30.         <!-- Maximum idleness of connection pool -->  
  31.         <property name="maxIdle" value="${maxIdle}"></property>  
  32.         <!-- Connection pool minimum idleness -->  
  33.         <property name="minIdle" value="${minIdle}"></property>  
  34.         <!-- Get the maximum connection waiting time -->  
  35.         <property name="maxWait" value="${maxWait}"></property>  
  36.     </bean>  
  37.   
  38.     <!-- spring and MyBatis Perfect integration, no need mybatis Configuration mapping file -->  
  39.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  40.         <property name="dataSource" ref="dataSource" />  
  41.         <!-- Automatic Scanning mapping.xml file -->  
  42.         <property name="mapperLocations" value="classpath:com/cn/hnust/mapping/*.xml"></property>  
  43.     </bean>  
  44.   
  45.     <!-- DAO The package name of the interface, Spring The following classes are automatically found -->  
  46.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  47.         <property name="basePackage" value="com.cn.hnust.dao" />  
  48.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
  49.     </bean>  
  50.   
  51.     <!-- (transaction management)transaction manager, use JtaTransactionManager for global tx -->  
  52.     <bean id="transactionManager"  
  53.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  54.         <property name="dataSource" ref="dataSource" />  
  55.     </bean>  
  56.   
  57. </beans>  


Configuration of 4.2.3 and Log4j


In order to facilitate debugging, log is usually used to output information. Log4j is Apache An open source project that we can control by using Log4j Journal The destination of information transmission is Console Documents, GUI Components, even socket servers, NT Event logger, UNIX SyslogDaemon process We can also control the output format of each log; by defining the level of each log information, we can control the generation process of the log more carefully.

Log4j's configuration is very simple and general. Here's a basic configuration. It doesn't need much adjustment to change to other projects. If you want to adjust or understand the various configurations of Log4j, refer to a blog post I reprinted. It's very detailed:

http://blog.csdn.net/zhshulin/article/details/37937365

The following is the configuration file directory:


log4j.properties

  1. #Define LOG output level
  2. log4j.rootLogger=INFO,Console,File  
  3. #Define the log output destination as the console
  4. log4j.appender.Console=org.apache.log4j.ConsoleAppender  
  5. log4j.appender.Console.Target=System.out  
  6. #You can specify the log output format flexibly. The next line specifies the specific format.
  7. log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
  8. log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
  9.   
  10. #A new file is generated when the file size reaches the specified size.
  11. log4j.appender.File = org.apache.log4j.RollingFileAppender  
  12. #Designated output directory
  13. log4j.appender.File.File = logs/ssm.log  
  14. #Define the maximum file size
  15. log4j.appender.File.MaxFileSize = 10MB  
  16. #Output logs, if replaced by DEBUG, indicate output logs above DEBUG level.
  17. log4j.appender.File.Threshold = ALL  
  18. log4j.appender.File.layout = org.apache.log4j.PatternLayout  
  19. log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  

4.2.4, JUnit test


After the above steps (4.2.2, log4j doesn't match or affect), we have completed the integration of Spring and mybatis, so that we can write a test code to see if it's successful.



4.2.4.1. Create test tables

Since we need to test, then we need to build a test table in the database. This table is very simple. The SQL statement is as follows:

  1. DROP TABLE IF EXISTS `user_t`;  
  2.   
  3. CREATE TABLE `user_t` (  
  4.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  5.   `user_name` varchar(40) NOT NULL,  
  6.   `passwordvarchar(255) NOT NULL,  
  7.   `age` int(4) NOT NULL,  
  8.   PRIMARY KEY (`id`)  
  9. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  
  10.   
  11. /*Data for the table `user_t` */  
  12.   
  13. insert  into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'test','sfasgfaf',24);  

4.2.4.2. Automatically create code using MyBatis Generator

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


This automatically creates entity classes, MyBatis mapping files, and DAO interfaces based on tables. Of course, I'm used to changing the name of the generated interface to IUserDao instead of directly using it to generate UserMapper. If you don't want to be in trouble, you can do nothing about it. Copy the file to the project after completion. As shown in the figure:

4.2.4.3. Establishing Service Interface and Implementation Class

Directory structure:


Specific contents are given below:

IUserService.jave

  1. package com.cn.hnust.service;  
  2.   
  3. import com.cn.hnust.pojo.User;  
  4.   
  5. public interface IUserService {  
  6.     public User getUserById(int userId);  
  7. }  

UserServiceImpl.java

  1. package com.cn.hnust.service.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import com.cn.hnust.dao.IUserDao;  
  8. import com.cn.hnust.pojo.User;  
  9. import com.cn.hnust.service.IUserService;  
  10.   
  11. @Service("userService")  
  12. public class UserServiceImpl implements IUserService {  
  13.     @Resource  
  14.     private IUserDao userDao;  
  15.     @Override  
  16.     public User getUserById(int userId) {  
  17.         // TODO Auto-generated method stub  
  18.         return this.userDao.selectByPrimaryKey(userId);  
  19.     }  
  20.   
  21. }  

4.2.4.4. Establishing test classes

The test class is built in src/test/java. The annotated part of the test class below is a test method in general when Spring is not used. If Spring is used, the configuration file and class can be introduced by annotation, and then the service interface object can be injected into the test.

If the test is successful, Spring and Mymatis have been integrated successfully. The output information is printed to the console by Log4j.


  1. package org.zsl.testmybatis;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.apache.log4j.Logger;  
  6. import org.junit.Before;  
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11. import org.springframework.test.context.ContextConfiguration;  
  12. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  13.   
  14. import com.alibaba.fastjson.JSON;  
  15. import com.cn.hnust.pojo.User;  
  16. import com.cn.hnust.service.IUserService;  
  17.   
  18. @RunWith(SpringJUnit4ClassRunner.class)     //Represents inheritance of the Spring JUnit4ClassRunner class  
  19. @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})  
  20.   
  21. public class TestMyBatis {  
  22.     private static Logger logger = Logger.getLogger(TestMyBatis.class);  
  23. //  private ApplicationContext ac = null;  
  24.     @Resource  
  25.     private IUserService userService = null;  
  26.   
  27. //  @Before  
  28. //  public void before() {  
  29. //      ac = new ClassPathXmlApplicationContext("applicationContext.xml");  
  30. //      userService = (IUserService) ac.getBean("userService");  
  31. //  }  
  32.   
  33.     @Test  
  34.     public void test1() {  
  35.         User user = userService.getUserById(1);  
  36.         // System.out.println(user.getUserName());  
  37.         //logger.info("value:"+user.getUserName()));  
  38.         logger.info(JSON.toJSONString(user));  
  39.     }  
  40. }  

Test results:



So far, the integration of Spring and mybatis is completed, and the integration of Spring MVC is continuing below.


4.3. Integrating Spring MVC

The above two frameworks have been integrated. Spring MVC's configuration files are placed separately and then integrated in web.xml.

4.3.1, configure spring-mvc.xml

The annotations in the configuration are also very detailed, let's not say here, mainly the automatic scanning controller, view mode, annotation start three.

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.                         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
  8.                         http://www.springframework.org/schema/context    
  9.                         http://www.springframework.org/schema/context/spring-context-3.1.xsd    
  10.                         http://www.springframework.org/schema/mvc    
  11.                         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
  12.     <!-- Scanning the package automatically SpringMVC Think the package is used.@controller The annotated class is the controller -->  
  13.     <context:component-scan base-package="com.cn.hnust.controller" />  
  14.     <!--avoid IE implement AJAX When, return JSON Download file appears -->  
  15.     <bean id="mappingJacksonHttpMessageConverter"  
  16.         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
  17.         <property name="supportedMediaTypes">  
  18.             <list>  
  19.                 <value>text/html;charset=UTF-8</value>  
  20.             </list>  
  21.         </property>  
  22.     </bean>  
  23.     <!-- start-up SpringMVC Annotation function to complete requests and annotations POJO Mapping of -->  
  24.     <bean  
  25.         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  26.         <property name="messageConverters">  
  27.             <list>  
  28.                 <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON Converter -->  
  29.             </list>  
  30.         </property>  
  31.     </bean>  
  32.     <!-- Define the prefix and suffix of the jumped file ,View mode configuration-->  
  33.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  34.         <!-- The configuration here is automatic to the back. action Method return With prefix and suffix, the string becomes a Available url address -->  
  35.         <property name="prefix" value="/WEB-INF/jsp/" />  
  36.         <property name="suffix" value=".jsp" />  
  37.     </bean>  
  38.       
  39.     <!-- Configuration file upload, if not using file upload can not be configured, of course, if not, then the configuration file does not need to introduce the upload component package. -->  
  40.     <bean id="multipartResolver"    
  41.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
  42.         <!-- Default encoding -->  
  43.         <property name="defaultEncoding" value="utf-8" />    
  44.         <!-- Maximum file size -->  
  45.         <property name="maxUploadSize" value="10485760000" />    
  46.         <!-- Maximum in memory -->  
  47.         <property name="maxInMemorySize" value="40960" />    
  48.     </bean>   
  49.   
  50. </beans>  

4.3.2. Configure the web.xml file

The introduction of spring-mybatis.xml and the configuration of spring-mvc Servlet s are for SSM integration. The previous two framework integration does not require any configuration here. Configuration is also annotated in detail, with little explanation.


web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.     version="3.0">  
  6.     <display-name>Archetype Created Web Application</display-name>  
  7.     <!-- Spring and mybatis Configuration file -->  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>classpath:spring-mybatis.xml</param-value>  
  11.     </context-param>  
  12.     <!-- Coding filter -->  
  13.     <filter>  
  14.         <filter-name>encodingFilter</filter-name>  
  15.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  16.         <async-supported>true</async-supported>  
  17.         <init-param>  
  18.             <param-name>encoding</param-name>  
  19.             <param-value>UTF-8</param-value>  
  20.         </init-param>  
  21.     </filter>  
  22.     <filter-mapping>  
  23.         <filter-name>encodingFilter</filter-name>  
  24.         <url-pattern>/*</url-pattern>  
  25.     </filter-mapping>  
  26.     <!-- Spring Monitor -->  
  27.     <listener>  
  28.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  29.     </listener>  
  30.     <!-- Prevent Spring Memory overflow listener -->  
  31.     <listener>  
  32.         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  33.     </listener>  
  34.   
  35.     <!-- Spring MVC servlet -->  
  36.     <servlet>  
  37.         <servlet-name>SpringMVC</servlet-name>  
  38.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  39.         <init-param>  
  40.             <param-name>contextConfigLocation</param-name>  
  41.             <param-value>classpath:spring-mvc.xml</param-value>  
  42.         </init-param>  
  43.         <load-on-startup>1</load-on-startup>  
  44.         <async-supported>true</async-supported>  
  45.     </servlet>  
  46.     <servlet-mapping>  
  47.         <servlet-name>SpringMVC</servlet-name>  
  48.         <!-- Here you can configure it to*.do,Corresponding struts Suffix Habits -->  
  49.         <url-pattern>/</url-pattern>  
  50.     </servlet-mapping>  
  51.     <welcome-file-list>  
  52.         <welcome-file>/index.jsp</welcome-file>  
  53.     </welcome-file-list>  
  54.   
  55. </web-app>  

4.3.3. Testing

At this point, the integration of the three main frameworks of SSM has been completed. Next, test it. If it succeeds, congratulate you. If it fails, continue debugging. As a programmer, you are fighting against BUG all the time.


4.3.3.1. New jsp page


showUser.jsp This page only outputs the user name to complete a complete simple process.

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4.   <head>  
  5.     <title>test</title>  
  6.   </head>  
  7.     
  8.   <body>  
  9.     ${user.userName}  
  10.   </body>  
  11. </html>  

4.3.3.2. Establish UserController class

UserController.java Controller

  1. package com.cn.hnust.controller;  
  2.   
  3. import javax.annotation.Resource;  
  4. import javax.servlet.http.HttpServletRequest;  
  5.   
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.Model;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9.   
  10. import com.cn.hnust.pojo.User;  
  11. import com.cn.hnust.service.IUserService;  
  12.   
  13. @Controller  
  14. @RequestMapping("/user")  
  15. public class UserController {  
  16.     @Resource  
  17.     private IUserService userService;  
  18.       
  19.     @RequestMapping("/showUser")  
  20.     public String toIndex(HttpServletRequest request,Model model){  
  21.         int userId = Integer.parseInt(request.getParameter("id"));  
  22.         User user = this.userService.getUserById(userId);  
  23.         model.addAttribute("user", user);  
  24.         return "showUser";  
  25.     }  
  26. }  

4.3.3.3. Deployment projects

Enter address: localhost:8080 / project name / user/showUser?id=1

So far, the integration of the three frameworks of SSM has been completed, and other functions can be added on this basis.


Keywords: Spring Mybatis log4j xml

Added by edevil on Fri, 21 Jun 2019 03:26:13 +0300