SSM framework
The so-called SSM, namely SpringMVC+Spring+Mybatis three frameworks, is also the most popular enterprise development framework in China. Although the current domestic trend is SpringBoot, but SpringBoot is just a simplification of the development, the use of convention is more than the configuration of the rules, automatic configuration of the framework, omits the SSM framework need manual configuration trouble. Therefore, the bottom layer of SpringBoot is still a set of patterns of the Spring framework, so we learn SSM framework, using Spring to integrate SpringMVC and Mybatis framework is still necessary, which can let us have a deeper understanding of SpringBoot.
Setting up the project environment
<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.hrp</groupId>
<artifactId>my_first_ssm</artifactId>
<version>1.0 the SNAPSHOT</version>
<! -- Notice that this is a war package -->
<packaging>war</packaging>
<! -- Unified version management -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.2. RELEASE</spring.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis.spring.version>1.3.2</mybatis.spring.version>
<mysql.version>5.1.32</mysql.version>
<druid.version>1.0.9</druid.version>
<slf4j.version>1.6.6</slf4j.version>
<lombox.version>1.16.22</lombox.version>
<jstl.version>1.2</jstl.version>
<jsp-api.version>2.0</jsp-api.version>
</properties>
<dependencies>
<! Springmvc dependencies, which also depend on spring's other collection core dependencies, can be implemented without the need for spring core dependencies.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<! -- SpringJDBC dependencies, not in the scope of the dependencies above, transaction management must rely on jar package -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<! Spring integrates with the Aspects framework, which is needed later for declarative transaction management based on XML configuration.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<! -- Mybatis dependency -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<! Spring integration Mybatis dependencies -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<! -- MySql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<! -- Druid connection pool, Ali open Source project
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<! -- Log handling -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<! The Lombox plugin is used to automatically generate getters and setters. It is not necessary to automatically generate getters and setters.
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombox.version}</version>
<scope>provided</scope>
</dependency>
<! -- JSTL expression dependencies -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<! Jsp-related dependencies, the scope of which is provided, used only for compilation and testing -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<! - Maven plug-in - >
<plugins>
<! -- build environment, JDK8-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<! -- Runtime environment, tomcat7-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
Copy the code
Writing configuration files
Log4j configuration file
# Global logging configuration
log4j.rootLogger=INFO, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Copy the code
Jdbc.properties, to configure database connection properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_database08
jdbc.username=root
jdbc.password=admin
Copy the code
Applicationcontext.xml configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<! Add jdbc.properties to application. XML file
<context:property-placeholder location="classpath:jdbc.properties"/>
<! Jdbc.properties -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<! SqlSessionFactory = sqlSessionFactory
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<! -- Entity class name package scan, all entity classes in com.hrp.domain package -->
<property name="typeAliasesPackage" value="com.hrp.domain"/>
</bean>
<! Mybatis and Spring
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<! -- Put all persistence layer classes in com.hrp.dao package -->
<property name="basePackage" value="com.hrp.dao"/>
</bean>
<! Add com.hrp. Service to com.hrp. Service
<context:component-scan base-package="com.hrp.service"/>
<! Spring dataSource transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<! Declarative transaction management, notification of transactions -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<! -- Transaction propagation behavior, all save methods start with save -->
<tx:method name="save*" propagation="REQUIRED" />
<! All delete methods start with delete -->
<tx:method name="delete*" propagation="REQUIRED" />
<! All update methods start with update -->
<tx:method name="update*" propagation="REQUIRED" />
<! -- All query methods start with find -->
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<! Service. Impl package for all classes and all methods.
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.hrp.service.impl.*.*(..) )"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
</aop:config>
</beans>
Copy the code
The springmVC.xml configuration file
<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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<! -- Configure Controller annotation scan, all control layers under com.hrp.controller -->
<context:component-scan base-package="com.hrp.controller" />
<! Processor mapper, processor adapter -->
<mvc:annotation-driven/>
<! -- Configure the view parser -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<! -- prefix -- -- >
<property name="prefix" value="/WEB-INF/jsp/" />
<! - the suffix - >
<property name="suffix" value=".jsp" />
</bean>
<! Release static resources -->
<mvc:default-servlet-handler/>
</beans>
Copy the code
Web.xml configuration file
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Interview</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<! -- Encoding filter -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/ *</url-pattern>
</filter-mapping>
<! -- Configure spring core listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<! -- Respecify the path to the Spring configuration file -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<! Configure the core servlet of SpringMVC
<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:springmvc.xml</param-value>
</init-param>
<! When springMVC starts, the parameter must be an integer -->
<! SpringMVC starts with the container if it is 0 or greater than 0 -->
<! If less than 0, start at first request -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<! -- All requests go to springMVC -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Copy the code
Write the code
Creating a database
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(11) DEFAULT NULL,
`password` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Copy the code
Writing entity classes
import lombok.Data;
/** * Entity class User *@author hrp
*/
@Data
public class User {
private String id;
private String name;
private String password;
}
Copy the code
Write the persistence layer, the business layer, and the Web layer
- The persistence layer
public interface UserDao {
/** * Find all users *@return
* @throws Exception
*/
@Select("select * from tb_user")
List<User> findAll(a) throws Exception;
/** * Delete user * based on id@param id
* @throws Exception
*/
@Delete("delete from tb_user where id = #{id}")
void deleteUser(Integer id) throws Exception;
/** * Save user *@param user
* @throws Exception
*/
@Insert("insert into tb_user(name,password) values(#{name},#{password})")
void saveUser(User user) throws Exception;
}
Copy the code
- The business layer
public interface UserService {
/** * Find all users *@return
* @throws Exception
*/
List<User> findAll(a) throws Exception;
/** * Delete user * based on id@param id
* @throws Exception
*/
void deleteUser(Integer id) throws Exception;
/** * Save user *@param user
* @throws Exception
*/
void save(User user) throws Exception;
}
Copy the code
- Business layer interface implementation
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAll(a) throws Exception {
return userDao.findAll();
}
@Override
public void deleteUser(Integer id) throws Exception {
userDao.deleteUser(id);
}
@Override
public void save(User user) throws Exception { userDao.saveUser(user); }}Copy the code
- Web control layer
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("list")
public String findAll(Model model) throws Exception{
List<User> list = userService.findAll();
model.addAttribute("list",list);
return "list";
}
@RequestMapping("delete/{id}")
public String deleteUser(@PathVariable Integer id) throws Exception{
userService.deleteUser(id);
return "forward:/user/list";
}
@RequestMapping("save")
public String save(User user) throws Exception {
userService.save(user);
return "forward:/user/list"; }}Copy the code
Testing capabilities
At this point, Spring’s integration of MVC and Mybatis is complete, and the next step is testing. If you have the Index page in the WebApp directory, you can go directly to the INEx page. If you don’t, you can also directly access the interface exposed by the Controller. http://localhost:8080/user/list remember under the WEB – INF create a folder called JSP, will all your JSP page in the folder.
For example: the list. The JSP
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>All users</title>
</head>
<body>
<h1>All users</h1>
<table>
<tr>
<td>ID</td>
<td>The user name</td>
<td>password</td>
</tr>
<c:forEach var="user" items="${list}">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.password}</td>
<td><a href="/user/delete/${user.id}">delete</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Copy the code