如需转载,请根据 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 许可,附上本文作者及链接。
本文作者: Alice
作者昵称: 沉。
本文链接: http://example.com/2020/10/23/JavaWeb%E9%BB%91%E9%A9%AC%E6%97%85%E6%B8%B8%E7%BD%91%E7%BB%BC%E5%90%88%E6%A1%88%E4%BE%8B/
Finished:2020-10-18,需要源码的请联系本人
一、导入项目
- 导入静态页面
- 导入配置文件
二、技术选型
Dao层:
- Mysql:数据库
- druid数据库连接池
- JDBCTemblate:jdbc的工具
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### pom.xml:导入项目所需要的jar包依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itcast</groupId>
<artifactId>travel</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
<scope>compile</scope>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!--jdbcTemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>compile</scope>
</dependency>
<!--beanUtils-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
<scope>compile</scope>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.3</version>
</dependency>
<!--javaMail-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.3</version>
</dependency>
<!--jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
<!--maven插件-->
<plugins>
<!--jdk编译插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<!--tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<!-- tomcat7的插件, 不同tomcat版本这个也不一样 -->
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<!-- 通过maven tomcat7:run运行项目时,访问项目的端口号 -->
<port>80</port>
<!-- 项目访问路径 本例:localhost:9090, 如果配置的aa, 则访问路径为localhost:9090/aa-->
<path>/travel</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
三、创建数据库
1 | -- 创建数据库并使用 |
四、注册功能
前台—-表单校验
功能分析
代码实现
前台代码
表单校验
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<script>
/*
表单校验:
1.用户名:单词字符,8-20位长度
2.密码:单词字符,8-20位长度
3.Email:用正则表示邮件格式
4.姓名:非空
5.手机号:手机号格式
6.出生日期:不能为空
7.验证码:非空
*/
//校验用户名,1.用户名:单词字符,8-20位长度
function checkUsername() {
//获取用户名的值
var username = $("#username").val();
//定义正则表达式
var reg_username = /^\w{8,20}$/;
//判断,给出提示信息
var flag = reg_username.test(username);
if(flag){
//用户名合法
$("#username").css("border","");
}else {
//用户名非法,加一个红色的边框
$("#username").css("border","1px solid red");
}
return flag;
}
//校验密码
function checkPassword() {
//获取密码的值
var password = $("#password").val();
//定义正则表达式
var reg_password = /^\w{8,20}$/;
//判断,给出提示信息
var flag = reg_password.test(password);
if(flag){
//密码合法
$("#password").css("border","");
}else {
//密码非法,加一个红色的边框
$("#password").css("border","1px solid red");
}
return flag;
}
//校验邮箱
function checkEmail(){
//获取邮箱
var email = $("#email").val();
//定义正则
var reg_email = /^\w+@\w+\.\w+$/;
//判断
var flag = reg_email.test(email);
if (flag){
$("#email").css("border","");
}else{
$("#email").css("border","1px solid red");
}
}
$(function () {
//当表单提交时调用所有的校验方法
$("#registerForm").submit(function () {
//发送数据到服务器
if (checkUsername() && checkPassword() && checkEmail() ) {
//校验通过,发送ajax请求提交表单的数据
$.post("registUserServlet",$(this).serialize(),function (data) {
//处理服务器响应的数据
});
}
return false;
//如果这个方法没有返回值或者返回为true,则表单提交,如果返回为false表单不提交
});
// $("#name").blur(checkName);
// $("#telephone").blur(checkTelephone);
//当某一个组件失去焦点时调用对应的校验方法
$("#username").blur(checkUsername);
$("#password").blur(checkPassword);
$("#email").blur(checkEmail);
});
</script>
* 异步(ajax)提交表单
* 再此使用异步提交表单是为了获取服务器的响应数据,因为我们前台使用的是html作为视图层,不能够直接从servlet相关的域对象获取值,只能通过ajax响应获取数据
> serialize()方法 序列表表格内容为字符串,用于 Ajax 请求
* 代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
$(function () {
//当表单提交时调用所有的校验方法
$("#registerForm").submit(function () {
//发送数据到服务器
if (checkUsername() && checkPassword() && checkEmail() ) {
//校验通过,发送ajax请求提交表单的数据
$.post("registUserServlet",$(this).serialize(),function (data) {
//处理服务器响应的数据
});
}
return false;
//如果这个方法没有返回值或者返回为true,则表单提交,如果返回为false表单不提交
});
* 后台代码实现
* 编写RegistUserServlet
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
//验证码的校验
String check = request.getParameter("check");
//从session中获取验证码
HttpSession session = request.getSession();
String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");//保证验证码只能使用一次
//比较
if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
//验证码错误
ResultInfo info = new ResultInfo();
//注册失败
info.setFlag(false);
info.setErrorMsg("验证码错误");
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
//将json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
//1.获取数据
Map<String, String[]> map = request.getParameterMap();
//2.封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.调用service完成注册
UserService service = new UserServiceImpl();
boolean flag = service.regist(user);
ResultInfo info = new ResultInfo();
//4.响应结果
if(flag){
// 注册成功
info.setFlag(true);
}else {
//注册失败
info.setFlag(false);
info.setErrorMsg("注册失败!");
}
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
//将json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
* 编写UserService以及UserServiceImpl
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
// UserService
boolean regist(User user);
boolean active(String code);
//UserServiceImpl
/**
* 注册用户
* @param user
* @return
*/
public boolean regist(User user) {
//1.根据用户名查询用户对象
User u = userDao.findByUsername(user.getUsername());
//判断u是否为null
if (u != null){
//用户名存在
return false;
}
//2.保存用户信息
//2.1设置激活码,唯一字符串
user.setCode(UuidUtil.getUuid());
//2.2设置激活状态
user.setStatus("N");
userDao.save(user);
//3.邮件发送,邮件的正文?
String content="<a href='http://localhost/travel/activeUserServlet?code="+user.getCode()+"'>点击激活【黑马旅游网】</a>";
MailUtils.sendMail(user.getEmail(),content,"激活邮件");
return true;
}
/**
* 激活用户
* @param code
* @return
*/
public boolean active(String code) {
//1.根据激活码查询用户对象
User user = userDao.findByCode(code);
if (user != null){
//2.调用dao的修改激活状态的方法
userDao.updateStatus(user);
return true;
}else {
return false;
}
}
* 编写UserDao以及UserDaoImpl
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
// UserDao
/**
* 根据用户名查询用户信息
* @param username
* @return
*/
public User findByUsername(String username);
/**
* 用户保存
* @param user
*/
public void save(User user);
User findByCode(String code);
void updateStatus(User user);
//UserDaoImpl
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
public User findByUsername(String username) {
User user = null;
try {
//1.定义sql语句
String sql = "select * from tab_user where username =?";
//2.执行sql
user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
} catch (DataAccessException e) {
}
return user;
}
public void save(User user) {
//1定义sql
String sql = "insert into tab_user(username,password,name,birthday,sex,telephone,email,status,code) values(?,?,?,?,?,?,?,?,?)";
//2.执行sql
template.update(sql, user.getUsername(),
user.getPassword(),
user.getName(),
user.getBirthday(),
user.getSex(),
user.getTelephone(),
user.getEmail(),
user.getStatus(),
user.getCode() );
}
/**
* 根据激活码查询用户对象
* @param code
* @return
*/
public User findByCode(String code) {
User user = null;
try {
String sql = "select *from tab_user where code = ?";
user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), code);
} catch (DataAccessException e) {
e.printStackTrace();
}
return user;
}
/**
* 修改指定用户激活状态
* @param user
*/
public void updateStatus(User user) {
String sql = "update tab_user set status = 'Y' where uid = ?";
template.update(sql,user.getUid());
}
* 邮件激活的功能
* 为了保证用户填写的邮箱是正确的,可以宣传推广邮件信息到用户邮箱中
* 发送邮件
* 用户点击邮件激活
* 经过分析,发现,用户激活其实就是 修改用户表中的status为'Y'
![image-20201020082026319](/images/heima.assets/image-20201020082026319.png)
五、登录功能
分析
后台代码实现
LoginServlet
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//获取用户名和密码数据
Map<String, String[]> map = request.getParameterMap();
//封装user对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用Service查询
UserService service = new UserServiceImpl();
User u = service.login(user);
ResultInfo info = new ResultInfo();
//4.判断用户对象是否为nulll
if (u == null){
//用户名密码错误
info.setFlag(false);
info.setErrorMsg("用户名或密码错误");
}
//5.判断用户是否激活
if (u != null && !"Y".equals(u.getStatus())){
//用户尚未激活
info.setFlag(false);
info.setErrorMsg("您尚未激活,请激活");
}
//6.判断登陆成功
if (u != null && "Y".equals(u.getStatus())){
//登录成功
info.setFlag(true);
}
//响应数据
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),info);
* UserService
1
2
3
4
5
6
7
8
9
/**
* 登录方法
* @param user
* @return
*/
public User login(User user) {
return userDao.findByUsernameAndPassword(user.getUsername(),user.getPassword());
}
* UserDao
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 根据用户名和密码查询的方法
* @param username
* @param password
* @return
*/
public User findByUsernameAndPassword(String username, String password) {
User user = null;
try {
//1.定义sql语句
String sql = "select * from tab_user where username =? and password=?";
//2.执行sql
user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username,password);
} catch (DataAccessException e) {
}
return user;
}
前台代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20//login.html
<script>
$(function () {
//给登录按钮绑定事件
$("#btn_sub").click(function () {
//发送ajax请求,提交表单数据
$.post("loginServlet",$("#loginForm").serialize(),function (data) {
//处理响应结果
//data:(flag:false,errorMsg:'')
if (data.flag){
//登陆成功
Location.href="index.html";
}else {
//登录失败
$("#errorMsg").html(data.errorMsg);
}
});
});
})
</script>修改登录后的姓名提示
1
2
3
4
5
6
7
8
9//header.html
<script>
$(function () {
$.get("findUserServlet",{},function (data) {
// {uid:1,name:'李四'}
var msg = "欢迎回来," + data.name;
$("#span_username").html()
})
})
六、退出功能
什么叫做登陆了?session中有user对象。
实现步骤:
- 访问servlet,将session销毁
- 跳转到登录页面
- 访问servlet,将session销毁
代码实现
前台代码Header.html
后台exitServlet
1
2
3
4//销毁session
request.getSession().invalidate();
//跳转页面
response.sendRedirect(request.getContextPath()+"/login.html");
七、优化Servlet
减少Servlet数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet,相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同的方法,完成用户的请求
分析
IDEA控制台中文乱码问题: -Dfile.encoding = gb1312
BaseServlet抽取方法
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
45package cn.itcast.travel.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("BaseServlet的service方法被执行了");
//完成方法的分发
//1.获取请求路径
String uri = req.getRequestURI(); // /user/add
System.out.println("请求uri:"+uri); // /travel/user/add
//2.获取方法名称
String methodName = uri.substring(uri.lastIndexOf('/') + 1);
System.out.println("方法名称:"+methodName);
//3.获取方法对象method
//谁调用我,我代表谁
System.out.println(this);//UserServlet的对象
try {
//getDeclaredMethod忽略访问权限修饰符获取方法
Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//暴力反射
// method.setAccessible(true);
//4.执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}利用UserServlet对用户注册登录退出等功能进行封装
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
171
172
173
174
175
176
177
178
179
180
181
182
183// /user/add /user/find
public class UserServlet extends BaseServlet {
//声明一个userservice的业务对象
private UserService service = new UserServiceImpl();
/**
* 注册功能
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证码的校验
String check = request.getParameter("check");
//从session中获取验证码
HttpSession session = request.getSession();
String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");//保证验证码只能使用一次
//比较
if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
//验证码错误
ResultInfo info = new ResultInfo();
//注册失败
info.setFlag(false);
info.setErrorMsg("验证码错误");
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
//将json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
//1.获取数据
Map<String, String[]> map = request.getParameterMap();
//2.封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.调用service完成注册
//UserService service = new UserServiceImpl();
boolean flag = service.regist(user);
ResultInfo info = new ResultInfo();
//4.响应结果
if(flag){
// 注册成功
info.setFlag(true);
}else {
//注册失败
info.setFlag(false);
info.setErrorMsg("注册失败!");
}
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
//将json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
}
/**
* 登录功能
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户名和密码数据
Map<String, String[]> map = request.getParameterMap();
//封装user对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用Service查询
//UserService service = new UserServiceImpl();
User u = service.login(user);
ResultInfo info = new ResultInfo();
//4.判断用户对象是否为nulll
if (u == null){
//用户名密码错误
info.setFlag(false);
info.setErrorMsg("用户名或密码错误");
}
//5.判断用户是否激活
if (u != null && !"Y".equals(u.getStatus())){
//用户尚未激活
info.setFlag(false);
info.setErrorMsg("您尚未激活,请激活");
}
//6.判断登陆成功
if (u != null && "Y".equals(u.getStatus())){
//登录成功
info.setFlag(true);
}
//响应数据
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),info);
}
/**
* 查询单个对象
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findeOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从session中获取登录用户
Object user = request.getSession().getAttribute("user");
//将user写回客户端
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),user);
}
/**
* 退出功能
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//销毁session
request.getSession().invalidate();
//跳转页面
response.sendRedirect(request.getContextPath()+"/login.html");
}
/**
* 激活功能
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取激活码
String code = request.getParameter("code");
if (code != null){
//调用service 完成激活
//UserService service = new UserServiceImpl();
boolean flag = service.active(code);
//3.判断标记
String msg = null;
if (flag){
//激活成功
msg = "激活成功,请<a href='login.html'>登录</a>";
}else {
//激活失败
msg = "激活失败,请联系管理员!";
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(msg);
}
}
}
八、分类数据展示功能
分析
代码实现
后台代码
CategoryServlet
CategoryService
CategoryDao
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//CategoryDao
/**
* 查询所有
* @return
*/
public List<Category> findAll();
public List<Category> findAll() {
String sql = "select * from tab_category";
return template.query(sql,new BeanPropertyRowMapper<Category>(Category.class));
}
//CategoryService
public List<Category> findAll();
public List<Category> findAll() {
return categoryDao.findAll();
}
//CategoryServlet
//调用service查询所有
List<Category> cs = service.findAll();
//序列化json返回
/*ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset-utf-8");
mapper.writeValue(response.getOutputStream(),cs);
*/
writeValue(cs,response);
//封装两个序列化json的方法
/**
* 直接将传入的对象序列化为json,并且写回客户端
* @param obj
*/
public void writeValue(Object obj,HttpServletResponse response) throws IOException {
//序列化json返回
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset-utf-8");
mapper.writeValue(response.getOutputStream(),obj);
}
/**
* 将传入的对象序列化为json,返回
* @param obj
*/
public String writeValueAsString(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
}
前台代码
header.html加载时发送ajax请求,轻轻category/findAll
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18//查询分类数据
$.get("category/findAll",{},function (data) {
//{{cid:1},{cname:国内游}}
var lis = '<li class="nav-active"><a href="index.html">首页</a></li>';
//遍历数组,拼接字符串(<li)
for (var i = 0; i < data.length; i++) {
//<li><a href="route_list.html">门票</a></li>
var li = '<li><a href="route_list.html">'+data[i].cname+'</a></li>';
lis += li;
};
//拼接收藏排行榜的li,<li><a href="favoriterank.html">收藏排行榜</a></li>
lis += '<li><a href="favoriterank.html">收藏排行榜</a></li>'
//将lis字符串设置到ul的html中
$("#category").html(lis);
})对分类数据进行缓存优化
分析发现,分类的数据在每一次页面加载后都会重新请求数据库加载,对数据库的压力比较大,但是分类的数据不会经常产生变化,所以可以使用redis来缓存这个数据
代码实现
期望数据库中存储的顺序就是将来展示的顺序
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
public List<Category> findAll() {
//从redis中 查询
//获取jedis客户端
Jedis jedis = JedisUtil.getJedis();
//判断查询的集合是否为空
//Set<String> categorys = jedis.zrange("category", 0, -1);
//查询混sorterset中的分数(cid)和值(cname)
Set<Tuple> categorys = jedis.zrangeWithScores("category", 0, -1);
List<Category> cs = null;
//判断是否为空,如果为空,需要从数据库中查询,再将数据存入redis
if (categorys == null || categorys.size() == 0){
System.out.println("从数据库查询...");
//为空,从数据库查询
cs = categoryDao.findAll();
//将集合的数据存储到redis中的一个category的key中
for (int i = 0; i < cs.size(); i++) {
jedis.zadd("category",cs.get(i).getCid(),cs.get(i).getCname());
}
}else {
System.out.println("从redis中查询");
//如果不为空,将set的数据存入list
cs = new ArrayList<Category>();
for (Tuple tuper: categorys) {
Category category = new Category();
category.setCname(tuper.getElement());
category.setCid((int)tuper.getScore());
cs.add(category);
}
}
return cs;
}
九、旅游线路的分页展示功能
点击了不同的分类后,将来看到的旅游线路不一样,通过分析数据库表结构,发现旅游线路表和分类表是多对一的关系
获取cid
1
2
3
4
5
6$(functinon (){
var serch = location.search;
//alert(search);//?id=5
//切割字符串,拿到第二个值
var cid = serarch.split("=")[1];
});
根据id查询不同类别的旅游线路数据
分析
创建PageBean实体类
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/*
分页对象
*/
public class PageBean<T> {
private int totalCount;//总记录数
private int totalPage;//总页数
private int currentPage;//当前页码
private int pageSize;//每页显示的条数
private List<T> list;//每页显示的数据集合
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}后台代码编写
RouteServlet
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
public class RouteServlet extends BaseServlet {
private RouteService routeService = new RouteServiceImpl();
private FavoriteService favoriteService = new FavoriteServiceImpl();
/**
* 分页查询
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void pageQuery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受参数
String currentPageStr = request.getParameter("currentPage");
String pageSizeStr = request.getParameter("pageSize");
String cidStr = request.getParameter("cid");
//接受rname 线路名称
String rname = request.getParameter("rname");
rname = new String(rname.getBytes("iso-8859-1"),"utf-8");
int cid = 0;//类别id
//2.处理参数
if(cidStr != null && cidStr.length() > 0 && !"null".equals(cidStr)){
cid = Integer.parseInt(cidStr);
}
int currentPage = 0;//当前页码,如果不传递,则默认为第一页
if(currentPageStr != null && currentPageStr.length() > 0){
currentPage = Integer.parseInt(currentPageStr);
}else{
currentPage = 1;
}
int pageSize = 0;//每页显示条数,如果不传递,默认每页显示5条记录
if(pageSizeStr != null && pageSizeStr.length() > 0){
pageSize = Integer.parseInt(pageSizeStr);
}else{
pageSize = 5;
}
//3. 调用service查询PageBean对象
PageBean<Route> pb = routeService.pageQuery(cid, currentPage, pageSize,rname);
//4. 将pageBean对象序列化为json,返回
writeValue(pb,response);
}
/**
* 根据id查询一个旅游线路的详细信息
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收id
String rid = request.getParameter("rid");
//2.调用service查询route对象
Route route = routeService.findOne(rid);
//3.转为json写回客户端
writeValue(route,response);
}
/**
* 判断当前登录用户是否收藏过该线路
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void isFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取线路id
String rid = request.getParameter("rid");
//2. 获取当前登录的用户 user
User user = (User) request.getSession().getAttribute("user");
int uid;//用户id
if(user == null){
//用户尚未登录
uid = 0;
}else{
//用户已经登录
uid = user.getUid();
}
//3. 调用FavoriteService查询是否收藏
boolean flag = favoriteService.isFavorite(rid, uid);
//4. 写回客户端
writeValue(flag,response);
}
/**
* 添加收藏
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void addFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取线路rid
String rid = request.getParameter("rid");
//2. 获取当前登录的用户
User user = (User) request.getSession().getAttribute("user");
int uid;//用户id
if(user == null){
//用户尚未登录
return ;
}else{
//用户已经登录
uid = user.getUid();
}
//3. 调用service添加
favoriteService.add(rid,uid);
}
}
* RouteService
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
private RouteDao routeDao = new RouteDaoImpl();
private RouteImgDao routeImgDao = new RouteImgDaoImpl();
private SellerDao sellerDao = new SellerDaoImpl();
private FavoriteDao favoriteDao = new FavoriteDaoImpl();
public PageBean<Route> pageQuery(int cid, int currentPage, int pageSize,String rname ) {
//封装PageBean
PageBean<Route> pb = new PageBean<Route>();
//设置当前页码
pb.setCurrentPage(currentPage);
//设置每页显示条数
pb.setPageSize(pageSize);
//设置总记录数
int totalCount = routeDao.findTotalCount(cid,rname);
pb.setTotalCount(totalCount);
//设置当前页显示的数据集合
int start = (currentPage - 1) * pageSize;//开始的记录数
List<Route> list = routeDao.findByPage(cid,start,pageSize,rname);
pb.setList(list);
//设置总页数 = 总记录数/每页显示条数
int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize :(totalCount / pageSize) + 1 ;
pb.setTotalPage(totalPage);
return pb;
}
public Route findOne(String rid) {
//1.根据id去route表中查询route对象
Route route = routeDao.findOne(Integer.parseInt(rid));
//2.根据route的id 查询图片集合信息
List<RouteImg> routeImgList = routeImgDao.findByRid(route.getRid());
//2.2将集合设置到route对象
route.setRouteImgList(routeImgList);
//3.根据route的sid(商家id)查询商家对象
Seller seller = sellerDao.findById(route.getSid());
route.setSeller(seller);
//4. 查询收藏次数
int count = favoriteDao.findCountByRid(route.getRid());
route.setCount(count);
return route;
}
* RouteDao
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
public class RouteDaoImpl implements RouteDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
public int findTotalCount(int cid,String rname) {
//String sql = "select count(*) from tab_route where cid = ?";
//1.定义sql模板
String sql = "select count(*) from tab_route where 1=1 ";
StringBuilder sb = new StringBuilder(sql);
List params = new ArrayList();//条件们
//2.判断参数是否有值
if(cid != 0){
sb.append( " and cid = ? ");
params.add(cid);//添加?对应的值
}
if(rname != null && rname.length() > 0){
sb.append(" and rname like ? ");
params.add("%"+rname+"%");
}
sql = sb.toString();
return template.queryForObject(sql,Integer.class,params.toArray());
}
public List<Route> findByPage(int cid, int start, int pageSize,String rname) {
//String sql = "select * from tab_route where cid = ? and rname like ? limit ? , ?";
String sql = " select * from tab_route where 1 = 1 ";
//1.定义sql模板
StringBuilder sb = new StringBuilder(sql);
List params = new ArrayList();//条件们
//2.判断参数是否有值
if(cid != 0){
sb.append( " and cid = ? ");
params.add(cid);//添加?对应的值
}
if(rname != null && rname.length() > 0){
sb.append(" and rname like ? ");
params.add("%"+rname+"%");
}
sb.append(" limit ? , ? ");//分页条件
sql = sb.toString();
params.add(start);
params.add(pageSize);
return template.query(sql,new BeanPropertyRowMapper<Route>(Route.class),params.toArray());
}
public Route findOne(int rid) {
String sql = "select * from tab_route where rid = ?";
return template.queryForObject(sql,new BeanPropertyRowMapper<Route>(Route.class),rid);
}
}
前台代码编写:route_list.html
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
171
172
173
174
175
176
177<script>
$(function () {
/* var search = location.search;
//alert(search);//?id=5
// 切割字符串,拿到第二个值
var cid = search.split("=")[1];*/
//获取cid的参数值
var cid = getParameter("cid");
//获取rname的参数值
var rname = getParameter("rname");
//判断rname如果不为null或者""
if(rname){
//url解码
rname = window.decodeURIComponent(rname);
}
//当页码加载完成后,调用load方法,发送ajax请求加载数据
load(cid,null,rname);
});
function load(cid ,currentPage,rname){
//发送ajax请求,请求route/pageQuery,传递cid
$.get("route/pageQuery",{cid:cid,currentPage:currentPage,rname:rname},function (pb) {
//解析pagebean数据,展示到页面上
//1.分页工具条数据展示
//1.1 展示总页码和总记录数
$("#totalPage").html(pb.totalPage);
$("#totalCount").html(pb.totalCount);
var lis = "";
//计算上一页的页码
var beforeNum = pb.currentPage - 1;
if(beforeNum <= 0){
beforeNum = 1;
}
lis += fristPage;
lis += beforePage;
//1.2 展示分页页码
/*
1.一共展示10个页码,能够达到前5后4的效果
2.如果前边不够5个,后边补齐10个
3.如果后边不足4个,前边补齐10个
*/
// 定义开始位置begin,结束位置 end
var begin; // 开始位置
var end ; // 结束位置
//1.要显示10个页码
if(pb.totalPage < 10){
//总页码不够10页
begin = 1;
end = pb.totalPage;
}else{
//总页码超过10页
begin = pb.currentPage - 5 ;
end = pb.currentPage + 4 ;
//2.如果前边不够5个,后边补齐10个
if(begin < 1){
begin = 1;
end = begin + 9;
}
//3.如果后边不足4个,前边补齐10个
if(end > pb.totalPage){
end = pb.totalPage;
begin = end - 9 ;
}
}
for (var i = begin; i <= end ; i++) {
var li;
//判断当前页码是否等于i
if(pb.currentPage == i){
}else{
//创建页码的li
}
//拼接字符串
lis += li;
}
/* for (var i = 1; i <= pb.totalPage ; i++) {
var li;
//判断当前页码是否等于i
if(pb.currentPage == i){
}else{
//创建页码的li
}
//拼接字符串
lis += li;
}*/
lis += nextPage;
lis += lastPage;
//将lis内容设置到 ul
$("#pageNum").html(lis);
/*
<div class="img"><img src="images/04-search_03.jpg" alt=""></div>
<div class="text1">
<div class="price">
<p class="price_num">
*/
//2.列表数据展示
var route_lis = "";
for (var i = 0; i < pb.list.length; i++) {
//获取{rid:1,rname:"xxx"}
var route = pb.list[i];
var li = '<li>\n' +
' <p>'+route.rname+'</p>\n' +
' <br/>\n' +
' <p>'+route.routeIntroduce+'</p>\n' +
' </div>\n' +
' <span>'+route.price+'</span>\n' +
' </p>\n' +
' </div>\n' +
' </li>';
route_lis += li;
}
$("#route").html(route_lis);
//定位到页面顶部
window.scrollTo(0,0);
});
}
</script>
十、旅游线路分页查询
后台代码修改
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//Servlet
public void pageQuery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受参数
String currentPageStr = request.getParameter("currentPage");
String pageSizeStr = request.getParameter("pageSize");
String cidStr = request.getParameter("cid");
//接受rname 线路名称
String rname = request.getParameter("rname");
rname = new String(rname.getBytes("iso-8859-1"),"utf-8");
int cid = 0;//类别id
//2.处理参数
if(cidStr != null && cidStr.length() > 0 && !"null".equals(cidStr)){
cid = Integer.parseInt(cidStr);
}
int currentPage = 0;//当前页码,如果不传递,则默认为第一页
if(currentPageStr != null && currentPageStr.length() > 0){
currentPage = Integer.parseInt(currentPageStr);
}else{
currentPage = 1;
}
int pageSize = 0;//每页显示条数,如果不传递,默认每页显示5条记录
if(pageSizeStr != null && pageSizeStr.length() > 0){
pageSize = Integer.parseInt(pageSizeStr);
}else{
pageSize = 5;
}
//3. 调用service查询PageBean对象
PageBean<Route> pb = routeService.pageQuery(cid, currentPage, pageSize,rname);
//4. 将pageBean对象序列化为json,返回
writeValue(pb,response);
}
//Service
//设置总记录数
int totalCount = routeDao.findTotalCount(cid,rname);
pb.setTotalCount(totalCount);
//设置当前页显示的数据集合
int start = (currentPage - 1) * pageSize;//开始的记录数
List<Route> list = routeDao.findByPage(cid,start,pageSize,rname);
pb.setList(list);
//Dao
public int findTotalCount(int cid,String rname) {
//String sql = "select count(*) from tab_route where cid = ?";
//1.定义sql模板
String sql = "select count(*) from tab_route where 1=1 ";
StringBuilder sb = new StringBuilder(sql);
List params = new ArrayList();//条件们
//2.判断参数是否有值
if(cid != 0){
sb.append( " and cid = ? ");
params.add(cid);//添加?对应的值
}
if(rname != null && rname.length() > 0){
sb.append(" and rname like ? ");
params.add("%"+rname+"%");
}
sql = sb.toString();
return template.queryForObject(sql,Integer.class,params.toArray());
}
public List<Route> findByPage(int cid, int start, int pageSize,String rname) {
//String sql = "select * from tab_route where cid = ? and rname like ? limit ? , ?";
String sql = " select * from tab_route where 1 = 1 ";
//1.定义sql模板
StringBuilder sb = new StringBuilder(sql);
List params = new ArrayList();//条件们
//2.判断参数是否有值
if(cid != 0){
sb.append( " and cid = ? ");
params.add(cid);//添加?对应的值
}
if(rname != null && rname.length() > 0){
sb.append(" and rname like ? ");
params.add("%"+rname+"%");
}
sb.append(" limit ? , ? ");//分页条件
sql = sb.toString();
params.add(start);
params.add(pageSize);
return template.query(sql,new BeanPropertyRowMapper<Route>(Route.class),params.toArray());
}
前台代码修改
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//route_list.html
$(function () {
/* var search = location.search;
//alert(search);//?id=5
// 切割字符串,拿到第二个值
var cid = search.split("=")[1];*/
//获取cid的参数值
var cid = getParameter("cid");
//获取rname的参数值
var rname = getParameter("rname");
//判断rname如果不为null或者""
if(rname){
//url解码
rname = window.decodeURIComponent(rname);
}
//当页码加载完成后,调用load方法,发送ajax请求加载数据
load(cid,null,rname);
});
var lis = "";
var fristPage = '<li onclick="javascipt:load('+cid+',1,\''+rname+'\')"><a href="javascript:void(0)">首页</a></li>';
//计算上一页的页码
var beforeNum = pb.currentPage - 1;
if(beforeNum <= 0){
beforeNum = 1;
}
var beforePage = '<li onclick="javascipt:load('+cid+','+beforeNum+',\''+rname+'\')" class="threeword"><a href="javascript:void(0)">上一页</a></li>';
if(pb.currentPage == i){
li = '<li class="curPage" onclick="javascipt:load('+cid+','+i+',\''+rname+'\')"><a href="javascript:void(0)">'+i+'</a></li>';
}else{
//创建页码的li
li = '<li onclick="javascipt:load('+cid+','+i+',\''+rname+'\')"><a href="javascript:void(0)">'+i+'</a></li>';
}1
2
3
4
5
6
7
8
9
10
11//header.html
//给搜索按钮绑定单击事件,获取搜索输入框的内容
$("#search-button").click(function () {
//线路名称
var rname = $("#search_input").val();
var cid = getParameter("cid");
// 跳转路径 http://localhost/travel/route_list.html?cid=5,拼接上rname=xxx
location.href="http://localhost/travel/route_list.html?cid="+cid+"&rname="+rname;
});
十一、详情展示功能
分析
代码实现
后台代码
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/**
RouteServlet
* 根据id查询一个旅游线路的详细信息
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收id
String rid = request.getParameter("rid");
//2.调用service查询route对象
Route route = routeService.findOne(rid);
//3.转为json写回客户端
writeValue(route,response);
}
//Service
public Route findOne(String rid) {
//1.根据id去route表中查询route对象
Route route = routeDao.findOne(Integer.parseInt(rid));
//2.根据route的id 查询图片集合信息
List<RouteImg> routeImgList = routeImgDao.findByRid(route.getRid());
//2.2将集合设置到route对象
route.setRouteImgList(routeImgList);
//3.根据route的sid(商家id)查询商家对象
Seller seller = sellerDao.findById(route.getSid());
route.setSeller(seller);
//4. 查询收藏次数
int count = favoriteDao.findCountByRid(route.getRid());
route.setCount(count);
return route;
}
//Dao层
public Route findOne(int rid) {
String sql = "select * from tab_route where rid = ?";
return template.queryForObject(sql,new BeanPropertyRowMapper<Route>(Route.class),rid);
}前台代码
Route_detail.html中加载后
1. 获取id 2. 发送ajax请求,获取route对象 3. 解析对象的数据
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//1.获取rid
var rid = getParameter("rid");
//2.发送请求请求 route/findOne
$.get("route/findOne",{rid:rid},function (route) {
//3.解析数据填充html
$("#rname").html(route.rname);
$("#routeIntroduce").html(route.routeIntroduce);
$("#price").html("¥"+route.price);
$("#sname").html(route.seller.sname);
$("#consphone").html(route.seller.consphone);
$("#address").html(route.seller.address);
//设置收藏次数
$("#favoriteCount").html("已收藏"+route.count+"次");
//图片展示
var ddstr = '<a class="up_img up_img_disable"></a>';
//遍历routeImgList
for (var i = 0; i < route.routeImgList.length; i++) {
var astr ;
if(i >= 4){
astr = '<a title="" class="little_img" data-bigpic="'+route.routeImgList[i].bigPic+'" style="display:none;">\n' +
' <img src="'+route.routeImgList[i].smallPic+'">\n' +
' </a>';
}else{
astr = '<a title="" class="little_img" data-bigpic="'+route.routeImgList[i].bigPic+'">\n' +
' <img src="'+route.routeImgList[i].smallPic+'">\n' +
' </a>';
}
ddstr += astr;
}
ddstr+='<a class="down_img down_img_disable" style="margin-bottom: 0;"></a>';
$("#dd").html(ddstr);
//图片展示和切换代码调用
goImg();
});
});
$(function () {
// 发送请求,判断用户是否收藏过该线路
var rid = getParameter("rid");
$.get("route/isFavorite",{rid:rid},function (flag) {
if(flag){
// 用户已经收藏过
//<a class="btn already" disabled="disabled">
//设置收藏按钮的样式
$("#favorite").addClass("already");
$("#favorite").attr("disabled","disabled");
//删除按钮的点击事件
$("#favorite").removeAttr("onclick");
}else{
// 用户没有收藏
}
});
});Service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class FavoriteServiceImpl implements FavoriteService {
private FavoriteDao favoriteDao = new FavoriteDaoImpl();
public boolean isFavorite(String rid, int uid) {
Favorite favorite = favoriteDao.findByRidAndUid(Integer.parseInt(rid), uid);
return favorite != null;//如果对象有值,则为true,反之,则为false
}
public void add(String rid, int uid) {
favoriteDao.add(Integer.parseInt(rid),uid);
}
}
Dao
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
31public class FavoriteDaoImpl implements FavoriteDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
public Favorite findByRidAndUid(int rid, int uid) {
Favorite favorite = null;
try {
String sql = " select * from tab_favorite where rid = ? and uid = ?";
favorite = template.queryForObject(sql, new BeanPropertyRowMapper<Favorite>(Favorite.class), rid, uid);
} catch (DataAccessException e) {
e.printStackTrace();
}
return favorite;
}
public int findCountByRid(int rid) {
String sql = "SELECT COUNT(*) FROM tab_favorite WHERE rid = ?";
return template.queryForObject(sql,Integer.class,rid);
}
public void add(int rid, int uid) {
String sql = "insert into tab_favorite values(?,?,?)";
template.update(sql,rid,new Date(),uid);
}
}
十二、旅游线路收藏功能
分析
判断当前登录用户是否收藏过该线路
当页面加载完成购,发送ajax请求,获取用户是否有收藏的标记
根据标记,展示不同的按钮样式
收藏按钮的分析
代码编写
后台代码
- Servlet
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/**
* 判断当前登录用户是否收藏过该线路
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void isFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取线路id
String rid = request.getParameter("rid");
//2. 获取当前登录的用户 user
User user = (User) request.getSession().getAttribute("user");
int uid;//用户id
if(user == null){
//用户尚未登录
uid = 0;
}else{
//用户已经登录
uid = user.getUid();
}
//3. 调用FavoriteService查询是否收藏
boolean flag = favoriteService.isFavorite(rid, uid);
//4. 写回客户端
writeValue(flag,response);
}
/**
* 添加收藏
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void addFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取线路rid
String rid = request.getParameter("rid");
//2. 获取当前登录的用户
User user = (User) request.getSession().getAttribute("user");
int uid;//用户id
if(user == null){
//用户尚未登录
return ;
}else{
//用户已经登录
uid = user.getUid();
}
//3. 调用service添加
favoriteService.add(rid,uid);
}
前台代码
Route_detail.html
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$(function () {
// 发送请求,判断用户是否收藏过该线路
var rid = getParameter("rid");
$.get("route/isFavorite",{rid:rid},function (flag) {
if(flag){
// 用户已经收藏过
//<a class="btn already" disabled="disabled">
//设置收藏按钮的样式
$("#favorite").addClass("already");
$("#favorite").attr("disabled","disabled");
//删除按钮的点击事件
$("#favorite").removeAttr("onclick");
}else{
// 用户没有收藏
}
});
});
//点击收藏按钮触发的方法
function addFavorite(){
var rid = getParameter("rid");
//1. 判断用户是否登录
$.get("user/findOne",{},function (user) {
if(user){
//用户登录了
//添加功能
$.get("route/addFavorite",{rid:rid},function () {
//代码刷新页面
location.reload();
});
}else{
//用户没有登录
alert("您尚未登录,请登录");
location.href="http://localhost/travel/login.html";
}
})
}
Service
1
2
3
4
public void add(String rid, int uid) {
favoriteDao.add(Integer.parseInt(rid),uid);
}
Dao
1
2
3
4
5
6
public void add(int rid, int uid) {
String sql = "insert into tab_favorite values(?,?,?)";
template.update(sql,rid,new Date(),uid);
}
-------------本文结束感谢您的阅读-------------
本文链接: http://example.com/2020/10/23/JavaWeb%E9%BB%91%E9%A9%AC%E6%97%85%E6%B8%B8%E7%BD%91%E7%BB%BC%E5%90%88%E6%A1%88%E4%BE%8B/
版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!