zoukankan      html  css  js  c++  java
  • Ajax异步加载数据及Redis缓存

    针对网页分类条目的动态加载,图为页面的Head部分。

    //categoryListServlet准备分类数据
    ProductService service = new ProductService();
    List<Category> categoryList = service.findAllCategoryList();
    response.setContentType("text/html; charset=utf-8");
    Gson gson = new Gson();
    String json = gson.toJson(categoryList);
    response.getWriter().write(json);

    head.jsp异步加载js部分:

    <script type="text/javascript">
              //head.jsp加载完成后,ajax异步加载分类条
              $(function(){
                  
                  var content= "";
                  $.post(
                          "${pageContext.request.contextPath}/categoryList",
                          function(data){
                              //[{"cid":"xxx","cname":"aaa"},{"cid":"xxx","cname":"aaa"}]
                              for(var i=0;i<data.length;i++){
                                  content += "<li><a href='#'>"+data[i].cname+"</a></li>";
                              }
                              //将拼接好的类别,写入到页面
                              $("#categoryUI").html(content);  
                          },
                          "json"
                  );
                  
              });
            
            
            </script>

    缓存逻辑:

      1.查询缓存中有无分类数据

      2.有,直接查询缓存;

       无,则通过hibernate查询,并添加到缓存中

      3.将查询到的数据返回。

    //查询缓存中有无分类数据,如果没有查询写入缓存
    Jedis jedis = JedisPoolUtils.getJedis();
    String categoryListJson = jedis.get("categoryListJson");
    if(categoryListJson == null){
        System.out.println("缓存没有数据 查询数据库");
        ProductService service = new ProductService();
        List<Category> categoryList = service.findAllCategoryList();
        Gson gson = new Gson();
        categoryListJson = gson.toJson(categoryList);
        jedis.set("categoryListJson", categoryListJson);
    }
    
    //准备分类数据    
    response.setContentType("text/html; charset=utf-8");
    response.getWriter().write(categoryListJson);
  • 相关阅读:
    emberjs初学记要
    自我的一点介绍(七夕礼物)
    JavaScript数据类型
    Vue+Webpack项目配置
    Git知识点整合
    Log4j简单配置解析
    如何明智地向程序员提问
    Navicat连接mysql报错1251
    多表查询sql语句
    PLSQL面向对象
  • 原文地址:https://www.cnblogs.com/zemul/p/10215978.html
Copyright © 2011-2022 走看看