回顾SpringMVC-04
本章咱就整合SSM,话不多说,上代码
环境要求
环境:
IDEAMySQL5.7Tomcat8Maven3.6
数据库
创建数据库
CREATE TABLE `user` (
`id
` int(20) NOT NULL,
`name
` varchar(30) DEFAULT NULL,
`pwd
` varchar(30) DEFAULT NULL,
`perms
` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id
`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
insert into `user`(`id
`,`name
`,`pwd
`,`perms
`) values
(1,'马云','123456',NULL),
(2,'aaa','123213',NULL),
(3,'李四','1z1z1z',NULL),
(4,'半仙','123355',NULL),
(5,'大仙','123255',NULL),
(6,'小仙','222255',NULL),
(7,'李武','546552',NULL),
(8,'刘霸','555599',NULL);
基本环境搭建
打开IDEA,创建一个Maven项目,取名看自己了,添加web支持
导入pom.xml中的依赖主要有
pom.xml
<dependencies>
<dependency>
<groupId>junit
</groupId>
<artifactId>junit
</artifactId>
<version>4.12
</version>
</dependency>
<dependency>
<groupId>mysql
</groupId>
<artifactId>mysql-connector-java
</artifactId>
<version>5.1.47
</version>
</dependency>
<dependency>
<groupId>com.mchange
</groupId>
<artifactId>c3p0
</artifactId>
<version>0.9.5.2
</version>
</dependency>
<dependency>
<groupId>org.mybatis
</groupId>
<artifactId>mybatis
</artifactId>
<version>3.5.2
</version>
</dependency>
<dependency>
<groupId>org.mybatis
</groupId>
<artifactId>mybatis-spring
</artifactId>
<version>2.0.4
</version>
</dependency>
<dependency>
<groupId>org.springframework
</groupId>
<artifactId>spring-webmvc
</artifactId>
<version>5.2.5.RELEASE
</version>
</dependency>
<dependency>
<groupId>org.springframework
</groupId>
<artifactId>spring-jdbc
</artifactId>
<version>5.1.9.RELEASE
</version>
</dependency>
<dependency>
<groupId>javax.servlet
</groupId>
<artifactId>servlet-api
</artifactId>
<version>2.5
</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp
</groupId>
<artifactId>jsp-api
</artifactId>
<version>2.2
</version>
</dependency>
<dependency>
<groupId>javax.servlet
</groupId>
<artifactId>jstl
</artifactId>
<version>1.2
</version>
</dependency>
<dependency>
<groupId>org.projectlombok
</groupId>
<artifactId>lombok
</artifactId>
<version>1.18.12
</version>
</dependency>
</dependencies>
别忘了加入资源过滤
<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>
建立基本目录结构
创建包,Controller,service,dao,实体类
com.feng.controller
com.feng.dao
com.feng.pojo
com.feng.service
配置文件
spring主配置文件
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"
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-4.2.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
里面导入的三个resource
spring-dao.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"
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">
<context:property-placeholder location="classpath:db.properties"/>
<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}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.feng.dao"/>
</bean>
</beans>
spring-service.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"
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">
<context:component-scan base-package="com.feng.service"/>
<bean id="UserServiceImpl" class="com.feng.service.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
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"
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-4.2.xsd">
<context:component-scan base-package="com.feng.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
mybatis配置文件
mybatis.properties
这里根据自己的数据库名和表来,账号密码一样自己来
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=*****
mybatis核心配置文件
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>
<properties resource="db.properties"></properties>
<typeAliases>
<typeAlias type="com.feng.pojo.User" alias="User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/feng/dao/UserMapper.xml"/>
</mappers>
</configuration>
Mybatis层编写
com.feng.pojo.User
User.java
package com
.feng
.pojo
;
import lombok
.AllArgsConstructor
;
import lombok
.Data
;
import lombok
.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id
;
private String name
;
private String pwd
;
}
这里用了lombok插件,没有的话就自己写一下get、set、有参无参
编写Dao层的Mapper接口
UserDao.java
package com
.feng
.dao
;
import com
.feng
.pojo
.User
;
import java
.util
.List
;
public interface UserDao {
List
<User> findAll();
User
getUserById(int id
);
List
<User> getUserLike(String value
);
int addUser(User user
);
int insertTest(User user
);
int updateUser(User user
);
int deleteUser(int id
);
User
queryUserByName(String name
);
}
根据UserDao的Mapper接口编写对应的Mapper文件
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.feng.dao.UserDao">
<select id="findAll" resultType="User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="User">
select * from mybatis.user where id = #{id}
</select>
<select id="getUserLike" resultType="User">
select * from mybatis.user where name like "%"#{value}"%"
</select>
<insert id="addUser" parameterType="User">
insert into mybatis.user (id,name,pwd)
values (#{id},#{name},#{pwd})
</insert>
<insert id="insertTest" useGeneratedKeys="true"
keyProperty="id" parameterType="User">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
SELECT MAX(id) +1 AS id From mybatis.user
</selectKey>
INSERT INTO mybatis.user (id,name,pwd)
VALUE (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
<select id="queryUserByName" resultType="User">
select * from mybatis.user where name =#{name}
</select>
</mapper>
编写Service层的接口和实现类
UserService.java
package com
.feng
.service
;
import com
.feng
.pojo
.User
;
import java
.util
.List
;
public interface UserService {
List
<User> findAll();
User
getUserById(int id
);
List
<User> getUserLike(String value
);
int addUser(User user
);
int updateUser(User user
);
int deleteUser(int id
);
User
queryUserByName(String name
);
}
实现类
UserServiceImpl.java
package com
.feng
.service
;
import com
.feng
.dao
.UserDao
;
import com
.feng
.pojo
.User
;
import java
.util
.List
;
public class UserServiceImpl implements UserService {
private UserDao userDao
;
public void setUserDao(UserDao userDao
) {
this.userDao
= userDao
;
}
@Override
public List
<User> findAll() {
return userDao
.findAll();
}
@Override
public User
getUserById(int id
) {
return userDao
.getUserById(id
);
}
@Override
public List
<User> getUserLike(String name
) {
return userDao
.getUserLike(name
);
}
@Override
public int addUser(User user
) {
return userDao
.addUser(user
);
}
@Override
public int updateUser(User user
) {
return userDao
.updateUser(user
);
}
@Override
public int deleteUser(int id
) {
return userDao
.deleteUser(id
);
}
@Override
public User
queryUserByName(String name
) {
return userDao
.queryUserByName(name
);
}
}
到这里底层就完毕了
web.xml
<?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">
<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>
<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-config>
<session-timeout>15
</session-timeout>
</session-config>
</web-app>
最后写业务类
业务类
UserController.java
package com
.feng
.controller
;
import com
.feng
.pojo
.User
;
import com
.feng
.service
.UserService
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.beans
.factory
.annotation
.Qualifier
;
import org
.springframework
.stereotype
.Controller
;
import org
.springframework
.ui
.Model
;
import org
.springframework
.web
.bind
.annotation
.PathVariable
;
import org
.springframework
.web
.bind
.annotation
.RequestMapping
;
import java
.util
.ArrayList
;
import java
.util
.List
;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
@Qualifier("UserServiceImpl")
private UserService userService
;
@RequestMapping("/allUser")
public String
list(Model model
){
List
<User> list
= userService
.findAll();
model
.addAttribute("list",list
);
return "allUser";
}
@RequestMapping("/queryUser")
public String
queryUser(String queryUserName
,Model model
){
User user
= userService
.queryUserByName(queryUserName
);
List
<User> list
= new ArrayList<>();
list
.add(user
);
if(user
==null
){
list
= userService
.findAll();
model
.addAttribute("error","未查到结果");
}
model
.addAttribute("list",list
);
return "allUser";
}
@RequestMapping("/getUserLike")
public String
getUserLike(String LikeName
,Model model
){
List
<User> list
= userService
.getUserLike(LikeName
);
model
.addAttribute("list",list
);
return "allUser";
}
@RequestMapping("/toAddUser")
public String
toAddPage(){
return "addUser";
}
@RequestMapping("/addUser")
public String
addUser(User user
){
System
.out
.println("addUser--->"+user
);
userService
.addUser(user
);
return "redirect:/user/allUser";
}
@RequestMapping("/toUpdate")
public String
toUpdate(int id
,Model model
){
User user
= userService
.getUserById(id
);
model
.addAttribute("user",user
);
return "updateUser";
}
@RequestMapping("/updateUser")
public String
updateUser(User user
){
System
.out
.println("updateUser-->"+user
);
userService
.updateUser(user
);
return "redirect:/user/allUser";
}
@RequestMapping("/del/{id}")
public String
deleteUser(@PathVariable("id") int id
){
userService
.deleteUser(id
);
return "redirect:/user/allUser";
}
}
前端页面
index.jsp
<%--
Created by IntelliJ IDEA.
User: 16979
Date: 2020/4/18
Time: 10:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML>
<html>
<head>
<title>首页</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/user/allUser">点击进入列表页</a>
</h3>
</body>
</html>
allUser.jsp
显示用户的页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 16979
Date: 2020/4/18
Time: 13:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户展示</title>
<meta name="viewport" content="width=device-width,initial-scal=1.0">
<%-- 引入Bootstrap,美化界面--%>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>用户列表——显示所有用户</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 colunm">
<%--toAddBook--%>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/user/toAddUser">新增用户</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/user/allUser">显示全部用户</a>
</div>
<div class="col-md-8 colunm">
<%--查询用户--%>
<form class="form-inline" action="${pageContext.request.contextPath}/user/queryUser" method="post" style="float: right" class="form-inline">
<span style="color: red;font-weight: bold">${error}</span>
<input type="text" name="queryUserName" class="form-control" placeholder="请输入要查询的用户名称">
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</div>
<div class="row">
<div class="col-md-4 colunm">
</div>
<div class="col-md-8 colunm">
<%--查询用户--%>
<form class="form-inline" action="${pageContext.request.contextPath}/user/getUserLike" method="post" style="float: right" class="form-inline">
<span style="color: red;font-weight: bold">${error}</span>
<input type="text" name="LikeName" class="form-control" placeholder="请输入要查询的用户名称">
<input type="submit" value="模糊查询" class="btn btn-primary">
</form>
</div>
</div>
<div class="row clearfix">
<div class="col-ma-12 column">
<table class="table table-hover table-striped">
<thread>
<tr>
<th>用户编号</th>
<th>用户名字</th>
<th>用户密码</th>
<th>操作</th>
</tr>
</thread>
<tbody>
<c:forEach var="user" items="${requestScope.get('list')}">
<tr>
<td>${user.getId()}</td>
<td>${user.getName()}</td>
<td>${user.getPwd()}</td>
<td>
<a href="${pageContext.request.contextPath}/user/toUpdate?id=${user.getId()}">更改</a>
|
<a href="${pageContext.request.contextPath}/user/del/${user.getId()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
addUser.jsp
<%--
Created by IntelliJ IDEA.
User: 16979
Date: 2020/5/26
Time: 12:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%-- 引入Bootstrap,美化界面--%>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>新增用户</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/user/addUser"method="post">
用户ID:<input type="text" name="id" required><br><br><br>
用户名称:<input type="text" name="name" required><br><br><br>
用户密码:<input type="text" name="pwd" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
updateUser.jsp
<%--
Created by IntelliJ IDEA.
User: 16979
Date: 2020/5/26
Time: 12:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>修改用户</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/user/updateUser"method="post">
<input type="hidden" name="id" value="${user.getId()}"/>
用户名称:<input type="text" name="name" value="${user.getName()}" required><br><br><br>
用户密码:<input type="text" name="pwd" value="${user.getPwd()}" required><br><br><br>
<input type="submit" value="修改">
</form>
</div>
</body>
</html>
结构一览图
完事儿
最后启动tomcat,运行~
主页
用户列表
普通查询
模糊查询
更新用户