旅游路线收藏功能-分析、后台代码
分析
当页面加载完成后,发送ajax请求,获取用户是否收藏的标记
根据标记,展示不同的按钮样式
后台代码
RouteServlet类:
/** * 判断当前登录用户是否收藏过该线路 */ public void isFavorite(HttpServletRequest request, HttpServletResponse response){ // 1.获取线路id String rid = request.getParameter("rid"); // 2.获取当前登录用户 user User user =(User) request.getSession().getAttribute("user"); // 用户id int uid; if (user == null){ // 用户已经登录 uid = user.getUid(); } // 3.调用FavoriteService查询是否收藏 boolean flag =favoriteService.isFavorite(rid,uid); // 4.写回客户端 writeValue(flag,request);
FavoriteService接口:
public interface FavoriteService { /** * 判断是否收藏 * @param rid * @param uid * @return */ public boolean isFavorite(String rid,int uid); }
FavoriteServiceImpl实现类:
private FavoriteDao favoriteDao = new FavoriteDaoImpl(); @Override public boolean isFavorite(String rid, int uid) { Favorite favorite = favoriteDao.findByRidAndUid(Integer.parseInt(rid), uid);
// 如果对象有值,则为true,反之则为false
return favorite != null;
} }
FavoriteDao接口:
public interface FavoriteDao { /** * 根据rid和uid查询收藏信息 * @param rid * @param uid * @return */ public Favorite findByRidAndUid(int rid,int uid); }
FavoriteDaoImpl实现类:
public class FavoriteDaoImpl implements FavoriteDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @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.class), rid, uid); } catch (DataAccessException e) { // e.printStackTrace(); } return favorite; } }