5,整合SSM
5.1,整合步骤
1,数据库
创建一个存放书籍数据的数据库表
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
2,基本环境搭建
1、新建一Maven项目
2、导入相关的pom依赖!
<dependencies>
<!--Junit-->
<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>
<!--Servlet - JSP -->
<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>
<!--Mybatis-->
<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.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--aop-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
3、Maven资源过滤设置
<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、建立基本结构和配置框架!
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>
<!--配置数据源, 交给Spring去做-->
<typeAliases>
<package name="com.ccc.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.ccc.dao.BookMapper"/>
</mappers>
</configuration>
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 http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
#mysql8.0+
#jdbc.driver=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/database?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
5,实体类Books
package com.ccc.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
6,Dao层
BookMapper
package com.ccc.dao;
import com.ccc.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//增加
int addBook(Books books);
//删除
int deleteBook(@Param("bookID") int bookID);
//修改
int updateBook(Books books);
//查询by id
Books queryBookById(@Param("bookID") int bookID );
//查询all
List<Books> queryBookAll();
}
BookMapper.xml
<?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.ccc.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into books (bookName, bookCounts, detail)
values (#{bookName}, #{bookCounts}, #{detail});
</insert>
<delete id="deleteBook" >
delete
from books
where bookID = #{bookID};
</delete>
<update id="updateBook" parameterType="Books" >
update books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID};
</update>
<select id="queryBookById" resultType="Books">
select * from books where bookID = #{bookID};
</select>
<select id="queryBookAll" resultType="Books">
select * from books;
</select>
</mapper>
7,Service层
BookService****
package com.ccc.service;
import com.ccc.pojo.Books;
import java.util.List;
public interface BookService {
//增加
int addBook(Books books);
//删除
int deleteBook( int bookID);
//修改
int updateBook(Books books);
//查询by id
Books queryBookById( int bookID );
//查询all
List<Books> queryBookAll();
}
BookServiceImpl
package com.ccc.service;
import com.ccc.dao.BookMapper;
import com.ccc.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
//组合Mapper
private BookMapper mapper;
public void setMapper(BookMapper mapper) {
this.mapper = mapper;
}
@Override
public int addBook(Books books) {
return mapper.addBook(books);
}
@Override
public int deleteBook(int bookID) {
return mapper.deleteBook(bookID);
}
@Override
public int updateBook(Books books) {
return mapper.updateBook(books);
}
@Override
public Books queryBookById(int bookID) {
return mapper.queryBookById(bookID);
}
@Override
public List<Books> queryBookAll() {
return mapper.queryBookAll();
}
}
3,Spring配置
1,配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;
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 http://www.springframework.org/schema/beans/spring-beans.xsd ">
<import resource="classpath:spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
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">
<!--1.关联数据库配置-->
<context:property-placeholder location="classpath:db.properties"/>
<!--2.连接池 dbcp-半自动化, c3p0-自动化, druid-->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
<property name="user" value="${jdbc.username}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4, 配置dao接口扫描包, 实现了Dao接口可以动态注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--扫描dao包-->
<property name="basePackage" value="com.ccc.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">
<!--1,扫描service-->
<context:component-scan base-package="com.ccc.service"/>
<!--2,把业务类注入到Spring, 可以配置或注解-->
<bean id="BookServiceImpl" class="com.ccc.service.BookServiceImpl">
<property name="mapper" ref="bookMapper"/>
</bean>
<!--3,声明式事物方法-->
<!--3.1开启 Spring 的事务处理功能-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg name="dataSource" ref="datasource" />
</bean>
<!--3.2结合AOP实现事务的接入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--事务传播新特性 propagation="REQUIRED"(默认) -->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--3.3配置事务切入-->
<aop:config >
<!--配置切入点-->
<aop:pointcut id="txPoint" expression="execution(* com.ccc.dao.*.*(..))"/>
<aop:pointcut id="txPoint2" expression="execution(* *.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
</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"
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">
<!-- 1,自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.ccc.controller"/>
<!-- 2,让Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler />
<!--
3,支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<mvc:annotation-driven />
<!-- 4,视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
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">
<!--1,配置DispatchServlet: SpringMVC的核心, 请求分发器, 前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--DispatchServlet要绑定Spring的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别:1(跟服务器一起启动)-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--
/ 和/* 的区别
/: 只匹配所有的请求, 不会去匹配jsp页面
/*: 匹配所有的请求, 包括jsp页面
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--2,乱码过滤-->
<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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--3,session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
4,Controller
package com.ccc.controller;
import com.ccc.pojo.Books;
import com.ccc.service.BookService;
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.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的book
@RequestMapping("/allBook")
public String queryAll(Model model){
List<Books> books = bookService.queryBookAll();
model.addAttribute("list",books);
return "allBook";
}
}
5,页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 20px;
}
h1{
width: 200px;
height: 40px;
margin: 100px auto;
text-align: center;
line-height: 40px;
background: aqua;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>
<a href="${pageContext.request.contextPath}/book/allBook">进入allBook</a>
</h1>
</body>
</html>
allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>allBook</title>
<%--BootSrap美化页面--%>
<link href="http://cdn.static.runoob.com/libs/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>
<small>书籍列表</small>
</h1>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 colum">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
</tr>
</thead>
<%--foreach遍历list--%>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
6,测试
5.2,实现增删改查操作
1,页面jsp
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 20px;
}
h1{
width: 200px;
height: 40px;
margin: 100px auto;
text-align: center;
line-height: 40px;
background: aqua;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>
<a href="${pageContext.request.contextPath}/book/allBook">进入allBook</a>
</h1>
</body>
</html>
allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>allBook</title>
<%--BootSrap美化页面--%>
<link href="http://cdn.static.runoob.com/libs/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>
<small>书籍列表</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/jump/addBook">新增书籍</a>
</div>
<div class="col-md-4 column">
<%--查询书籍--%>
<form action="${pageContext.request.contextPath}/book/queryBookByName" method="post">
<input type="text" name="bookName" class="form-inline" placeholder="请输入书籍名称"/>
<input type="submit" value="查询" class="btn btn-primary"/><br/>
<span style="color:red;font-weight: bold">${error}</span>
</form>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 colum">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<%--foreach遍历list--%>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/jump/updateBook/${book.bookID}">修改</a> |
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>addBook</title>
<%--BootSrap美化页面--%>
<link href="http://cdn.static.runoob.com/libs/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>
<small>新增书籍</small>
</h1>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label for="bookName">书籍名称</label>
<input type="text" class="form-control" name="bookName" id="bookName" required>
</div>
<div class="form-group">
<label for="bookCounts">书籍数量</label>
<input type="text" class="form-control" name="bookCounts" id="bookCounts" required>
</div>
<div class="form-group">
<label for="detail">书籍描述</label>
<input type="text" class="form-control" name="detail" id="detail" required>
</div>
<button type="submit" class="btn btn-default">添加</button>
</form>
</div>
</div>
</body>
</html>
updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>addBook</title>
<%--BootSrap美化页面--%>
<link href="http://cdn.static.runoob.com/libs/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>
<small>修改书籍</small>
</h1>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.bookID}">
<div class="form-group">
<label for="bookName">书籍名称</label>
<input type="text" class="form-control" name="bookName" id="bookName" required value="${book.bookName}">
</div>
<div class="form-group">
<label for="bookCounts">书籍数量</label>
<input type="text" class="form-control" name="bookCounts" id="bookCounts" required value="${book.bookCounts}">
</div>
<div class="form-group">
<label for="detail">书籍描述</label>
<input type="text" class="form-control" name="detail" id="detail" required value="${book.detail}">
</div>
<button type="submit" class="btn btn-default">修改</button>
</form>
</div>
</div>
</body>
</html>
2,Mapper
增加了一个查询方法
BookMapper
List<Books> queryBookByName(String bookName);
BookMapper.xml
<select id="queryBookByName" resultType="Books">
select * from books
<where>
<if test="bookName!=null">
bookName like "%"#{bookName}"%"
</if>
</where>
</select>
3,Controller
package com.ccc.controller;
import com.ccc.pojo.Books;
import com.ccc.service.BookService;
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 org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的book
@RequestMapping("/allBook")
public String queryAll(Model model){
List<Books> books = bookService.queryBookAll();
model.addAttribute("list",books);
return "allBook";
}
//跳转页面--增删改页面跳转
// @RequestMapping("/jump/{page}/{id}")
@RequestMapping(value = {"/jump/{page}","/jump/{page}/{id}"})//id可以为空
public String jumpPage(@PathVariable String page,@PathVariable(required = false) Integer id, Model model){
if ("updateBook".equals(page)){
Books book = bookService.queryBookById(id);
model.addAttribute("book",book);
return "updateBook";
}else if ("addBook".equals(page)){
return "addBook";
}else {
return "error";
}
}
//添加书籍请求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("addBook"+books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
//修改书籍请求
@RequestMapping("/updateBook")
public String updateBook(Books books){
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//修改书籍请求
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable Integer id){
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
//查询书籍
@RequestMapping("/queryBookByName")
public String queryBookByName(String bookName,Model model){
List<Books> list = bookService.queryBookByName(bookName);
if (list.size()<1){
model.addAttribute("error","无数据 ! 请重新输入 ! ");
}else {
model.addAttribute("list",list);
}
return "allBook";
}
}
4,测试
主页
新增书籍
查询后跳转allBook
修改书籍
修改后跳转allBook
删除
查询
5.3,实现登录功能(为拦截器准备)
1,UserMapper
public interface UserMapper {
//查询用户(登录)
User login(@Param("userCode") String userCode,@Param("userPwd") String userPwd);
//添加用户(注册)
int addUser(User user);
//查询用户数
int queryUserCount(@Param("userCode") String userCode);
}
2,UserMapper.xml
<?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.ccc.mapper.UserMapper">
<!--开启全局缓存,第二步-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
<insert id="addUser" parameterType="User">
insert into user (userID, userCode, userPwd, userName)
values (#{userID}, #{userCode}, #{userPwd}, #{userName});
</insert>
<select id="login" resultType="User">
select * from user where userCode = #{userCode} and userPwd = #{userPwd}
</select>
<select id="queryUserCount" resultType="int">
select count(1) from user
<where>
<if test="userCode!=null and userCode!=''">
userCode = #{userCode}
</if>
</where>
</select>
</mapper>
3,UserService
public interface UserService {
//查询用户(登录)
User login(String userCode, String userPwd);
//添加用户(注册)
int addUser(User user);
//查询用户数
int queryUserCount(String userCode);
}
4,UserServiceImpl
public class UserServiceImpl implements UserService{
public UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public User login(String userName, String userPwd) {
return userMapper.login(userName,userPwd);
}
@Override
public int addUser(User user) {
return userMapper.addUser(user);
}
@Override
public int queryUserCount(String userCode) {
return userMapper.queryUserCount(userCode);
}
}
5,mybatis-config.xml
- 添加UserMapper
- 开启缓存
<?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>
<settings>
<!--开启日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--开启全局缓存,第一步-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--配置数据源, 交给Spring去做-->
<typeAliases>
<package name="com.ccc.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.ccc.mapper.BooksMapper"/>
<mapper class="com.ccc.mapper.UserMapper"/>
</mappers>
</configuration>
6,spring-service.xml
- 注入userMapper
<!--2,把业务类注入到Spring, 已使用注解-->
<bean id="BooksServiceImpl" class="com.ccc.service.BooksServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<bean id="UserServiceImpl" class="com.ccc.service.UserServiceImpl">
<property name="userMapper" ref="userMapper"/>
</bean>
7,工具类
Constant
package com.ccc.utils;
public class Constant {
//session存用户
public static final String USER_SESSION = "USER_SESSION";
//session存msg
public static final String MSG_SESSION = "msg";
}
UuidUtil
import java.util.UUID;
public class UuidUtil {
public static String getUuid(){
//replaceAll("-","") 把-换成空
//return UUID.randomUUID().toString().replaceAll("-","");
return UUID.randomUUID().toString();
}
}
8,UserController
package com.ccc.controller;
import com.ccc.pojo.User;
import com.ccc.service.UserService;
import com.ccc.utils.Constant;
import com.ccc.utils.UuidUtil;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
public UserService service;
//页面跳转
@RequestMapping("/jump/{page}")
public String jumpPage(@PathVariable String page,HttpServletRequest req){
if ( "register".equals(page) ) {
return "register";
}else if( "logout".equals(page) ) {//先清session再跳转登录页面
if (req.getSession().getAttribute(Constant.USER_SESSION) != null)
req.getSession().removeAttribute(Constant.USER_SESSION);
return "../../index";
}
return "error";
}
//用户登录
@RequestMapping("/login")
public String login(String userCode, String userPwd, HttpServletRequest req,Model model){
User user = service.login(userCode, userPwd);
if (user != null) {
req.getSession().setAttribute(Constant.USER_SESSION,user);
return "redirect:/book/allBook";
}
model.addAttribute(Constant.MSG_SESSION,"用户名或密码错误! 请重试");
return "../../index";
}
//用户注册
@RequestMapping("/register")
public String registerUser(User user,Model model){
model.addAttribute("user",user);
int count = service.queryUserCount(user.getUserCode());
if (count == 1) {
model.addAttribute(Constant.MSG_SESSION,"用户名已存在,请重新输入");
return "register";
}else if (count > 1) {
model.addAttribute(Constant.MSG_SESSION,"用户名不合规,请重新输入");
return "register";
}
if ( !StringUtils.isNullOrEmpty(user.getUserName()) && !StringUtils.isNullOrEmpty(user.getUserCode()) && !StringUtils.isNullOrEmpty(user.getUserPwd()) ) {
user.setUserID(UuidUtil.getUuid());
int i = service.addUser(user);
if (i == 1) {
model.addAttribute(Constant.MSG_SESSION,"注册成功!");
return "../../index";
}
}
model.addAttribute(Constant.MSG_SESSION,"注册失败! 请重试");
return "register";
}
}
9,页面
登录index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<title>登录</title>
<link href="favicon.ico" rel="shortcut icon" />
<link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<%--背景图片--%>
<%--<body style=" background: url(https://gimg2.baidu.com/image_search/src=http); background-size: 100%;">--%>
<body style=" background-color: #D9AFD9;
background-image: linear-gradient(312deg, #D9AFD9 0%, #97D9E1 100%); background-size: 100%;"><%--渐变色--%>
<div class="modal-dialog" style="margin-top: 10%;">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title text-center" id="myModalLabel">登录</h4><span style="color: red">${msg}</span>
</div>
<form action="${pageContext.request.contextPath}/user/login" method="post">
<div class="modal-body" id = "model-body">
<div class="form-group">
<input type="text" name="userCode" class="form-control"placeholder="用户名" autocomplete="off" required>
</div>
<div class="form-group">
<input type="password" name="userPwd" class="form-control" placeholder="密码" autocomplete="off" required>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<%-- <button type="button" class="btn btn-primary form-control">登录</button>--%>
<input type="submit" class="btn btn-primary form-control" value="登录">
</div>
<div class="form-group">
<%-- <button type="button" class="btn btn-default form-control">注册</button>--%>
<a href="${pageContext.request.contextPath}/user/jump/register" type="button" class="btn btn-default form-control">注册</a>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
注册register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<title>注册</title>
<link href="favicon.ico" rel="shortcut icon" />
<link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style=" background-color: #FFFFFF;
background-image: linear-gradient(180deg, #FFFFFF 0%, #6762ff 50%, #FF0000 100%);
background-size: 100%;">
<div class="modal-dialog" style="margin-top: 10%;">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title text-center" id="myModalLabel">注册</h4><span style="color: red">${msg}</span>
</div>
<form action="${pageContext.request.contextPath}/user/register" method="post">
<div class="modal-body" id = "model-body">
<div class="form-group">
<input type="text" name="userCode" class="form-control"placeholder="用户名" autocomplete="off" required value="${user.userCode}">
</div>
<div class="form-group">
<input type="password" name="userPwd" class="form-control" placeholder="密码" autocomplete="off" required value="${user.userPwd}">
</div>
<div class="form-group">
<input type="text" name="userName" class="form-control" placeholder="真实姓名" autocomplete="off" required value="${user.userName}">
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<%-- <button type="button" class="btn btn-primary form-control">登录</button>--%>
<input type="submit" class="btn btn-primary form-control" value="注册">
</div>
<div class="form-group">
<%-- <button type="button" class="btn btn-default form-control">注册</button>--%>
<a href="${pageContext.request.contextPath}/user/jump/logout" type="button" class="btn btn-default form-control">返回</a>
</div>
</div>
</form>
</div>
</div>
</body>
</html>