cartcountfilter.java

来自「在线购物系统,ajax+jsp实现」· Java 代码 · 共 52 行

JAVA
52
字号
package com.accp.gz.th.zm.client.servlet.filter;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.accp.gz.th.zm.client.javabean.*;

public class CartCountFilter extends HttpServlet implements Filter {

    private FilterConfig filterConfig;
    //Handle the passed-in FilterConfig
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    //Process the request/response pair
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) {
        try {
            // 计算购物车的总价格
            HttpSession session = ((HttpServletRequest) request).getSession();
            ArrayList cartlist = null;
            Object objCartList = session.getAttribute("cartlist");
            if (objCartList == null) {
                cartlist = new ArrayList();
                session.setAttribute("cartlist", cartlist);
            } else {
                cartlist = (ArrayList) objCartList;
            }

            float totalpriceofcart = 0;
            for (int i = 0; i < cartlist.size(); i++) {
                CartBean bean = (CartBean) cartlist.get(i);
                totalpriceofcart += bean.getPrice() * bean.getNumber();
            }
            session.setAttribute("totalpriceofcart", new Float(totalpriceofcart));


            filterChain.doFilter(request, response);
        } catch (ServletException sx) {
            filterConfig.getServletContext().log(sx.getMessage());
        } catch (IOException iox) {
            filterConfig.getServletContext().log(iox.getMessage());
        }
    }

    //Clean up resources
    public void destroy() {
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?