实现的效果
分析
分类数据在数据库中有单独的表:tab_category
- 在前端页面header加载完成之后,发送ajax请求,获得分类数据
- 在后端查询数据库获取数据
- 为了提高页面响应速度,使用redis存储分类数据,在查询的时候,先找redis有没有数据,有的话将数据封装到list集合返回,没有的话再查询数据库
代码实现
前端
$.post("category/findCategorys",{
},function(list){
var msg = '<li class="nav-active"><a href="index.html">首页</a></li>';
for(var i = 0; i < list.length; i++){
msg += '<li><a href="route_list.html">'+list[i].cname+'</a></li>';
}
msg += '<li><a href="favoriterank.html">收藏排行榜</a></li>';
$("#category").html(msg);
});
CategoryServlet
@WebServlet("/category/*")
public class CategoryServlet extends BaseServlet {
private CategoryService categoryService = new CategoryServiceImpl();
/**
* 查找分类数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
public void findCategorys(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Category> list = categoryService.findCategorys();
writeValue(resp,list);
}
}
CategoryServiceImpl
public class CategoryServiceImpl implements CategoryService {
private CategoryDao categoryDao = new CategoryDaoImpl();
/**
* 查找所有分类数据
* @return
*/
@Override
public List<Category> findCategorys() {
Jedis jedis = JedisUtil.getJedis();
//在redis数据库中查找分类数据
Set<String> jedis_set = jedis.zrange("category", 0, -1);
List<Category> categorys;
//有的话
if(jedis_set.size() > 0){
categorys = new ArrayList<Category>();
//遍历将分类数据存储到集合中
for(String str: jedis_set){
Category category = new Category();
category.setCname(str);
categorys.add(category);
}
}else{
//没有的话,从数据库中获取分类数据
categorys = categoryDao.findList();
//存入redis
for(Category c: categorys){
jedis.zadd("category",c.getCid(),c.getCname());
}
}
return categorys;
}
}
CategoryDao
public class CategoryDaoImpl implements CategoryDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 查找所有分类
* @return
*/
@Override
public List<Category> findList() {
System.out.println("dao");
List<Category> list = null;
try{
String sql = "select * from tab_category";
list = template.query(sql, new BeanPropertyRowMapper<Category>(Category.class));
return list;
}catch(Exception e){
e.printStackTrace();
}
return list;
}
}
完成