码迷,mamicode.com
首页 > 其他好文 > 详细

页面静态化(三)

时间:2017-12-25 16:57:27      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:config   请求   body   extends   lte   数据   访问   页面   odi   

public class StaticResponse extends HttpServletResponseWrapper {
    private PrintWriter pw;

    public StaticResponse(HttpServletResponse response, String filepath)
            throws FileNotFoundException, UnsupportedEncodingException {
        super(response);
        pw = new PrintWriter(filepath, "UTF-8");[使用路径创建流!当使用该流写数据时,数据会写入到指定路径的文件中。]
    }

    public PrintWriter getWriter[jsp页面会调用本方法获取这个流!使用它来写入页面中的数据。这些数据都写入到指定路径的页面中去了,即写入到静态页面中。]() throws IOException {
        return pw;
    }
public void close() throws IOException {

pw.close();
}

}
public class StaticFilter implements Filter {
    private ServletContext sc;
    
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String key = "key_" + request.getParameter("category");[获取分类参数,分类参数可能是:1,2,3,null。使用分类参数做key]
                
        Map<String,String> map = (Map<String, String>) sc.getAttribute("pages");[在ServletContext中获取Map,首次访问这个Map不存在。]
        if(map == null) {
            map = new HashMap<String,String>();
            sc.setAttribute("pages", map);
        }[如果Map不存在,那么创建一个Map,并存放到ServletContext中,这样下次访问Map就存在了。]
        
        if(map.containsKey(key)) {
            res.sendRedirect(req.getContextPath() + "/staticPages/" + map.get(key));
            return;
        }[查看Map中是否存在这个key,如果存在,那么获取值,值就是这个参数对应的静态页面路径。然后直接重定向到静态页面!]

        String html = key + ".html";[如果当前请求参数对应的静态页面不存在,那么就生成静态页面,首先静态页面的名称为key,容颜名为html]
        String realPath = sc.getRealPath("/staticPages/" + html);[生成真实路径,下面会使用这个路径创建静态页面。]
        StaticResponse sr = new StaticResponse(res, realPath);[创建自定义的response对象,传递待生成的静态页面路径]
        chain.doFilter(request, sr);[放行]
        sr.close();[这个方法的作用是刷新缓冲区!]

        res.sendRedirect(req.getContextPath() + "/staticPages/" + html);[这时静态页面已经生成,重定向到静态页面]
        map.put(key, html);[把静态页面保存到map中,下次访问时,直接从map中获取静态页面,不用再次生成。]
    }

    public void init(FilterConfig fConfig) throws ServletException {
        this.sc = fConfig.getServletContext();
    }
}

 

页面静态化(三)

标签:config   请求   body   extends   lte   数据   访问   页面   odi   

原文地址:http://www.cnblogs.com/ajjava/p/8109955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!