12.图书借阅系统和SpringMVC拦截器

 

图书借阅系统

项目目录结构:

项目依赖包:

Entity

entity: BookInfo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.course.entity;

import java.util.Date;

public class BookInfo {
private Integer bookid;

private String bookname;

private String booktype;

private String bookauthor;

private String publishpress;

private Date publishdate;

private Integer borrowStatus;

private String createdUser;

private Date createdTime;

private Date lastUpdateTime;

public Integer getBookid() {
return bookid;
}

public void setBookid(Integer bookid) {
this.bookid = bookid;
}

public String getBookname() {
return bookname;
}

public void setBookname(String bookname) {
this.bookname = bookname == null ? null : bookname.trim();
}

public String getBooktype() {
return booktype;
}

public void setBooktype(String booktype) {
this.booktype = booktype == null ? null : booktype.trim();
}

public String getBookauthor() {
return bookauthor;
}

public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor == null ? null : bookauthor.trim();
}

public String getPublishpress() {
return publishpress;
}

public void setPublishpress(String publishpress) {
this.publishpress = publishpress == null ? null : publishpress.trim();
}

public Date getPublishdate() {
return publishdate;
}

public void setPublishdate(Date publishdate) {
this.publishdate = publishdate;
}

public Integer getBorrowStatus() {
return borrowStatus;
}

public void setBorrowStatus(Integer borrowStatus) {
this.borrowStatus = borrowStatus;
}

public String getCreatedUser() {
return createdUser;
}

public void setCreatedUser(String createdUser) {
this.createdUser = createdUser == null ? null : createdUser.trim();
}

public Date getCreatedTime() {
return createdTime;
}

public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}

public Date getLastUpdateTime() {
return lastUpdateTime;
}

public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
}

Vo

vo: BookInfoVo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.course.vo;

import com.course.entity.BookInfo;

public class BookInfoVo extends BookInfo {

private Integer pageIndex;

public Integer getPageIndex() {
return pageIndex;
}

public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
}

vo: Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.course.vo;

import java.util.Date;

public class Student {
private Integer userid;

private String usercode;

private String password;

private String email;

private String gender;

private Date registerTime;

private Date lastLoginTime;

public Integer getUserid() {
return userid;
}

public void setUserid(Integer userid) {
this.userid = userid;
}

public String getUsercode() {
return usercode;
}

public void setUsercode(String usercode) {
this.usercode = usercode == null ? null : usercode.trim();
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender == null ? null : gender.trim();
}

public Date getRegisterTime() {
return registerTime;
}

public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}

public Date getLastLoginTime() {
return lastLoginTime;
}

public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
}

Dao

Dao: BookInfoMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.course.dao;

import java.util.List;

import com.course.entity.BookInfo;

public interface BookInfoMapper {

int deleteByPrimaryKey(Integer bookid);

int insert(BookInfo record);

int insertSelective(BookInfo record);

BookInfo selectByPrimaryKey(Integer bookid);

int updateByPrimaryKeySelective(BookInfo record);

int updateByPrimaryKey(BookInfo record);

// 查询图书列表
public List<BookInfo> queryBookList(BookInfo bookInfo);

}

Dao: StudentMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.course.dao;

import com.course.vo.Student;

public interface StudentMapper {

int deleteByPrimaryKey(Integer userid);

int insert(Student record);

int insertSelective(Student record);

Student selectByPrimaryKey(Integer userid);

int updateByPrimaryKeySelective(Student record);

int updateByPrimaryKey(Student record);

// 用户登录
Student login(Student student);

}

Mapper.xml

BookInfoMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<?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.course.dao.BookInfoMapper">
<resultMap id="BaseResultMap" type="com.course.entity.BookInfo">
<id column="bookid" jdbcType="INTEGER" property="bookid" />
<result column="bookname" jdbcType="VARCHAR" property="bookname" />
<result column="booktype" jdbcType="VARCHAR" property="booktype" />
<result column="bookauthor" jdbcType="VARCHAR" property="bookauthor" />
<result column="publishpress" jdbcType="VARCHAR" property="publishpress" />
<result column="publishdate" jdbcType="TIMESTAMP" property="publishdate" />
<result column="borrow_status" jdbcType="INTEGER" property="borrowStatus" />
<result column="created_user" jdbcType="VARCHAR" property="createdUser" />
<result column="created_time" jdbcType="TIMESTAMP" property="createdTime" />
<result column="last_update_time" jdbcType="TIMESTAMP" property="lastUpdateTime" />
</resultMap>

