Common SSM integration methods
Seeing so many integration methods on the Internet, I'm really dazzled. I can't see that some materials are only integrating a certain part, or the integration method is too simple to be used in actual development. Next, I will also write an article on the integration method I usually use to write projects. First, I will record my integration template, and second, I will provide you with a reference idea.
Before explaining the integration idea, we will build a project so that we can carry out the following operations
1, Create project
Let's first create an environment to integrate the project, and then talk about how to integrate the three frameworks.
Create project
Bind maven
After clicking finish, we will modify the pom file of the project to the following structure:
<?xml version="1.0" encoding="UTF-8"?> <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> <packaging>war</packaging> <name>SSM_Template</name> <groupId>example</groupId> <artifactId>SSM_Template</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> </dependencies> </project>
Then modify the contents of the web.xml file as follows
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> </web-app>
Here, our project structure is as follows for the time being
2, Build spring MVC environment
To integrate these three frameworks, I start with Spring MVC, that is, to build the Spring MVC environment first. In fact, some people started from building Spring. There is no big difference between the two. The integration ideas are generally the same.
1. Import spring MVC related dependencies
First of all, if we want to use the related functions of spring MVC, we must first import the jar package related to spring MVC, otherwise we won't be able to play.
Add the following dependencies in the pom.xml file
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
2. Configure spring MVC related components
2.1. web.xml file
Front end controller
As we all know, the core of spring MVC is that before all requests initiated by the client browser reach the server, a front-end controller controls all requests and determines the request method in which controller the request is forwarded. Therefore, to use spring MVC, we must first configure the front-end controller in the web. XML file. If you want to ask why it is configured in the web.xml file, this front-end controller is called DispatcherServlet. It is a Servlet. Since it is a Servlet, it is the same as configuring a Servlet when I learned java web before. It is the same in web.xml.
Add the following contents to web.xml to configure the front-end controller
<servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
Spring MVC configuration file
Note that I did not specify where the springmvc configuration file is when configuring the front-end controller, so the springmvc configuration file is placed in the WEB-INF directory by default, and its name is the name of the front-end controller plus - servlet. In order to reduce the error rate, We will now create the springmvc configuration file in the WEB-INF directory, and the file name is [springdispatcher servlet servlet. XML].
I won't add the contents first
Chinese garbled code filter
Random code filtering is almost necessary. I don't think it needs to be too verbose to configure it. The only thing to pay attention to is that this filter must be placed before all filters, otherwise it can't achieve the filtering effect.
Add the following contents to the web.xml file
<filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Support restful style requests
If the i project development with small partners needs to use the restful style request method, a restful style support component HiddenHttpMethodFilter must be configured in the web.xml file, as follows:
<filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Remember what we just said? The Chinese garbled code Filter must be placed at the first Filter, so the Filter supporting restfull style needs to be placed after the Chinese garbled code Filter.
2.3. Corresponding contents of spring MVC configuration file
Scan Controller
In spring MVC, we no longer use Servlet for request processing, but use a Controller called Controller. Write the corresponding request method and request mapping here, and the browser's request can be correctly sent to the corresponding request method by the front-end Controller. However, if these controllers want to be found by the front-end Controller, they must be added to the container to be recognized. Therefore, we should use < / context: component scan > in the configuration file of spring MVC to scan these controllers, but note that if we use the following configuration method when scanning controllers
<context:component-scan base-package="SSM.Template"> </context:component-scan>
This configuration can indeed scan the Controller into the container, and it can be used correctly at present. However, don't forget that we now want to integrate the three frameworks of SSM. Now we use the above method to scan the components into the container, including all components under the Template package, including service s, bean s and so on, When configuring the spring container at that time, we will also scan components in the same way. Then there will be two same components in the container. The components used in our development are not the same component, nor are they single instance components, which will bring a lot of unnecessary trouble, such as the failure of our transaction control
Therefore, it is natural for spring to manage business-related component beans and spring MVC to manage Controller related beans. That is, use filters during scanning. In short, only the Controller controller is scanned in the spring MVC configuration file, and all components except the Controller are scanned in the spring configuration file. That is, the following should be written in the spring MVC configuration file
<context:component-scan base-package="SSM.Template" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
Release static resources
When configuring the front-end controller, the filtering rule is a slash /, which means to intercept all resources except those with. jsp suffix, that is, except jsp pages, requests for other resources, such as. html,. png and other static resources, will be intercepted by the front-end controller, and these static resources are originally processed by tomcat, Now the front-end controller intercepts the requests of these static resources, so tomcat cannot receive these static requests, so we cannot access these static resources. Therefore, we need to add the following content to the configuration file of spring MVC to tell tomcat that the resources that the front-end controller cannot process are processed by tomcat
<mvc:annotation-driven/> <mvc:default-servlet-handler/>
view resolver
I won't explain more about this. It's just a convenient tool. After configuring it, we don't need to have all the prefixes and suffixes in the request forwarding path in the request method every time. However, note that the request forwarding path decorated with forward, redirect and so on needs to write the full path.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean>
3. Page Test
The spring MVC configuration file is almost written. Now let's write some pages and request methods to test whether the environment is built or not!
3.1. Write a HelloController
@Controller public class HelloController { @RequestMapping("hello") public String hello( Model model ){ model.addAttribute("msg" ,"Hello, trendsetter"); return "success"; } }
3.2. Page preparation
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Success page</title> </head> <body> Information from the server: <br/> <h1>${msg}</h1> </body> </html>
file location
3.3. Configure tomcat
Start the server, because we didn't write an index.jsp home page, so the default interface after startup is like this
Don't worry about it. Of course, if you want to have a default interface, you can create an index.jsp page by yourself. Here I directly initiate the request,
http://localhost:8080/SSM_Template/hello
The following shows that our spring MVC environment has been built
3, Integrate Spring environment
OK, after completing the configuration of spring MVC, let's integrate it with spring.
3.1. Import spring dependency
Because we imported the following coordinates before, the corresponding spring package will also be imported
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
So we don't guide bags here
3.2. Create corresponding JavaBean s, services, etc
In order to be consistent with the JavaBeans used to integrate mybatis later, I now create a JavaBean related to my database table fields
JavaBean
@Component public class Book { private Integer id; private String name; private String author; private String price; private String sales; private String stock; private String img_path; //The corresponding get / set method and the parameterless constructor }
BookUservice
public interface BookService { public void deleteById(Integer id); }
BookServiceImpl
@Service public class BookServiceImpl implements BookService { /** * Simulated deletion of books * @param id Book id */ @Override public void deleteById(Integer id) { System.out.println("id by" + id +" Your book has been deleted....."); } }
3.3. spring configuration file
The corresponding business code is almost written. Now let's start writing the spring configuration file
Create a spring configuration file named spring.xml under the classpath (resources directory)
When writing the spring MVC configuration file, we said that the spring configuration file does not need to scan the Controller, so when scanning the configuration package, add the following contents to the spring.xml file
<context:component-scan base-package="SSM.Template"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
3.4. Testing spring environment
Reference the test dependency and write a test method to see if our component has been scanned into the spring container
Test dependency
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency>
test method
@Test public void test1(){ ClassPathXmlApplicationContext ioc =new ClassPathXmlApplicationContext("spring.xml"); String[] beanDefinitionNames = ioc.getBeanDefinitionNames(); for (String name : beanDefinitionNames) { System.out.println(name); } }
The test results are shown as follows, which shows that the configuration content in our spring.xml file has taken effect, and the Controller has not been scanned, which is exactly what we want
3.5 integration of spring and spring MVC
Now that the spring and spring MVC environments have been set up, let's begin to combine them. So what is the success of integration? Making this clear will have a great effect on us. First, the function of spring is to reduce coupling and reverse control; The role of our spring MVC is to provide a more convenient way to process requests instead of servlet s. The popular point is that the components configured in the spring container should be able to be used in the spring MVC components, that is, BookService should be able to complete DI injection in the Controller.
Because our project is deployed under tomcat, that is, our server is Tomcat. When we start the Tomcat server, we will only start our spring mvc container, not our spring container, because when we configure the front-end controller in the web.xml file, the front-end controller will load the spring mvc file in the default location by default instead of our spring configuration file, That is to say, our spring container did not start. So how can the Tomcat container be loaded when it is started, just like the spring mvc configuration file? Is there anything like the front controller in mvc in our spring?
Although it is not available in spring, we can use the Lister listener in tomcat to initialize and load our spring container, that is, in addition to configuring spring MVC in webx.xml file, we also need to add the following contents to load our spring container.
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
3.6. Test the environment after spring MVC and spring integration
Add the following request method to the controller
@Autowired BookService bookService; @RequestMapping("hello2") public String hello2( Model model ){ bookService.deleteById(5); model.addAttribute("msg","Hello, Li Yinhe!"); return "success"; }
After starting the server, initiate the request
http://localhost:8080/SSM_Template/hello2
Successfully jump to page
Moreover, the server side outputs the following contents, indicating that our Controller can normally DI inject components into our spring container. Integration successful!
4, Integrate Mybatis
Before integrating Mybatis, let's talk about the databases and data tables that will be used
Here, I directly use the previously created Book as the JavaBean for testing
1. Import dependent coordinates
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
Similarly, the goal of integrating mybatis is to use spring inversion control to inject DI into the corresponding Mapper interface, that is, directly use Mapper in ServiceImpl.
2. Create dao layer file
BookDao interface
import SSM.Template.bean.Book; import org.springframework.stereotype.Repository; @Repository public interface BookDao { public Book getBookById(Integer id); }
Corresponding mapper mapping file
<?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="SSM.Template.dao.BookDao"> <select id="getBookById" resultType="SSM.Template.bean.Book"> select * from t_book where id=#{id} </select> </mapper>
When we learned about mybatis before, we all knew that mybatis can help us generate a proxy object using the dao interface. This proxy object helps us to add, delete, modify and query. We can also put the proxy object into the IOC container, so that the service can get the object for DI injection. Integrating mybatis into the spring container is actually transferring the configuration content of mybatis to the spring configuration file, so that the container can get the components of mybatis and realize DI injection.
3. Configure the components related to the (mybatis framework) database in the spring configuration file
Create the dbconfig.properties file under the classpath
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/blog jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=xxxxx
Add the following content to the spring configuration file
<content:property-placeholder location="classpath:dbconfig.properties"/> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="pooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> <!-- appoint mybatis Location of global profile --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <!-- <!– appoint mybatis,mapper File location –>--> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScanner"> <property name="basePackage" value="com.mdy.blog.dao"/> </bean>
4. Testing
Service interface add method
import SSM.Template.bean.Book; public interface BookService { public void deleteById(Integer id); public Book getBookById(Integer id); }
BookServiceImpl implementation class
package SSM.Template.service.impl; import SSM.Template.bean.Book; import SSM.Template.dao.BookDao; import SSM.Template.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookServiceImpl implements BookService { /** * Simulated deletion of books * @param id Book id */ @Override public void deleteById(Integer id) { System.out.println("id by" + id +" Your book has been deleted....."); } @Autowired BookDao bookDao; @Override public Book getBookById(Integer id) { return bookDao.getBookById(id); } }
Controller add request method
@Autowired BookService bookService; @RequestMapping("hello2") public String hello2( Model model ){ Book bookById = bookService.getBookById(5); System.out.println(bookById); model.addAttribute("msg","Hello, Li Yinhe!"); return "success"; }
Start the server to access the request
http://localhost:8080/SSM_Template/hello2
Page Jump succeeded
The server outputs the corresponding database information
It shows that spring simply integrates mybatis successfully!!!