学习及资源途径:狂神说java
1.ssm整合:Mybatis层
数据库
CREATE DATABASE ssmbuild;
USE ssmbuild;
CREATE TABLE `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT 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,'从进门到进牢');
SELECT * FROM books;
创建Maven项目
导入依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<!-- <dependency>-->
<!-- <groupId>c3p0</groupId>-->
<!-- <artifactId>c3p0</artifactId>-->
<!-- <version>0.9.1.2</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
mybatis配置文件 mybtais-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.hongkai.pojo"/>
</typeAliases>
</configuration>
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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
数据库配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuilduseSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=128730
建立实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
Mapper接口
public interface BooksMapper {
//获取所有数书籍
List<Books> getBooks();
//添加书籍
int addBook(Books books);
//通过id删除书籍
int deleteBookById(@Param("bookID") int id);
//修改书籍
int updateBookById(Books books);
//根据id获取书籍
Books getBookById(@Param("bookID")int id);
}
Mapper.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.hongkai.dao.BooksMapper">
<select id="getBooks" resultType="books">
select * from books
</select>
<insert id="addBook" parameterType="books">
insert into books(bookName,bookCounts,detail) values
(#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete from books where id=#{bookID};
</delete>
<update id="updateBookById" parameterType="books">
update books
<set>
<if test="bookName!=null">bookName=#{bookName},</if>
<if test="bookCounts!=null">bookCounts=#{bookCounts},</if>
<if test="detail!=null">detail=#{detail}</if>
</set>
where bookID=#{bookID};
</update>
<select id="getBookById" resultType="books">
select * from books where bookID=#{bookID};
</select>
</mapper>
在Mybatis配置文件注册mapper.xml
<mappers>
<mapper class="com.hongkai.dao.BooksMapper"/>
</mappers>
service层
public interface BookService {
//获取所有数书籍
List<Books> getBooks();
//添加书籍
int addBook(Books books);
//通过id删除书籍
int deleteBookById(int id);
//修改书籍
int updateBookById(Books books);
//根据id获取书籍
Books getBookById(int id);
}
serviceImpl 业务层调dao层
public class BookServiceImpl implements BookService{
//调用dao层
private BooksMapper booksMapper;
public void setBooksMapper(BooksMapper booksMapper) {
this.booksMapper = booksMapper;
}
@Override
public List<Books> getBooks() {
return booksMapper.getBooks();
}
@Override
public int addBook(Books books) {
return booksMapper.addBook(books);
}
@Override
public int deleteBookById(int id) {
return booksMapper.deleteBookById(id);
}
@Override
public int updateBookById(Books books) {
return booksMapper.updateBookById(books);
}
@Override
public Books getBookById(int id) {
return booksMapper.getBookById(id);
}
}
2.ssm整合:Spring层
整合Dao层 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.关联数据库配置-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2.连接池
dbcp:半自动化操作 不能自动连接
c3p0:自动化操作
-->
<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}"/>
</bean>
<!--3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4.配置dao接口扫描包 动态的实现了Dao接口可以注入到Soring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入 sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的包-->
<property name="basePackage" value="com.hongkai.dao"/>
</bean>
</beans>
整合Service层 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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.扫描service下的包-->
<context:component-scan base-package="com.hongkai.service"/>
<!--2.将所有业务类注入到spring 通过配置或者注解实现-->
<bean id="BookServiceImpl" class="com.hongkai.service.BookServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<!--3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.aop事务支持-->
</beans>
3.ssm整合:SpringMVC层
增加web的支持
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.注册 DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--管理一个springmvc的配置文件-->
<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>
<!--2.乱码过滤-->
<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>
<!--3.session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
springmvc-servlet.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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
<context:component-scan base-package="com.hongkai.controller"/>
<!--让spring mvc不处理静态资源 如:.css .js .html .mp3......-->
<mvc:default-servlet-handler/>
<!--完成handlerMapping handlerAdapter两个实例的注册-->
<mvc:annotation-driven/>
<!--ViewResolver(视图解析器):DispatcherServlet给它的ModeAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
到此所有配置完成了,开始进入秀操作时间!
查询书籍功能
BookController
@Controller
@RequestMapping("/book")
public class BookController {
//controller调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部书籍 并返回一个书籍展示页面
@RequestMapping("/allBooks")
public String getAllBooks(Model model){
List<Books> booksList = bookService.getBooks();
model.addAttribute("list",booksList);
return "allBooks";
}
}
index.jsp
<%--
Created by IntelliJ IDEA.
User: Hongkai
Date: 2022/5/29
Time: 20:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style>
h3{
width:180px;
height: 30px;
margin: 100px auto;
text-align: center;
line-height: 38px;
}
a{
text-decoration: none;
color: aqua;
font-size: 18px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBooks">进入书籍页面</a>
</h3>
</body>
</html>
allBooks.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Hongkai
Date: 2022/5/29
Time: 20:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<small>书籍列表-----------显示所有书籍</small>
</div>
</div>
<div class="row">
<div class="col-md-4 colum">
<a class="btn btn-default" href="${pageContext.request.contextPath}/book/toAddBook" role="button">新增书籍</a>
<a class="btn btn-default" href="${pageContext.request.contextPath}/book/allBooks" role="button">显示全部书籍</a>
</div>
<div class="col-md-4 col-md-offset-4 colum " style="">
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post">
<div class="form-group">
<input type="text" name="queryBook" class="form-control" id="exampleInputEmail2" placeholder="请输入你要搜索的书籍名称" onkeyup="this.value=this.value.replace(/[, ]/g,'')">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<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/toUpdateBook?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
遭遇bug
1.通配符的匹配很全面, 但无法找到元素 'context:property-placeholder
原因:spring-dao.xml文件中
头文件配置不全
2.Receiver class com.mchange.v2.c3p0.impl.NewProxyResultSet does not define or inherit an implementation of the resolved method 'abstract boolean isClosed()' of interface java.sql.ResultSet.
原因:大致意思就是我配置的c3p0依赖等级低了
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency><dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
之前配置的是上面哪个,版本低了,换成下面哪个,然后还是报错
先去out文件夹lib里面把之前的那个依赖删掉,再将依赖重新导入到lib目录后成功!
增加书籍
//跳转的新增书籍页面
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("books--->"+books);
bookService.addBook(books);
return "redirect:/book/allBooks";//重定向到@RequestMapping("/allBooks")
}
addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Hongkai
Date: 2022/5/29
Time: 20:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</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>
<form action="${pageContext.request.contextPath}/book/addBook" method="" class="form-horizontal">
<div class="form-group">
<label for="bkId" class="col-sm-2 control-label">书籍编号</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkId" name="bookID" required>
</div>
</div>
<div class="form-group">
<label for="bkName" class="col-sm-2 control-label">书籍名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkName" name="bookName" required>
</div>
</div>
<div class="form-group">
<label for="bkCount" class="col-sm-2 control-label">书籍数量</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkCount" name="bookCounts" required>
</div>
</div>
<div class="form-group">
<label for="bkDetail" class="col-sm-2 control-label">书籍详情</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkDetail" name="detail" required>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">提交</button>
</div>
</form>
</div>
</body>
</html>
修改书籍
//跳转的修改书籍页面
@RequestMapping("/toUpdateBook")
public String toUpdateBook(int id,Model model){
Books books = bookService.getBookById(id);
model.addAttribute("queryBooks",books);
return "updateBook";
}
//修改书籍的请求
@RequestMapping("/updateBook")
public String updateBookk(Books books){
System.out.println("books--->"+books);
bookService.updateBookById(books);
return "redirect:/book/allBooks";//重定向到@RequestMapping("/allBooks")
}
updateBook.jsp
<%--
Created by IntelliJ IDEA.
User: Hongkai
Date: 2022/5/30
Time: 17:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</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>
<form action="${pageContext.request.contextPath}/book/updateBook" method="" class="form-horizontal">
<%--隐藏域--%>
<input type="hidden" name="bookID" value="${queryBooks.bookID}">
<div class="form-group">
<label for="bkName" class="col-sm-2 control-label">书籍名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkName" name="bookName" value="${queryBooks.bookName}" required>
</div>
</div>
<div class="form-group">
<label for="bkCount" class="col-sm-2 control-label">书籍数量</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkCount" name="bookCounts" value="${queryBooks.bookCounts}" required>
</div>
</div>
<div class="form-group">
<label for="bkDetail" class="col-sm-2 control-label">书籍详情</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="bkDetail" name="detail" value="${queryBooks.detail}" required>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">提交</button>
</div>
</form>
</div>
</body>
</html>
删除书籍
//删除书籍的请求
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBooks";//重定向到@RequestMapping("/allBooks")
}
增加用户查询书籍功能
BookMapper
//查询书籍
Books queryBookByName(@Param("bookName") String bookName);
BookMapper.xml
<select id="queryBookByName" resultType="books">
select * from books where bookName=#{bookName}
</select>
BookService
//查询书籍
Books queryBookByName(String bookName);
BookServiceImpl
@Override
public Books queryBookByName(String bookName) {
return booksMapper.queryBookByName(bookName);
}
controller
//查询一本书
@RequestMapping("/queryBook")
public String queryBook(String queryBook,Model model){
Books books = bookService.queryBookByName(queryBook);
List<Books> booksArrayList = new ArrayList<>();
booksArrayList.add(books);
if (books==null){
booksArrayList=bookService.getBooks();
}
model.addAttribute("list",booksArrayList);
return "allBooks";
}
用户登录
创建一个简单的数据库表 就三个字段id 用户名 密码
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int userId;
private String userCode;
private String userPassword;
}
login.jsp
<%--
Created by IntelliJ IDEA.
User: Hongkai
Date: 2022/5/31
Time: 10:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#wrap{
height: 200px;
margin: 100px;
padding: 30px;
background-color: aqua;
}
</style>
</head>
<body>
<h2>欢迎来到登录页面</h2>
<div class="snippet-container" id="wrap">
<form class="form-horizontal" action="/user/login" method="post">
<div class="form-group">
<label for="inputUserCode" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="inputUserCode" name="userCode" placeholder="userCode">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">密码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="inputPassword" name="userPassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">登录</button>
</div>
</div>
<span style="color: red">${error}</span>
</form>
</div>
</body>
</html>
UserMapper
public interface UserMapper {
//根据用户名密码查询用户 登录
public User loginByNameAndPwd(@Param("userCode") String userCode, @Param("userPassword") String userPassword);
}
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.hongkai.dao.user.UserMapper">
<select id="loginByNameAndPwd" resultType="user">
select * from user where userCode=#{userCode} and userPassword=#{userPassword}
</select>
</mapper>
UserService
public interface UserService {
//根据用户名密码查询用户 登录
public User loginByNameAndPwd(String userCode,String userPassword);
}
UserServiceImpl
public class UserServiceImpl implements UserService{
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public User loginByNameAndPwd(String userCode, String userPassword) {
return userMapper.loginByNameAndPwd(userCode,userPassword);
}
LoginController 登录以及注销
package com.hongkai.controller;
import com.hongkai.pojo.User;
import com.hongkai.service.user.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.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class LoginController {
@Autowired
@Qualifier("UserServiceImpl")
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
//进入登录界面
@RequestMapping("/goLogin")
public String goLogin(){
return "login";
}
//验证登录之后进入书籍展示页面
@RequestMapping("/login")
public String login(String userCode, String userPassword, HttpSession session, Model model){
User user = userService.loginByNameAndPwd(userCode, userPassword);
if (user!=null){
//将用户信息保存
session.setAttribute("userInfo",user);
return "redirect:/book/allBooks";
}else {
model.addAttribute("error","账号或者密码错误,请重新输入!");
return "login";
}
}
//注销
@RequestMapping("/loginOut")
public String login(HttpSession session, Model model){
session.removeAttribute("userInfo");
return "login";
}
}
拦截器
如果没有登录不允许进入到书籍展示页面
获取用户的session---》userInfo 如果不存在判断用户没有登录 将用户拦截在登录界面
LoginFilter
package com.hongkai.filter;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginFilter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断什么时候登录
HttpSession session = request.getSession();
//登录页面放行 不然进不去登录页面
if (request.getRequestURI().contains("goLogin")){
return true;
}
//第一次登录也没session
if (request.getRequestURI().contains("login")){
return true;
}
// 判断是否有用户的session 有代表以及登陆过
if(session.getAttribute("userInfo")!=null){
//有人登录过 放行
return true;
}
//没有登录
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
}
在applicationContext.xml注册拦截器
<!-- 用户登录拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.hongkai.filter.LoginFilter"/>
</mvc:interceptor>
</mvc:interceptors>