SSM framework integration
1. Create database tables
CREATE DATABASE `ssmbuild`; USE `ssmbuild`; DROP TABLE IF EXISTS `books`; CREATE TABLE `books` ( `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'book id', `bookName` VARCHAR(100) NOT NULL COMMENT 'title', `bookCounts` INT(11) NOT NULL COMMENT 'quantity', `detail` VARCHAR(200) NOT NULL COMMENT 'describe', KEY `bookID` (`bookID`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES (1,'Java',1,'From getting started to giving up'), (2,'MySQL',10,'From deleting the library to running away'), (3,'Linux',5,'From entering the door to entering the prison');
2. Merge Mybatis+spring
1. Create Maven project
2. Import dependency
Dependencies: Junit, database driver, connection pool, servlet, JSP, mybatis, mybatis spring, spring
<!-- Import dependency--> <dependencies> <!-- mysql drive--> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!-- Database connection pool: c3p0--> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <!-- mybatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!-- mybatis-spring--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- JUnit--> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <!-- log4j--> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- lombok--> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
3. Maven resource filtering settings
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
4. resources folder
Create mybatis config 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> </configuration>
Create ApplicationContext 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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
5. Write database properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8 username=root password=123456
Add a time zone configuration using MySQL 8.0 +
6. Requirements analysis - code implementation
Create package - pojo, DAO layer / persistence layer, Service layer / business layer / Service layer: mainly deal with business functions, logs, permissions and things. controller presentation layer: it mainly receives the parameters of the foreground browser user, responds to the browser data, and so on.
Then create entity class, dao layer interface and implementation class, service layer interface and implementation class, and then write controller presentation layer
dao layer
//Add a Book int addBook(Books books); //Delete a Book int deleteBookById(@Param("bookID") int id); //Update a Book int updateBook(Books books); //Inquire about a Book Books queryBookById(@Param("bookID")int id); //Check all the books List<Books> queryAllBook();
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.dao.BookMapper"> <insert id="addBook" parameterType="books"> insert into ssmbuild.books ( bookName, bookCounts, detail) VALUES (#{bookName},#{bookCounts},#{detail}) </insert> <delete id="deleteBookById" parameterType="int" > delete from ssmbuild.books where bookID=#{bookID} </delete> <update id="updateBook" parameterType="books"> update ssmbuild.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID} </update> <select id="queryBookById" resultType="books"> select * from ssmbuild.books where bookID=#{bookID} </select> <select id="queryAllBook" resultType="books"> select * from ssmbuild.books </select> </mapper>
7,mybatis-config.xml
Write mybatis config xml
Configure alias and register Mapper
The fundamental purpose of handing over the work of configuring data sources to spring is to simplify development
<?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 <typeAliases> <package name="com.test.pojo"/> </typeAliases> <mappers> <mapper class="com.test.dao.BookMapper"/> </mappers> </configuration>
8. Write spring Dao xml
<!-- 1,Associated database profile--> <context:property-placeholder location="classpath:database.properties"/>
spring configuration data source
<!-- 2,Connection pool dbcp: Semi automatic operation, unable to connect automatically c3p0: Automatic operation(The configuration file is loaded automatically and can be automatically set into the object) druid: hikari --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> <!-- c3p0 Private properties of connection pool --> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- Not automatically after closing the connection commit --> <property name="autoCommitOnClose" value="false"/> <!-- Get connection timeout --> <property name="checkoutTimeout" value="10000"/> <!-- Number of retries when getting connection failed --> <property name="acquireRetryAttempts" value="2"/> </bean>
In mybatis spring, SqlSessionFactory bean is used to create SqlSessionFactory.
There is a unique required property: DataSource for JDBC
A common attribute is configLocation, which is used to specify the XML configuration file path of MyBatis.
<!-- 3,SQLSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- binding Mybatis Configuration file for--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean>
<!-- to configure dao The interface scanning package is dynamically implemented Dao Interface can be injected into Spring In container!--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- injection sqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- To scan dao package--> <property name="basePackage" value="com.test.dao"/> </bean>
9. Write spring service xml
<!-- scanning service Package under--> <context:component-scan base-package="com.test.service"/>
We're at Spring Dao XML implements the configuration Dao interface scanning package, and dynamically implements the Dao interface, which can be injected into the Spring container! So at this time, we can inject Dao interface by injecting all business classes into Spring.
<!-- Inject all our business classes into Spring,It can be implemented through configuration or annotation--> <bean id="BookServiceImpl" class="com.test.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean>
To enable the transaction processing function of Spring, create a DataSourceTransactionManager object in the Spring configuration file:
Note: the DataSource specified for the transaction manager must be the same data source used to create the SqlSessionFactoryBean, otherwise the transaction manager will not work.
<!-- Declarative transaction configuration--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- Injection data source--> <property name="dataSource" ref="dataSource"/> </bean> <!-- aop Transaction support!-->
10,applicationContext.xml
Introduce the spring Dao XML and spring service Merge XML into one
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="spring-dao.xml"/> <import resource="spring-service.xml"/> </beans>
3. Merge spring MVC
1. Add web support
Right click the item Add Framework Support
2. Write web xml
Dispatcher Servlet is a front-end Controller configured on the web In the XML file, the Servlet intercepts matching requests according to specific rules defined by itself and distributes them to the target Controller for processing.
On the web In the < Servlet > tag of XML, you can use < load on startup > to control whether servlets are initialized with the start of the web container and the initialization order when multiple servlets are created at the same time.
DispatchServlet
<!-- DispatchServlet--> <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:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
loadOnStartup settings are divided into three cases:
- Loadonstartup < 0 does not instantiate when the web container is started. The servlet is instantiated only when it is called for the first time. Loadonstartup is this by default (that is, when it is not configured).
- Loadonstartup > 0 instantiation is performed when the web container is started. The order is from small to large, and the small positive integer is instantiated first.
- Loadonstartup = 0. Instantiation is performed when the web container is started, which is equivalent to the maximum integer. Therefore, when the web container is started, it is instantiated at last.
In addition, < servlet mapping > intercepts the request, and then the corresponding servlet processes the request. The above configuration < URL pattern > / < / url pattern > means to intercept all URLs except jsp, and DispatchServlet will process these requests.
Random code filtering
<!-- Random code filtering--> <filter> <filter-name>encodingFilter</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
session
<!--Session--> <session-config> <session-timeout>15</session-timeout> </session-config>
3. Write spring MVC xml
1. Support mvc annotation driven
2. Auto scan package
<context:component-scan base-package="com.test.controller"/>
3. Make spring MVC not handle static resources
<mvc:default-servlet-handler/>
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1,Annotation driven--> <mvc:annotation-driven/> <!-- 2,Static resource filtering--> <mvc:default-servlet-handler/> <!-- 3,Scan package: controller--> <context:component-scan base-package="com.test.controller"/> <!-- 4,view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp"/> <property name="suffix" value=".jap"/> </bean> </beans>