day-28 商城业务1历史记录,返回,validate自定义

2017-10-24  本文已影响0人  路人爱早茶
----取出cookie---
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获得cid
        String cid = request.getParameter("cid");
        String currentPageStr = request.getParameter("currentPage");
        if (currentPageStr == null)
            currentPageStr = "1";
        int currentPage = Integer.parseInt(currentPageStr);
        int currentCount = 12;
        ProductService service = new ProductService();
        PageBean pageBean = service.findProductListByCid(cid, currentPage, currentCount);
        request.setAttribute("pageBean", pageBean);
        request.setAttribute("cid", cid);
        // 定义一个记录历史商品信息的集合
        List<Product> historyProductList = new ArrayList<Product>();
        // 获得客户端携带名字叫pids的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("pids".equals(cookie.getName())) {
                    String pids = cookie.getValue();// 3-2-1
                    String[] split = pids.split("-");
                    for (String pid : split) {
                        Product pro = service.findProductByPid(pid);
                        historyProductList.add(pro);
                    }
                }
            }
        }

        // 将历史记录的集合放到域中
        request.setAttribute("historyProductList", historyProductList);
        request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
-------------在详情页放入cookie---------------
// 获得客户端携带cookie---获得名字是pids的cookie
        String pids = pid;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("pids".equals(cookie.getName())) {
                    pids = cookie.getValue();
                    // 1-3-2 本次访问商品pid是8----->8-1-3-2
                    // 1-3-2 本次访问商品pid是3----->3-1-2
                    // 1-3-2 本次访问商品pid是2----->2-1-3
                    // 将pids拆成一个数组
                    String[] split = pids.split("-");// {3,1,2}
                    List<String> asList = Arrays.asList(split);// [3,1,2]
                    LinkedList<String> list = new LinkedList<String>(asList);// [3,1,2]
                    // 判断集合中是否存在当前pid
                    if (list.contains(pid)) {
                        // 包含当前查看商品的pid
                        list.remove(pid);
                        list.addFirst(pid);
                    } else {
                        // 不包含当前查看商品的pid 直接将该pid放到头上
                        list.addFirst(pid);
                    }
                    // 将[3,1,2]转成3-1-2字符串
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < list.size() && i < 7; i++) {
                        sb.append(list.get(i));
                        sb.append("-");// 3-1-2-
                    }
                    // 去掉3-1-2-后的-
                    pids = sb.substring(0, sb.length() - 1);
                }   }   }
        Cookie cookie_pids = new Cookie("pids", pids);
        response.addCookie(cookie_pids);
        request.getRequestDispatcher("/product_info.jsp").forward(request, response);
    }
-----------redis工具包---
-----配置
redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=localhost
redis.port=6379
------
public class JedisPoolUtils {
    private static JedisPool pool = null;
    static {
        // 加载配置文件
        InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获得池子对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));// 最大闲置个数
        poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));// 最小闲置个数
    poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));// 最大连接数
        pool = new JedisPool(poolConfig, pro.getProperty("redis.url"),
                Integer.parseInt(pro.get("redis.port").toString()));
    }
    // 获得jedis资源的方法
    public static Jedis getJedis() {
        return pool.getResource();  }
    public static void main(String[] args) {
        Jedis jedis = getJedis();
        System.out.println(jedis.get("xxx"));
    }
}
------------------ajax绑定数据到jsp
<script type="text/javascript">
            //header.jsp加载完毕后 去服务器端获得所有的category数据
            $(function(){
                var content = "";
                $.post(
                    "${pageContext.request.contextPath}/categoryList",
                    function(data){
                        //[{"cid":"xxx","cname":"xxxx"},{},{}]
                        //动态创建<li><a href="#">${category.cname }</a></li>
                        for(var i=0;i<data.length;i++){
                            content+="<li><a href='${pageContext.request.contextPath}/productListByCid?cid="+data[i].cid+"'>"+data[i].cname+"</a></li>";
                        }
                        
                        //将拼接好的li放置到ul中
                        $("#categoryUl").html(content);
                    },
                    "json"
                );
            });
        </script>
--------------------categoryListservlet中的返回数据操作---gson转json
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ProductService service = new ProductService();
        
        //先从缓存中查询categoryList 如果有直接使用 没有在从数据库中查询 存到缓存中
        //1、获得jedis对象 连接redis数据库
        Jedis jedis = JedisPoolUtils.getJedis();
        String categoryListJson = jedis.get("categoryListJson");
        //2、判断categoryListJson是否为空
        if(categoryListJson==null){
            System.out.println("缓存没有数据 查询数据库");
            //准备分类数据
            List<Category> categoryList = service.findAllCategory();
            Gson gson = new Gson();
            categoryListJson = gson.toJson(categoryList);
            jedis.set("categoryListJson", categoryListJson);
        }
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(categoryListJson);
    }
Paste_Image.png Paste_Image.png
------只能使用同步,异步会是返回值flag 无法赋值
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
//自定义校验规则
    $.validator.addMethod(
    //规则的名称
    "checkUsername",
    //校验的函数
    function(value, element, params) {

        //定义一个标志
        var flag = false;
        //value:输入的内容
        //element:被校验的元素对象
        //params:规则对应的参数值
        //目的:对输入的username进行ajax校验
        $.ajax({
            "async" : false,
            "url" : "${pageContext.request.contextPath}/checkUsername",
            "data" : {
                "username" : value
            },
            "type" : "POST",
            "dataType" : "json",
            "success" : function(data) {
                flag = data.isExist;
            }
        });
        //返回false代表该校验器不通过
        return !flag;
    }
    );

1.解决也面向servlet传中文-method=post,request.setCharacterEncoding("UTF-8");连用
2.validate导包前台验证注册(看内存源码)错误信息会先看原来代码中有没有(以class=error和for=sex来确定是为name=sex准备的)

<label class="error" for="sex" style="display:none ">您没有第三种选择</label>

上一篇下一篇

猜你喜欢

热点阅读