Create projects and integrate ideas into the SSM framework
Create a project
Because it will be configured laterspringMVC
, so useIDEA
theweb
Skeleton create amaven
The project.
Create the project directory as follows, and the packages and files required for the project have been manually created:
In the figure above, application. XML is the Spring configuration file, log4j is the logging configuration file, and SpringMVC.xml is the springMVC configuration file
Configure the required dependencies in the POM.xml file, as shown below for the entire project.
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hust.demo-ssm</groupId> <artifactId>demo</artifactId> <version>1.0 the SNAPSHOT</version> <packaging>war</packaging> <name>demo Maven Webapp</name> <! -- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.2. RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</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-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</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>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <! -- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</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 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency> </dependencies> <build> <finalName>demo</finalName> <pluginManagement><! -- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <! -- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project> Copy the code
So at this point, the skeleton of the project is built, the project’s dependencies have been imported, and then introduce the integration idea.
Second, SSM integration ideas
For purposes of integration, the Service layer needs to be able to invoke dao layer methods through dependency injection and the Controller layer needs to invoke Service layer methods through dependency injection. So, the basic idea of integration is to use Spring to integrate MyBatis with springMVC.
Mybatis configuration
First, let’s configure the MyBatis framework.
Create a databasedemo_ssm
And createaccount
table
The SQL statement is as follows:
CREATE DATABASE `demo_ssm`; USE `demo_ssm`; DROP TABLE IF EXISTS `account`; CREATE TABLE `account`( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(32), `money` DOUBLE, PRIMARY KEY(`id`) )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO ` account ` (` name `, ` money `) VALUES (' zhao, 99999.99), (11111.1), 'zhang mowgli, (' wood wan qing, 22222.22);Copy the code
Create an account entity class
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
//getter and setter
//toString } Copy the code
3. Develop the persistence layer interface with annotations
package com.hust.dao;
public interface IAccountDao {
@Select("select * from account")
public List<Account> findAllAccount(a); } Copy the code
At this point Mybatis has been configured, the data source has not been configured yet, we will wait until the integration of Spring to configure and test.
Spring configures and integrates Mybatis
Spring configuration
The applicationContext. XML file now configures:
<beans xmlns="http://www.springframework.org/schema/beans" 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/context http://www.springframework.org/schema/context/spring-context.xsd">
<! -- Configure scan --> <context:component-scan base-package="com.hust"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans> Copy the code
Note:
Autowiring requires scanning for annotations in the package, so configure to enable annotation scanning. There are two ways to enable annotation scanning:
. The similarities and differences are as follows:
: Annotation scanning is for beans that have already been registered in the Spring container
: not only has all the functionality of
, but also can scan the corresponding bean under the specified package
Spring integration with Mybatis
Analysis of ideas:
Mybatis framework can automatically generate a proxy object, so the persistence layer, we only write an interface and annotations, the specific implementation class is by the framework to help us to complete, the database CRUD is also achieved through this proxy object. So, as long as we can store the generated proxy object in the container and let the Spring framework control it, the integration is successful.
Another key point is that Mybatis framework uses SqlSessionFactory factory instance to create SqlSession instance, from which we can operate on the database.
In short, the key to Spring’s Mybatis integration is to enable the container to control the SqlSessionFactoryBean class.
Specific configuration
The specific configuration is divided into three parts:
1. Configure connection pool 2. Configure sqlSession Factory class 3. Configure a scanner that scans packets
Therefore, the configuration is as follows:
<beans xmlns="http://www.springframework.org/schema/beans" 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/context http://www.springframework.org/schema/context/spring-context.xsd">
<! -- Configure scan --> <context:component-scan base-package="com.hust"> </context:component-scan> <! -- Configure data source --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///demo_ssm"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <! SqlSession factory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <! -- Configure scanned packets --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.hust.dao"/> </bean> </beans> Copy the code
With this configuration, the Spring container can create the sqlSession factory class. Add the @Repository annotation to the IAccountDao, and the proxy object for the AccountDao interface can be container-managed and consolidated. Let’s test with a test class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class SpringTest {
@Autowired
private IAccountDao accountDao; @Test public void testSpring(a){ List<Account> accounts = accountDao.findAllAccount(); for (Account account:accounts ) { System.out.println(account); } } } Copy the code
The results are as follows:
Account{id=1, name='zhao', money = 99999.99}Account{id=2, name='Zhang Wuji', money = 11111.1}Account{id=3, name='Mu Wan Qing', money = 22222.22}Copy the code
All accounts have been successfully queried, indicating that dependency injection can be implemented through the container. This indicates that Spring and MyBatis have been configured and integrated successfully.
Spring uses @runwith and @contextConfiguration to integrate junit PS: To enable XML file configuration with annotations, add the mapperLocations configuration when configuring the sqlSession factory in applicationContext.xml as follows:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<! -- Automatically scan mapping.xml file --> <property name="mapperLocations" value="classpath*:mapper/*.xml"></property>
</bean>
Copy the code
For springMVC configuration
1. Configuration web. XML
The SpringMVC framework is designed around the DispatcherServlet, which handles all HTTP requests and responses. So we need to configure the web.xml file to map the requests we want the DispatcherServlet to handle.
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>demo</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> Copy the code
Obviously, you need to configure the servlet, along with the servlet mapping.
The
configuration lets us load the servlet configuration file at initialization.
2. Configuration for springMVC. XML
<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"> <! Configure the package to be scanned when creating springMVC <context:component-scan base-package="com.hust"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <! -- Enable SpringMVC framework annotation support --> <mvc:annotation-driven/> </beans> Copy the code
3. Write the AccountController class
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService accountService;
@RequestMapping("/all") public String findAllAccounts(a){ return "success"; } } Copy the code
At this point, springMVC is configured, we start the server, and when we jump to the success.jsp page after accessing the/Account /all path, the following image appears.
The springMVC configuration is successful
Spring integration for springMVC
Thought analysis
When the server is started, the applicationContext.xml file is not loaded, and the Spring framework does not work, so you cannot use the @Autowire annotation to implement dependency injection and call service layer methods. So the idea is to load the configuration file and create the container when the server starts. In this way, the presentation layer can call the methods of the business layer.
The specific implementation
We set up listeners so that when the server starts, the configuration file is loaded and the container is initialized.
The final web.xml file looks like this:
<! DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name> <! Configure the spring-provided listener to load the container when the service is started.The listener loads the configuration file named ApplicationContext.xml in the WEB-INF directory --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <! -- Specify the location of spring configuration file --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>demo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>demo</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> Copy the code
In the meantime, modify the AccountController class
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService accountService;
@RequestMapping("/all") public String findAllAccounts(a){ List<Account> all = accountService.findAllAccount(); for (Account a:all ) { System.out.println(a); } return "success"; } } Copy the code
When the success.jsp page is accessed, the back end outputs
Account{id=1, name='zhao', money = 99999.99}Account{id=2, name='Zhang Wuji', money = 11111.1}Account{id=3, name='Mu Wan Qing', money = 22222.22}Copy the code
The accountService object can be injected through the container, and the integration is successful.
PS: Use the @RestController annotation to implement the API to separate the front end from the back end.
summary
The key is to use the Spring framework to integrate other frameworks, and understanding what the Spring framework does is crucial!
If you have any questions or write wrong place, welcome to leave a comment!
This article is formatted using MDNICE