7-黑马旅游网-旅游线路收藏
程序员文章站
2022-04-03 18:30:58
...
旅游线路收藏功能
分析
判断当前登录用户是否收藏过该线路
当页面加载完成后,发送ajax请求,获取用户是否收藏的标记
根据标记,展示不同的按钮样式
后台代码
RouteServlet
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);
}
FavoriteService
@Override
public boolean isFavorite(String rid, int uid) {
Favorite favorite = favoriteDao.findByRidAndUid(Integer.parseInt(rid), uid);
return favorite != null;//如果对象有值,则为true,反之,则为false
}
FavoriteDao
@Override
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;
}
前台代码
route_detail.html
$(function () {
// 发送请求,判断用户是否收藏过该线路
var rid = getParameter("rid");
$.get("route/isFavorite",{rid:rid},function (flag) {
if(flag){
// 用户已经收藏过
//<a class="btn already" disabled="disabled">
//设置收藏按钮的样式
$("#favorite").addClass("already");
$("#favorite").prop("disabled",disabled);
}else{
// 用户没有收藏
}
});
收藏次数的动态展示
//设置收藏次数
$("#favoriteCount").html("已收藏"+route.count+"次");
后台
RouteService
//4. 查询收藏次数
int count = favoriteDao.findCountByRid(route.getRid());
route.setCount(count);
FavoriteDao
@Override
public int findCountByRid(int rid) {
String sql = "SELECT COUNT(*) FROM tab_favorite WHERE rid = ?";
return template.queryForObject(sql,Integer.class,rid);
}
上一篇: 一直在给你的手表上弦