layout: post
author: zjhChester
header-img: img/post-bg-os-metro.jpg
catalog: true
tags:
- ssm integration
spring+springmvc+mybatis (ssm) integration
1. Preliminary preparation
1. Build maven project, check skeleton construction, check web app
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-S8LwyYnG-1580546011637)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570857284829.png))
2. Add a set of key value pairs in the place where maven is introduced: archetypecatalog internal
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-38vqSxA4-1580546011638)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570857482777.png))
3. Build pom coordinate dependency
<!--spring Framework core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--spring web core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--spring mvc core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
2. Construction of spring MVC mybatis configuration file
2.1. Project structure
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2blfghho-1580546011640) (/ mdimg / Spring + springmvc + mybatis% EF% BC% 88ssm% EF% BC% 89% E6% 95% B4% E5% 90% 88. Assets / 157085861777. PNG))
2.2.spring
1. Namespace:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
2. Annotation scanning:
It should be noted that we integrate the three frameworks. If we need to develop with spring annotation, we should avoid the Controller annotation in mvc framework, so we should add the corresponding non scanning configuration in the xml configuration file, as follows
applicationContext.xml
<!--Enable annotation scanning--> <context:component-scan base-package="cn.tfs"> <!--Packages not scanned--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan>
2.3.spring-mvc
1. Annotation scanning:
As above, the annotation that spring MVC needs to scan only includes the annotation of @ Controller, so we add filter in the scan
spring-mvc.xml
<!--Scan annotation--> <context:component-scan base-package="cn.tfs"> <!--To configure spring-mvc Notes to scan--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter> </context:component-scan>
2. View parser:
<!--jsp view resolver --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> <property name="contentType" value="text/html;charset=UTF-8"/> <property name="order" value="0" /> </bean>
3. Annotation support:
Because sometimes we need to use @ Response annotation to return string content to the request, then we may encounter Chinese problems, so here we add the corresponding code conversion bean when opening annotation support
<mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!--To configure@Response Annotation coding problem--> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/html;charset=utf-8"></property> </bean> </mvc:message-converters> </mvc:annotation-driven>
4. Static resource access mapping:
<mvc:default-servlet-handler/> <!--Conform to/js/**Matching rule requests,Map to directory/WEB-INF/js/lower--> <mvc:resources mapping="/js/**" location="WEB-INF/js/"/> <mvc:resources mapping="/img/**" location="WEB-INF/img/"/> <mvc:resources mapping="/css/**" location="WEB-INF/css/"/>
5.web.xml configuration:
Namespace of 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"
Note: if there is a red report, we will leave the filter in front of the controller
In addition, we also need to solve the problem of Chinese scrambling code of data transmitted from the front end ----- > filter
<!--Filter--> <filter> <filter-name>characterEncodingFilter</filter-name> <!--Character encoding filter to solve the problem of Chinese scrambling--> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
And the front controller of web.xml
<servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--Read profile read--> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring-mvc.xml</param-value> </init-param> <!--Load when the server is turned on--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
2.4.mybatis
The method of using properties to import parameters makes the code more readable
db.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/javaee?serverTimezone=GMT&useSSL=false&allowPublicKeyRetrieval=true username=root password=123
mybatisConfig.xml
<?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> <!-- 1,mybatis Use properties To bring in the outside properties Content of profile resource Introducing resources under classpath url Introduce resources under network path or disk path --> <properties resource="db.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- Configure database connection information --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="DaoMapper.xml"></mapper> <!--Form assembly of scanning package mapper--> <!--<package name="cn.tfs.yunge.dao"></package>--> </mappers> </configuration>
3. integration
3.1. Ensure that each frame can operate independently and normally
(write test program!!!)
3.2. Integrating spring,springmvc
1. First, make sure that the scan package in the application context.xml configuration file of spinning does exclude @ Controller
2. Ensure that the scan package in the spring-mvc configuration file spring-mvc.xml does contain only @ Controller
3. (important) in a web project, if we initiate a request, we are sure that web.xml will only parse to the configuration file of spring-mvc.xml
<!--Read profile read--> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring-mvc.xml</param-value> </init-param>
Therefore, we need to configure a spring listener in web.xml to load the spring configuration file applicationContext.xml when the server is turned on
<!--spring Listener default load WEB-INF/Lower applicationContext.xml file--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Set profile path--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param>
4. implementation:
UserServiceImpl.java
@Service("userService") public class UserServiceImpl implements UserService{ public List<User> findUser(User user) { System.out.println("Service findUser implement..."); return dao.findUser(user); } }
HelloController.java
@Controller public class HelloController { @Autowired private UserService userService; @RequestMapping("/1") public String index(){ User user = new User(); userService.findUser(user); return "index"; } }
test result
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2LQEAZTz-1580546011641)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570863946084.png))
3.3. Integrating spring mybatis
1. The principle of calling Dao in the business layer is the same. The only difference is that we use proxy Dao, which is an interface, so we need to find a way to assemble the implementation classes under the proxy into the IoC container
Let's look at the spring configuration file applicationContext.xml
<!--integration mybatis--> <!--Configure connection pool--> <!--Introduce db.properties Database configuration information--> <context:property-placeholder location="classpath*:db.properties"></context:property-placeholder> <bean id="pooledDataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!--Auto commit transaction--> <property name="defaultAutoCommit" value="true"></property> </bean> <!--To configure SQLSessionFactory factory--> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--Inject the above connection pool into the factory--> <property name="dataSource" ref="pooledDataSource"></property> <!--scanning mapper The package--> <property name="mapperLocations"> <list> <value>classpath*:cn/tfs/yunge/dao/*.xml</value> </list> </property> </bean> <!--To configure Dao Package of interface--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.tfs.yunge.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property> </bean>
After writing the above connection pool and other information, our mybatis global configuration file can be deleted. Previously, the db.properties file imported in mybatisConfig.xml file was imported into applicationContext.xml in the way of spring context
<context:property-placeholder location="classpath*:db.properties"></context:property-placeholder>
2. The above connection pool and SQLSessionFactory factory need to introduce two coordinate dependencies (jar packages) that spring MVC did not use before
2.1. Connection pool: transaction package tx and jdbc
<!--Transaction management core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency>
2.2. Configure SQLSessionFactory factory and Mapper package: org.mybatis package org.apache.ibatis.datasource.pooled.pooledatasource mybatis connection pool package
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
3.UserServiceImpl.java
@Service("userService") public class UserServiceImpl implements UserService { @Autowired private Dao dao; @Override public List<User> findUser(User user) { System.out.println("Service findUser implement..."); return dao.findUser(user); } @Override public int insertUser(User user) { System.out.println("Service insertUser implement..."); return dao.insertUser(user); }
HelloController.java
@Controller public class HelloController { @Autowired private UserService userService; @RequestMapping("/1") public String findUser(Model model){ User user = new User(); user.setUsername("zjh"); model.addAttribute("result", userService.findUser(user)); return "index"; } @RequestMapping("/2") public String insertUser(Model model){ User user = new User(); user.setUsername("zjh"); user.setPassword("123"); model.addAttribute("result",userService.insertUser(user)); return "index"; } }
Test:
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-G2Ybm11X-1580546011642)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570873585507.png))
Pits:
1.pom.xml coordinates:
Spring TX spring JDBC transaction management import, mybatis spring package import
2. It is better to add jdbc.xxx to the key of db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/javaee?serverTimezone=GMT&useSSL=false&allowPublicKeyRetrieval=true jdbc.username=root jdbc.password=123
3. The most problematic problem is java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout()Ljava/lang/Integer; Exception
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-bgaxcVg0-1580546011642)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570873725282.png))
The reason is the problem of the adaptation version. It took me an hour and a half... Manual depression
4. the last one is to add static resources of pom.xml
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources>
Otherwise, * mapper.xml or. properties cannot be found. This is the bold style to solve the exception of nested exception is org.apache.ibatis.binding.BindingExceptio