<sql id="Base_Column_List">
bookid, bookname, booktype, bookauthor, publishpress, publishdate, borrow_status,
created_user, created_time, last_update_time
</sql>

<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from bookinfo
where bookid = #{bookid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from bookinfo
where bookid = #{bookid,jdbcType=INTEGER}
</delete>

<insert id="insert" parameterType="com.course.entity.BookInfo">
insert into bookinfo (bookid, bookname, booktype,
bookauthor, publishpress, publishdate,
borrow_status, created_user, created_time,
last_update_time)
values (#{bookid,jdbcType=INTEGER}, #{bookname,jdbcType=VARCHAR}, #{booktype,jdbcType=VARCHAR},
#{bookauthor,jdbcType=VARCHAR}, #{publishpress,jdbcType=VARCHAR}, #{publishdate,jdbcType=TIMESTAMP},
#{borrowStatus,jdbcType=INTEGER}, #{createdUser,jdbcType=VARCHAR}, #{createdTime,jdbcType=TIMESTAMP},
#{lastUpdateTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.course.entity.BookInfo">
insert into bookinfo
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="bookid != null">
bookid,
</if>
<if test="bookname != null">
bookname,
</if>
<if test="booktype != null">
booktype,
</if>
<if test="bookauthor != null">
bookauthor,
</if>
<if test="publishpress != null">
publishpress,
</if>
<if test="publishdate != null">
publishdate,
</if>
<if test="borrowStatus != null">
borrow_status,
</if>
<if test="createdUser != null">
created_user,
</if>
<if test="createdTime != null">
created_time,
</if>
<if test="lastUpdateTime != null">
last_update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="bookid != null">
#{bookid,jdbcType=INTEGER},
</if>
<if test="bookname != null">
#{bookname,jdbcType=VARCHAR},
</if>
<if test="booktype != null">
#{booktype,jdbcType=VARCHAR},
</if>
<if test="bookauthor != null">
#{bookauthor,jdbcType=VARCHAR},
</if>
<if test="publishpress != null">
#{publishpress,jdbcType=VARCHAR},
</if>
<if test="publishdate != null">
#{publishdate,jdbcType=TIMESTAMP},
</if>
<if test="borrowStatus != null">
#{borrowStatus,jdbcType=INTEGER},
</if>
<if test="createdUser != null">
#{createdUser,jdbcType=VARCHAR},
</if>
<if test="createdTime != null">
#{createdTime,jdbcType=TIMESTAMP},
</if>
<if test="lastUpdateTime != null">
#{lastUpdateTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>

<update id="updateByPrimaryKeySelective" parameterType="com.course.entity.BookInfo">
update bookinfo
<set>
<if test="bookname != null">
bookname = #{bookname,jdbcType=VARCHAR},
</if>
<if test="booktype != null">
booktype = #{booktype,jdbcType=VARCHAR},
</if>
<if test="bookauthor != null">
bookauthor = #{bookauthor,jdbcType=VARCHAR},
</if>
<if test="publishpress != null">
publishpress = #{publishpress,jdbcType=VARCHAR},
</if>
<if test="publishdate != null">
publishdate = #{publishdate,jdbcType=TIMESTAMP},
</if>
<if test="borrowStatus != null">
borrow_status = #{borrowStatus,jdbcType=INTEGER},
</if>
<if test="createdUser != null">
created_user = #{createdUser,jdbcType=VARCHAR},
</if>
<if test="createdTime != null">
created_time = #{createdTime,jdbcType=TIMESTAMP},
</if>
<if test="lastUpdateTime != null">
last_update_time = #{lastUpdateTime,jdbcType=TIMESTAMP},
</if>
</set>
where bookid = #{bookid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.course.entity.BookInfo">
update bookinfo
set bookname = #{bookname,jdbcType=VARCHAR},
booktype = #{booktype,jdbcType=VARCHAR},
bookauthor = #{bookauthor,jdbcType=VARCHAR},
publishpress = #{publishpress,jdbcType=VARCHAR},
publishdate = #{publishdate,jdbcType=TIMESTAMP},
borrow_status = #{borrowStatus,jdbcType=INTEGER},
created_user = #{createdUser,jdbcType=VARCHAR},
created_time = #{createdTime,jdbcType=TIMESTAMP},
last_update_time = #{lastUpdateTime,jdbcType=TIMESTAMP}
where bookid = #{bookid,jdbcType=INTEGER}
</update>

<!-- 查询图书列表 -->
<select id="queryBookList" parameterType="com.course.entity.BookInfo" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from bookinfo
<where>
<if test="booktype != null and booktype != 0">booktype = #{booktype}</if>
<if test="bookname != null and bookname != ''">and bookname like "%"#{bookname}"%"</if>
<if test="borrowStatus != null and borrowStatus != 0">and borrow_status = #{borrowStatus}</if>
</where>
</select>

</mapper>

StudentMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?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.course.dao.StudentMapper" >
<resultMap id="BaseResultMap" type="com.course.vo.Student" >
<id column="userid" property="userid" jdbcType="INTEGER" />
<result column="usercode" property="usercode" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="gender" property="gender" jdbcType="CHAR" />
<result column="register_time" property="registerTime" jdbcType="TIMESTAMP" />
<result column="last_login_time" property="lastLoginTime" jdbcType="TIMESTAMP" />
</resultMap>

<sql id="Base_Column_List" >
userid, usercode, password, email, gender, register_time, last_login_time
</sql>

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from student
where userid = #{userid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from student
where userid = #{userid,jdbcType=INTEGER}
</delete>

<insert id="insert" parameterType="com.course.vo.Student" >
insert into student (userid, usercode, password,
email, gender, register_time,
last_login_time)
values (#{userid,jdbcType=INTEGER}, #{usercode,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, #{registerTime,jdbcType=TIMESTAMP},
#{lastLoginTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.course.vo.Student" >
insert into student
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userid != null" >
userid,
</if>
<if test="usercode != null" >
usercode,
</if>
<if test="password != null" >
password,
</if>
<if test="email != null" >
email,
</if>
<if test="gender != null" >
gender,
</if>
<if test="registerTime != null" >
register_time,
</if>
<if test="lastLoginTime != null" >
last_login_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userid != null" >
#{userid,jdbcType=INTEGER},
</if>
<if test="usercode != null" >
#{usercode,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="gender != null" >
#{gender,jdbcType=CHAR},
</if>
<if test="registerTime != null" >
#{registerTime,jdbcType=TIMESTAMP},
</if>
<if test="lastLoginTime != null" >
#{lastLoginTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>

<update id="updateByPrimaryKeySelective" parameterType="com.course.vo.Student" >
update student
<set >
<if test="usercode != null" >
usercode = #{usercode,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="gender != null" >
gender = #{gender,jdbcType=CHAR},
</if>
<if test="registerTime != null" >
register_time = #{registerTime,jdbcType=TIMESTAMP},
</if>
<if test="lastLoginTime != null" >
last_login_time = #{lastLoginTime,jdbcType=TIMESTAMP},
</if>
</set>
where userid = #{userid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.course.vo.Student" >
update student
set usercode = #{usercode,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
gender = #{gender,jdbcType=CHAR},
register_time = #{registerTime,jdbcType=TIMESTAMP},
last_login_time = #{lastLoginTime,jdbcType=TIMESTAMP}
where userid = #{userid,jdbcType=INTEGER}
</update>

<!-- 用户登录 -->
<select id="login" resultMap="BaseResultMap" parameterType="com.course.vo.Student" >
select
<include refid="Base_Column_List" />
from student
<where>
usercode = #{usercode} and password = #{password}
</where>
</select>
</mapper>

Service

BookInfoService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.course.service;

import java.util.List;

import com.course.entity.BookInfo;
import com.course.util.PageBean;

public interface BookInfoService {

public List<BookInfo> queryBookListByPage(PageBean pageBean, BookInfo bookInfo);

public void borrowBook(Integer bookid);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.course.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.course.dao.BookInfoMapper;
import com.course.entity.BookInfo;
import com.course.service.BookInfoService;
import com.course.util.PageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class BookInfoServiceImpl implements BookInfoService {

@Autowired
private BookInfoMapper bookInfoMapper;

@Override
public List<BookInfo> queryBookListByPage(PageBean pageBean, BookInfo bookInfo) {
Page<BookInfo> page = PageHelper.startPage(pageBean.getPageIndex(), pageBean.getPageSize());
List<BookInfo> bookInfoList = bookInfoMapper.queryBookList(bookInfo);
pageBean.setTotalCount((int) page.getTotal());
return bookInfoList;
}

@Override
public void borrowBook(Integer bookid) {
BookInfo bookInfo = new BookInfo();
bookInfo.setBookid(bookid);
bookInfo.setBorrowStatus(2);
bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
}

}

UserService

1
2
3
4
5
6
7
8
9
10
11
package com.course.service;

import com.course.vo.Student;

public interface UserService {

public Student login(Student student);

public void updateUserLastLoginTime(Student student);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.course.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.course.dao.StudentMapper;
import com.course.service.UserService;
import com.course.vo.Student;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private StudentMapper studentMapper;

@Override
public Student login(Student student) {
return studentMapper.login(student);
}

@Override
public void updateUserLastLoginTime(Student student) {
Date lastLoginTime = new Date();
student.setLastLoginTime(lastLoginTime);
studentMapper.updateByPrimaryKeySelective(student);
}

}

Controller

BookInfoController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.course.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.course.entity.BookInfo;
import com.course.service.BookInfoService;
import com.course.util.PageBean;
import com.course.vo.BookInfoVo;

@Controller
@RequestMapping("bookInfo")
public class BookInfoController {

@Autowired
private BookInfoService bookInfoService;

@RequestMapping("queryBookInfoList")
public String queryBookInfoList(BookInfoVo bookInfoVo, Model model) {
PageBean pageBean = new PageBean();
Integer pageIndex = bookInfoVo.getPageIndex();
if (pageIndex == null) {
pageBean.setPageIndex(1);
} else {
pageBean.setPageIndex(pageIndex);
}
List<BookInfo> bookList = bookInfoService.queryBookListByPage(pageBean, bookInfoVo);
model.addAttribute("bookList", bookList);
model.addAttribute("pageBean", pageBean);

return "bookList";
}

@RequestMapping("borrowBook")
public String borrowBook(Integer bookid) {
bookInfoService.borrowBook(bookid);
return "redirect:../bookInfo/queryBookInfoList.do";
}
}

LoginController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.course.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.course.service.UserService;
import com.course.vo.Student;

@Controller
@RequestMapping("login")
public class LoginController {

@Autowired
private UserService userService;

// 跳转到登录界面
@RequestMapping(value = "jumpToLoginPage", method = RequestMethod.GET)
public String jumpToLoginPage() {
return "login";
}

// 用户登录
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(Student student, HttpSession httpSession, Model model) {
student = userService.login(student);
if (student == null) {
model.addAttribute("message", "登录失败,用户名或密码错误");
return "login";
} else {
userService.updateUserLastLoginTime(student);
httpSession.setAttribute("student", student);
return "redirect:../bookInfo/queryBookInfoList.do";

}
}

}

Util

PageBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.course.util;

public class PageBean {

private Integer pageIndex;
private Integer pageSize = 5;
private Integer totalPage;
private Integer totalCount;

public Integer getPageIndex() {
return pageIndex;
}
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
this.totalPage = (int) Math.ceil((this.totalCount*1.0)/this.pageSize);
}

}

config

log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 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

db.properties

1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springmvc_test
username=root
password=123456

mybatis.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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">

<!-- MyBatis的整体配置 -->
<configuration>

<settings>
<!-- 让log4j去记录sql日志,打印mybatis执行的sql语句 -->
<setting name="logImpl" value="LOG4J"/>
<!-- https://mybatis.org/mybatis-3/zh/configuration.html#properties -->
</settings>

<!-- 使用plugin: PageHelper,不能在application-dao.xml中注入,必须在mybatis.cfg.xml中添加插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

</configuration>

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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">


<!--
配置控制器
包扫描
-->
<context:component-scan base-package="com.course.controller"></context:component-scan>

<!--
合并注解的控制器映射器和控制器适配器的配置
对控制器映射器和控制器适配器进行加强,如把对象转化为json字符串
-->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

</beans>

application-dao.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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">


<!-- 解析配置文件 -->
<!--
${username}在Spring里默认取的是当前的主机名,
如果想禁用取主机名可以使用system-properties-mode="FALLBACK"
-->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="FALLBACK"/>

<!-- 声明数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 注入相关属性 -->
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>

<!-- 声明sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 注入mybatis.cfg.xml -->
<property name="configLocation" value="classpath:mybatis.cfg.xml"></property>


<property name="mapperLocations">
<array>
<value>classpath:com/course/mapper/*.xml</value>
</array>
</property>

<!-- 使用plugin: PageHelper,不能在application-dao.xml中注入,必须在mybatis.cfg.xml中添加插件 -->
<!--
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
-->

</bean>

<!--
配置接口扫描
因为UserMapper.java没有实现类,所以必须依靠cglib在内存中构造代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入mapper接口所在的包 -->
<property name="basePackage" value="com.course.dao"></property>

<!--
如果有多个mapper接口,value可以为数组,用逗号或者换行分割
<property name="basePackage" value="com.course.dao,com.course.dao2"></property>

<property name="basePackage">
<value>
com.course.dao
com.course.dao2
</value>
</property>
-->

<!--
注入sqlSessionFactory
因为是BeanName,所以是value,不是ref
-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

</beans>

application-service.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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">


<!-- 声明式事务的配置开始 -->
<!-- 1.声明事务管理器 -->
<!-- 用Spring自带的事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 2.声明通知方式 -->
<tx:advice id="advice" transaction-manager="transactionManager">
<!-- 配置那些方法要加入事务 -->
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="borrow*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 3.进行AOP配置 -->
<aop:config>
<!-- 声明切面 -->
<!-- 事务应该加在service层,不应该加在dao层 -->
<aop:pointcut id="pc" expression="execution(* com.course.service.impl.*.*(..))"/>
<!-- 织入 -->
<aop:advisor advice-ref="advice" pointcut-ref="pc"/>
</aop:config>
<!-- 声明式事务的配置结束 -->

<!-- 声明Service -->
<!-- <bean id="userService" class="com.course.service.impl.UserServiceImpl" autowire="byType"></bean> -->

<context:component-scan base-package="com.course.service"></context:component-scan>

</beans>

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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">


<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>

</beans>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>05_ssm</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>

<!-- 配置SpringMVC编码过滤器 -->
<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>
<!--
方法1: <url-pattern>*.do</url-pattern>
<url-pattern>/*</url-pattern>
-->
<!-- 指定某个servlet去过滤 -->
<servlet-name>springmvc</servlet-name>
</filter-mapping>

<!-- 配置Spring的监听器,在项目启动时加载applicationContext.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置applicationContext.xml的地址 -->
<context-param>
<!-- ContextLoaderListener的父类ContextLoader的属性 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- 配置前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 加载springmvc.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>

<!-- 启动加载 -->
<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>

jsp

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="login/jumpToLoginPage.do"></jsp:forward>
</body>
</html>

login.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h2 align="center">用户登录</h2>
<hr>
<form action="${pageContext.request.contextPath }/login/login.do" method="post">
<table align="center" width="50%" cellpadding="10">
<tr>
<td align="right">用户名</td>
<td><input type="text" name="usercode"></td>
</tr>
<tr>
<td align="right">密码</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td align="right"><input type="reset" value="重置"></td>
<td><input type="submit" value="登录"></td>
</tr>
</table>
</form>
<h6 style="color: red;" align="center">
${message }
</h6>
</body>
</html>

bookList.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Book List</h1>
<h5>当前用户: ${student.usercode }</h5>
<hr/>
<table align="center" width="60%" border="1" cellspacing="5">
<tr>
<td>
图书分类:
<select name="booktype" id="booktype">
<option value="0" ${bookInfoVo.booktype==0?'selected':'' }>-----请选择-----</option>
<option value="1" ${bookInfoVo.booktype==1?'selected':'' }>科技</option>
<option value="2" ${bookInfoVo.booktype==2?'selected':'' }>历史</option>
<option value="3" ${bookInfoVo.booktype==3?'selected':'' }>文学</option>
</select>
图书名称:
<input type="text" name="bookname" id="bookname" value="${bookInfoVo.bookname }">
是否借阅:
<select name="borrowStatus" id="borrowStatus">
<option value="0" ${bookInfoVo.borrowStatus==0?'selected':'' }>-----请选择-----</option>
<option value="1" ${bookInfoVo.borrowStatus==1?'selected':'' }>未借阅</option>
<option value="2" ${bookInfoVo.borrowStatus==2?'selected':'' }>已借阅</option>
</select>
<input type="submit" value="查询" onclick="searchBook()">
<input type="reset" value="重置" onclick="reset()">
</td>
</tr>
</table>
<table align="center" width="60%" border="1" cellspacing="5">
<thead>
<tr>
<th>编号</th>
<th>分类</th>
<th>名称</th>
<th>作者</th>
<th>出版社</th>
<th>是否借阅</th>
<tr>
</thead>
<tbody>
<c:choose>
<c:when test="${empty bookList }">
<tr>
<td align="center" colspan="6">
no result
</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach var="book" items="${bookList}">
<tr>
<td>${book.bookid}</td>
<td>
<c:choose>
<c:when test="${book.booktype==1}">科技</c:when>
<c:when test="${book.booktype==2}">历史</c:when>
<c:when test="${book.booktype==3}">文学</c:when>
<c:otherwise>其他</c:otherwise>
</c:choose>
</td>
<td>${book.bookname}</td>
<td>${book.bookauthor}</td>
<td>${book.publishpress}</td>
<td>
<c:choose>
<c:when test="${book.borrowStatus==1}">
<a href="javascript:void(0)" onclick="borrowBook(${book.bookid})">申请借阅</a>
</c:when>
<c:otherwise>
已借阅
</c:otherwise>
</c:choose>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
<tr>
<td algin="right" colspan="6">
<c:choose>
<c:when test="${pageBean.pageIndex==1 }">
previous
</c:when>
<c:otherwise>
<a href="javascript:void(0)" onclick="changePage(${pageBean.pageIndex-1})">previous</a>
</c:otherwise>
</c:choose>
&nbsp;&nbsp;&nbsp;
<c:forEach begin="1" end="${pageBean.totalPage }" var="pageNum">
<c:choose>
<c:when test="${pageBean.pageIndex==pageNum }">
${pageNum }
</c:when>
<c:otherwise>
<a href="javascript:void(0)" onclick="changePage(${pageNum})">${pageNum }</a>
</c:otherwise>
</c:choose>
</c:forEach>
&nbsp;&nbsp;&nbsp;
<c:choose>
<c:when test="${pageBean.pageIndex==pageBean.totalPage }">
next
</c:when>
<c:otherwise>
<a href="javascript:void(0)" onclick="changePage(${pageBean.pageIndex+1})">next</a>
</c:otherwise>
</c:choose>
&nbsp;&nbsp;&nbsp;
total ${pageBean.totalPage } page
&nbsp;&nbsp;&nbsp;
Jump to
<select onchange="jumpToPage(this)">
<c:forEach begin="1" end="${pageBean.totalPage }" var="pageNum">
<c:choose>
<c:when test="${pageBean.pageIndex==pageNum }">
<option value="${pageNum }" selected="selected">${pageNum }</option>
</c:when>
<c:otherwise>
<option value="${pageNum }">${pageNum }</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
page
</td>
</tr>
</tbody>
</table>
</body>
<script type="text/javascript">
function changePage(pageIndex) {
var booktype = document.getElementById("booktype").value;
var bookname = document.getElementById("bookname").value;
var borrowStatus = document.getElementById("borrowStatus").value;
var parameter = "?pageIndex="+pageIndex+"&booktype="+booktype+"&bookname="+bookname+"&borrowStatus="+borrowStatus;
window.location.href="${pageContext.request.contextPath }/bookInfo/queryBookInfoList.do"+parameter;
}

function jumpToPage(obj) {
var pageNum = obj.value;
changePage(pageNum);
}

function borrowBook(bookid) {
window.location.href="${pageContext.request.contextPath }/bookInfo/borrowBook.do?bookid="+bookid;
}

function searchBook() {
changePage(1);
}

function reset() {
document.getElementById("booktype").value = 0;
document.getElementById("bookname").value = '';
document.getElementById("borrowStatus").value = 0;
}
</script>
</html>

SQL

表: student

1
2
3
4
5
6
7
8
9
10
CREATE TABLE `student` (
`userid` int NOT NULL AUTO_INCREMENT,
`usercode` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` char(2) DEFAULT NULL,
`register_time` datetime DEFAULT NULL,
`last_login_time` datetime DEFAULT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

表: bookinfo

1
2
3
4
5
6
7
8
9
10
11
12
13
CREATE TABLE `bookinfo` (
`bookid` int NOT NULL AUTO_INCREMENT,
`bookname` varchar(255) DEFAULT NULL,
`booktype` varchar(255) DEFAULT NULL,
`bookauthor` varchar(255) DEFAULT NULL,
`publishpress` varchar(255) DEFAULT NULL,
`publishdate` datetime DEFAULT NULL,
`borrow_status` int DEFAULT NULL,
`created_user` varchar(255) DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
`last_update_time` datetime DEFAULT NULL,
PRIMARY KEY (`bookid`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;

浏览器访问: http://localhost:8080/06_library_management/index.jsp

SpringMVC拦截器

Servlet过滤器与SpringMVC拦截器对比:

1.Servlet过滤器: 可以拦截所有请求,包括:Servlet, jsp, 静态资源(js, css, 图片), 文件等

2.SpringMVC拦截器: 只会拦截Controller

在图书借阅系统的基础上:

1.添加Interceptor类,增加拦截器处理类

2.修改springmvc.xml配置文件,添加对SpringMVC拦截器的配置

Interceptor

LoginInterceptor.java: 对未登录的请求进行拦截,未登录的请求会跳转到登录页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.course.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.course.vo.Student;

/*
* 对未登录的请求进行拦截,未登录的请求会跳转到登录页面
*/
public class LoginInterceptor implements HandlerInterceptor {

/**
* 请求被拦截,首先执行的方法
* @return true: 通过,false: 拦截
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
System.out.println("开始执行preHandle()方法");
HttpSession httpSession = httpServletRequest.getSession();
Student student = (Student) httpSession.getAttribute("student");
System.out.println("student = " + student);
if (student != null) {
String username = student.getUsercode();
System.out.println("username = " + username);
System.out.println("结束执行preHandle()方法");
return true;
} else {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index.jsp");
System.out.println("结束执行preHandle()方法");
return false;
}
}

/**
* 在controller方法执行完返回modelAndView之后执行该方法
* 可以对modelAndView再次进行加工
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView)
throws Exception {
System.out.println("开始执行postHandle()方法");
System.out.println("结束执行postHandle()方法");
}

/**
* 当整个请求完成之后执行的方法
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception exception)
throws Exception {
System.out.println("开始执行afterCompletion()方法");
System.out.println("结束执行afterCompletion()方法");
}

}

TimerInterceptor.java: 计算程序运行耗时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.course.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/*
* 计算程序运行耗时
*/
public class TimerInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
httpServletRequest.setAttribute("startTime", startTime);
return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView)
throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception exception)
throws Exception {
long startTime = (long) httpServletRequest.getAttribute("startTime");
long endTime = System.currentTimeMillis();
long timeConsumption = endTime - startTime;
System.out.println("执行耗时: " + timeConsumption + " ms");

}

}

config

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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">


<!--
配置控制器
包扫描
-->
<context:component-scan base-package="com.course.controller"></context:component-scan>

<!--
合并注解的控制器映射器和控制器适配器的配置
对控制器映射器和控制器适配器进行加强,如把对象转化为json字符串
-->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 配置SpringMVC拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/login/login*"/>
<mvc:exclude-mapping path="/login/jumpToLoginPage*"/>
<bean class="com.course.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>

<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.course.interceptor.TimerInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>

</beans>