Project introduction:
What is ssm?
ssm represents the integration project of Spring + spring MVC + mybatis;
The integration of SSM framework is to realize the integration of Spring and Spring MVC, Spring and Mybatis respectively, and the main work of the integration is to configure the objects in Spring MVC and Mybatis into the Spring container and give them to Spring for management.
SSM stratification
1. Spring MVC: web layer, equivalent to controller (equivalent to struts action), which is mainly used for page; request acceptance and response.
Components include: front-end controller, processor mapper, processor adapter, View parser, processor Handler and View. Among them, only processor Handler and View need to be developed by programmers.
Spring: IOC container DI#AOP
MyBatis: automatically map result sets
2. SSM framework corresponds to Java EE three-tier architecture
(1) Web tier: Spring MVC
(2) Service layer: Spring
(3) DAO layer: MyBatis
Integrated ideas:
(1) Integrate Spring MVC framework and Spring framework
Since Spring MVC and Spring come from the same source, they can be integrated seamlessly
Note: the creation of the Controller object of spring MVC is still managed by spring MVC
(2) Integrate Spring framework and MyBatis framework
1) write the database connection configuration in the MyBatis core configuration file directly into the Spring core configuration file
2) leave the creation of SqlSessionFactory object of MyBatis to Spring for management
3) configuration: when the server starts, load the Spring core configuration file and create a series of objects including SqlSessionFactory objects
Required attributes of each framework:
About the respective configuration files of the SSM framework and the required object properties?
1,SpringMVC
Spring MVC is the framework of the view layer (UI). The objects used by the view are managed by the spring MVC container and placed in the spring MVC configuration file.
1) processor object (Controller);
2) register the component scanner < context: component scan base package = "package name of controller Annotation" / >;
3) register view resolver: InternalResourceViewResolver, configure prefix and suffix;
4) registration annotation driven: < MVC: annotation driven >;
5) mapper of registered processor and adapter of registered processor (optional)
2,Spring
Spring manages the objects of the business layer and persistence layer (Service and dao). These objects are placed in the spring configuration file and managed by the spring container.
1) give the Service object to Spring and use @ Service annotation.
< context: component scan base package = "package name of service Annotation" / >;
2) Dao object to Spring, MyBatis object to Spring.
a) data source: c3p0, dbcp;
b) register SqlSessionFactoryBean to create SqlSessionFactory;
c) register the dynamic proxy scanner to create the dynamic proxy object of Dao interface, that is, the object of Dao layer;
3) leave the transaction management to Spring.
a) use annotations to handle transactions;
b) manage transactions in the configuration file using AOP of AspectJ
Relationship between Spring container and Spring MVC container:
Spring is the parent container of spring MVC.
Yes, you can know the existence of the Spring container (parent container) in the Spring MVC container (child container). The child container can access the parent container, but the parent container cannot access the child container.
SSM consolidation profile:
SSM consolidated profile:
1) spring MVC configuration file. The file name is user-defined. Spring MVC xml
2) Spring configuration file. The file name is user-defined. ApplicationContext xml
3) main configuration file of MyBatis, location of configuration alias and SQL mapping file;
4) SQL mapping file, which is used to write SQL statements;
5) database attribute configuration file, for example: JDBC properties;
6)web.xml
A) register the central scheduler of spring MVC: the function is to receive requests, create a spring MVC container at startup, and read the configuration file of spring MVC;
b) register the Spring listener ContextLoadListener, create the Spring container at startup, and read the Spring configuration file;
c) register the character set filter to solve the garbled code problem of POST request.
The basic beginning of integrating SSM
I preparation
Create a new database table [the tool I use here is Navicat]
catalogue
Required attributes of each framework:
The basic beginning of integrating SSM
① at POM XML to add some configuration files
② on the web Configure again under XM
④ create a new mybatis config XML [data source needs to be configured]
⑥ Create a new ApplicationContext xml
[the above is all the configuration files required for SSM integration]
Department [the Department attribute is encapsulated]
Employee [encapsulates attributes]
Note: before testing, you need to configure the relevant Tomcat
Create a maven project, add some web related packages
① at POM XML to add some configuration files
<?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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ssm</groupId> <artifactId>ssm01</artifactId> <version>1.0-SNAPSHOT</version> <!--to configure web Need to pack--> <packaging>war</packaging> <dependencies> <!--1.Import first springmvc Import some dependent packages spring Related packages Automatically brought in aop beans context core web expression package--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.9.RELEASE</version> </dependency> <!--2.spring package--> <!--Support transaction control--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.9.RELEASE</version> </dependency> <!--Aspect oriented programming support transactions--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.9.RELEASE</version> </dependency> <!--3.mybatis package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!--Adaptation package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!--4.Database related--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!--durid Connection pool--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> <!--5.Other packages--> <!--servletAPI--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--web Packages required for the project jsp:jstl jsp Integration package--> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> <!--Tymleaf and Spring Integration package--> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> <!--journal log4j2--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>2.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.2</version> </dependency> </dependencies> </project>
② on the web Configure again under XM
[there may be errors in the content of spring mvc.xml , don't worry, let's do the next steps first]
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--1.load Spring container--> <!--Load profile--> <context-param> <param-name>contextConfigLocation</param-name> <!--spring Location of the configuration file--> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--The container is loaded when the project is started--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--2.SpringMVC--> <!--Front end controller--> <servlet> <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--3.Character encoding filter--> <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>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--4.handle rest Stylized delete put request--> <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> </web-app>
③ create a new spring MVC 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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--springMVC configuration file Configure site jump logic===>controller use-default-filters="false":Default use rule off--> <!--1.Scan only Controller--> <context:component-scan base-package="ssm" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- to configure Thymeleaf view resolver --> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <!-- View prefix --> <property name="prefix" value="/WEB-INF/templates/"/> <!-- View suffix --> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean> <!--3.Requests that cannot be processed by the front-end controller processing static resources are handed over to the default controller servlet tomcat Server--> <mvc:default-servlet-handler/> <!--4.Turn on the annotation driver and let mvc Support for more advanced features--> <mvc:annotation-driven/> <!--5.View controller--> <mvc:view-controller path="/" view-name="index"/> </beans>
④ create a new mybatis config XML [data source needs to be configured]
<?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> <!--Configure only unique--> <!--Hump nomenclature--> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <!--To avoid version updates, show write out--> <setting name="cacheEnabled" value="true"/> </settings> <!--Alias--> <typeAliases> <package name="ssm.bean"/> </typeAliases> <databaseIdProvider type="DB_VENDOR"> <!--Alias for configuration database--> <property name="MySQL" value="mysql"/> <property name="Oracle" value="oracle"/> <property name="SQL Server" value="sqlserver"/> </databaseIdProvider> </configuration>
db.properties
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <!--Configuration hinder status Used to set log4j2 The internal information output can not be set when it is set to trace When, you can see log4j2 Various internal detailed outputs--> <configuration status="TRACE"> <!--Define all first appender--> <appenders> <!--Output log information to console--> <console name="Console" target="SYSTEM_OUT"> <!--Controls the format of log output--> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </console> </appenders> <!--Then define logger,Only defined logger And introduced appender,appender Will take effect--> <!--root: Used to specify the root log of the project, if not specified separately Logger,Will be used root As default log output--> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="info" /> </logger> <loggers> <root level="debug"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
⑥ Create a new 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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--spring configuration file--> <!--1.Scan component--> <context:component-scan base-package="ssm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--2.Configure data sources--> <context:property-placeholder location="classpath:db.properties"/> <!--Configure data sources--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </bean> <!--3.Spring integration MyBatis--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybtis-config.xml"></property> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!--4.Configure scanner --> <!--base-package: Specify the package where the interface is located--> <mybatis-spring:scan base-package="ssm.dao"/> <!--5.Configure transactions--> <!--①Transaction manager--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--②use aop Enforce transactions on methods of classes--> transaction-manager="transactionManager" Specify transaction manager If the name of the transaction manager is transactionManager It can be omitted --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--Configure enhanced properties--> <tx:attributes> <!--All methods use transactions--> <tx:method name="*"/> <!--getxxx Method is read-only--> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <!--③Configure how facets and pointcuts are added to methods and what rules are followed--> <!--AOP to configure--> <aop:config> <!--breakthrough point--> <aop:pointcut id="pt" expression="execution(* ssm.service.*.*(..))"/> <!--Which enhancement does the slice add to the tangent point--> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor> </aop:config> </beans>
[the above is all the configuration files required for SSM integration]
Next, let's do a test
At the beginning of the project, we created a new package, so we need it in the next test
Department [the Department attribute is encapsulated]
public class Department implements Serializable { private static final long serialVersionUID = 3101613282324740629L; private Integer id;// private String deptname;// public Department() { } public Department(Integer id, String deptname) { this.id = id; this.deptname = deptname; } public static long getSerialVersionUID() { return serialVersionUID; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDeptname() { return deptname; } public void setDeptname(String deptname) { this.deptname = deptname; } @Override public String toString() { return "Department{" + "id=" + id + ", deptname='" + deptname + '\'' + '}'; } }
Employee [encapsulates attributes]
public class Employee implements Serializable { private static final long serialVersionUID = 1423771930125710351L; private Integer id;// private String lastName; private String gender;//Gender private String email; //Department private Department dept; public Employee(Department dept) { this.dept = dept; } public Department getDept() { return dept; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", gender='" + gender + '\'' + ", email='" + email + '\'' + ", dept=" + dept + '}'; } public void setDept(Department dept) { this.dept = dept; } public Employee() { } public Employee(Integer id, String lastName, String gender, String email) { this.id = id; this.lastName = lastName; this.gender = gender; this.email = email; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
EmloyeeController
@Controller public class EmployeeController { //Call service @Autowired EmployeeService employeeService; @RequestMapping("/getEmpall") public String getEmpall(Model model){ List<Employee> empAll = employeeService.getEmpAll(); model.addAttribute("empall",empAll); return "emp_list"; } }
EmployeeService
@Service public class EmployeeService { /*Auto inject from spring container*/ @Autowired EmployeeMapper mapper; //Call dao to query all public List<Employee> getEmpAll(){ return mapper.getEmpByAll(); } }
[jump test]
After doing the above steps, we jump to the page and display the content
① index.html
②emp_list.html
<body> <table border="1" width="800px"> <tr> <td>number</td> <td>full name</td> <td>Gender</td> <td>mailbox</td> <td>Department name</td> </tr> <!--Traversal data--> <tr th:each="emp:${empall}"> <td th:text="${emp.id}"></td> <td th:text="${emp.lastName}"></td> <td th:text="${emp.gender}">male</td> <td th:text="${emp.gender}">female</td> <td th:text="${emp.email}"></td> <td th:text="${emp.dept}!=null ? ${emp.dept.deptname}:'There is no department for the time being'"></td> </tr> </table> </body>
Note: before testing, you need to configure the relevant Tomcat
[test results]