文章目录
-
- SSM项目
- 创建项目
- pom.xml
- web.xml
- applicationContext.xml
- db.properties
- SpringMVC.xml
- mybatis-config.xml
- log4j.xml
- SQL
- Users.java
- UsersMapper.java
- UsersMapper.xml
- UsersService.java
- UsersServiceImpl.java
- UsersController.java
- userList.html
- addUser.html
- editUser.html
- userDetails.html
- 效果
SSM项目
- SpringMVC:表现层框架,处理浏览器发送的请求,找到具体的数据,将具体数据响应到服务器,
- Spring:整合形框架,通过Ioc管理对象,比如Mybatis中操作数据库的SqlSession对象,MyBatis操作数据库时需要的事务功能,也可以使用Spring中的AOP的重要应用,来声明事务实现,
- MyBatis:持久层框架,连接数据库,操作数据库,访问数据库
创建项目
![SSM整合_第1张图片](http://img.e-com-net.com/image/info8/d669bdc4a4c94fd19a78859e8788a03c.jpg)
![SSM整合_第2张图片](http://img.e-com-net.com/image/info8/bdfb07267cab4279be4ff475d7ffcb8c.jpg)
![SSM整合_第3张图片](http://img.e-com-net.com/image/info8/1d8847dbc6af4496bbf7a24fd1215500.jpg)
![SSM整合_第4张图片](http://img.e-com-net.com/image/info8/a0953d3a7a4749b49c03bb3967e9a8ad.jpg)
![SSM整合_第5张图片](http://img.e-com-net.com/image/info8/e6b7d9c1524f4b789007e79d4340be1c.jpg)
![SSM整合_第6张图片](http://img.e-com-net.com/image/info8/068632295e9c4ceca9a87b360954464d.jpg)
![SSM整合_第7张图片](http://img.e-com-net.com/image/info8/e1c943f398f94984afd075dc2cf884c2.jpg)
pom.xml
<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.0modelVersion>
<groupId>com.singroupId>
<artifactId>SSMDemoartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>SSMDemo Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<spring.version>5.3.22spring.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.7version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.11version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
dependency>
<dependency>
<groupId>org.thymeleafgroupId>
<artifactId>thymeleaf-spring5artifactId>
<version>3.0.15.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>SSMDemofinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
web.xml
<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">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>hiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
applicationContext.xml
<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">
<context:component-scan base-package="com">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<context:property-placeholder location="classpath: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>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml">property>
<property name="dataSource" ref="dataSource">property>
<property name="mapperLocations" value="classpath:mapper/*.xml">property>
bean>
<mybatis-spring:scan base-package="com.sin.mapper"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
<tx:method name="get*" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pt" expression="execution(* com.sin.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt">aop:advisor>
aop:config>
beans>
db.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/demo
jdbc.username = root
jdbc.password = 123456
SpringMVC.xml
<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">
<context:component-scan base-package="com" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<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">
<property name="prefix" value="/WEB-INF/templates/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
bean>
property>
bean>
property>
bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
beans>
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="cacheEnabled" value="true"/>
settings>
<typeAliases>
<package name="com.sin"/>
typeAliases>
<databaseIdProvider type="DB_VENDOR">
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
<property name="SQL Server" value="sqlserver"/>
databaseIdProvider>
configuration>
log4j.xml
<configuration status="TRACE">
<appenders>
<console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
console>
appenders>
<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>
SQL
use demo;
-- 创建数据表
-- primary key : 逐渐id
-- auto_increment : 字段自增
-- comment : 字段的注释
-- character set utf8 : 字段的编码格式
-- default null : 字段默认为null
-- charset = utf8 : 将表的编码格式设置为utf8
create table users(
id int primary key auto_increment comment '主键id',
name varchar(20) character set utf8 default null comment '姓名',
email varchar(20) default null comment '邮箱'
)charset = utf8;
insert into users(name,email) values ('张三','[email protected]');
select id,name,email from users;
Users.java
package com.sin.pojo;
public class Users {
private int id;
private String name;
private String email;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UsersMapper.java
package com.sin.mapper;
import com.sin.pojo.Users;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UsersMapper {
List<Users> getAllUsers();
Users getUserById(int id);
void addUser(Users user);
void updateUser(Users user);
void deleteUser(int id);
}
UsersMapper.xml
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sin.mapper.UsersMapper">
<select id="getAllUsers" resultType="com.sin.pojo.Users">
SELECT * FROM users;
select>
<select id="getUserById" parameterType="int" resultType="com.sin.pojo.Users">
SELECT * FROM users WHERE id = #{id};
select>
<insert id="addUser" parameterType="com.sin.pojo.Users">
INSERT INTO users (name, email) VALUES (#{name}, #{email});
insert>
<update id="updateUser" parameterType="com.sin.pojo.Users">
UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id};
update>
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id};
delete>
mapper>
UsersService.java
package com.sin.service;
import com.sin.pojo.Users;
import java.util.List;
public interface UsersService {
List<Users> getAllUsers();
Users getUserById(int id);
void addUser(Users user);
void updateUser(Users user);
void deleteUser(int id);
}
UsersServiceImpl.java
package com.sin.service.impl;
import com.sin.mapper.UsersMapper;
import com.sin.pojo.Users;
import com.sin.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UsersServiceImpl implements UsersService {
@Autowired(required = false)
private UsersMapper usersMapper;
@Override
public List<Users> getAllUsers() {
return usersMapper.getAllUsers();
}
@Override
public Users getUserById(int id) {
return usersMapper.getUserById(id);
}
@Override
public void addUser(Users user) {
usersMapper.addUser(user);
}
@Override
public void updateUser(Users user) {
usersMapper.updateUser(user);
}
@Override
public void deleteUser(int id) {
usersMapper.deleteUser(id);
}
}
UsersController.java
package com.sin.controller;
import com.sin.pojo.Users;
import com.sin.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
@Controller
public class UsersController {
@Autowired(required = false)
private UsersService userService;
@GetMapping("/users")
public String getAllUsers(Model model) {
List<Users> users = userService.getAllUsers();
model.addAttribute("users", users);
return "userList";
}
@GetMapping("/users/{id}")
public String getUserById(@PathVariable int id, Model model) {
Users user = userService.getUserById(id);
model.addAttribute("user", user);
return "userDetails";
}
@GetMapping("/users/add")
public String addUserForm(Model model) {
model.addAttribute("user", new Users());
return "addUser";
}
@PostMapping("/users")
public String addUser(@ModelAttribute("user") Users user) {
userService.addUser(user);
return "redirect:/users";
}
@GetMapping("/users/{id}/edit")
public String editUserForm(@PathVariable int id, Model model) {
Users user = userService.getUserById(id);
model.addAttribute("user", user);
return "editUser";
}
@PostMapping("/users/{id}")
public String updateUser(@PathVariable int id, @ModelAttribute("user") Users user) {
userService.updateUser(user);
return "redirect:/users";
}
@GetMapping("/users/{id}/delete")
public String deleteUser(@PathVariable int id) {
userService.deleteUser(id);
return "redirect:/users";
}
}
userList.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表title>
head>
<body>
<h1>用户列表h1>
<table>
<thead>
<tr>
<th>IDth>
<th>姓名th>
<th>邮箱th>
<th>操作th>
tr>
thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}">td>
<td th:text="${user.name}">td>
<td th:text="${user.email}">td>
<td>
<a th:href="@{/users/{id}(id=${user.id})}">查看a>
<a th:href="@{/users/{id}/edit(id=${user.id})}">编辑a>
<a th:href="@{/users/{id}/delete(id=${user.id})}">删除a>
td>
tr>
tbody>
table>
<a href="/users/add">添加用户a>
body>
html>
addUser.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户title>
head>
<body>
<h1>添加用户h1>
<form th:action="@{/users}" method="post" th:object="${user}">
<label>姓名: <input type="text" th:field="*{name}" />label><br/>
<label>邮箱: <input type="email" th:field="*{email}" />label><br/>
<input type="submit" value="添加" />
form>
<a href="/users">返回列表a>
body>
html>
editUser.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改用户title>
head>
<body>
<h1>修改列表h1>
<form th:action="@{/users/{id}(id=${user.id})}" method="post" th:object="${user}">
<input type="hidden" th:field="*{id}" />
<label>姓名: <input type="text" th:field="*{name}" />label><br/>
<label>邮箱: <input type="email" th:field="*{email}" />label><br/>
<input type="submit" value="修改" />
form>
<a href="/users">返回列表a>
body>
html>
userDetails.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户详情title>
head>
<body>
<h1>用户详情h1>
<p>id: <span th:text="${user.id}">span>p>
<p>姓名: <span th:text="${user.name}">span>p>
<p>邮箱: <span th:text="${user.email}">span>p>
<a href="/users">返回列表a>
body>
html>
效果
![SSM整合_第8张图片](http://img.e-com-net.com/image/info8/4dc673d367444589a69a4603e5b37903.jpg)
![SSM整合_第9张图片](http://img.e-com-net.com/image/info8/5113e6dc020f4b8c9cc5c6f08579c2d6.jpg)
![SSM整合_第10张图片](http://img.e-com-net.com/image/info8/e729556b8a4845088b2d80447615aba2.jpg)
![SSM整合_第11张图片](http://img.e-com-net.com/image/info8/3bf22276b708416c8c865fa8466f905e.jpg)