zoukankan      html  css  js  c++  java
  • JavaWeb笔记——利用过滤器实现页面静态化

    1、说明

    页面静态化是把动态页面生成的html保存到服务器的文件上,然后再有相同请求时,不再去执行动态页面,而是直接给用户响应上次已经生成的静态页面。

    * 核心思路为拦截请求,实现请求转发指向静态页面。

    * 静态化页面实现方法为自定义类继承HttpServletResponseWrapper,修改构造函数参数,并重写getWriter()方法,使其原本输出至浏览器额内容写入静态页面中
    =============================== 

    2、查看图书分类

    我们先来写一个小例子,用来查看不同分类的图书。然后我们再去思考如何让动态页面静态化的问题。


    index.jsp

      <body>

    <a href="<c:url value='/BookServlet'/>">全部图书</a><br/>

    <a href="<c:url value='/BookServlet?category=1'/>">JavaSE分类</a><br/>

    <a href="<c:url value='/BookServlet?category=2'/>">JavaEE分类</a><br/>

    <a href="<c:url value='/BookServlet?category=3'/>">Java框架分类</a><br/>

      </body>


    BookServlet.java

    public class BookServlet extends HttpServlet {

        public void doGet(HttpServletRequest request, HttpServletResponse response)

               throws ServletException, IOException {

           BookService bookService = new BookService();

           List<Book> bookList = null;

            String param = request.getParameter("category");

           if(param == null || param.isEmpty()) {

               bookList = bookService.findAll();

           } else {

               int category = Integer.parseInt(param);

               bookList = bookService.findByCategory(category);

           }

          

           request.setAttribute("bookList", bookList);

           request.getRequestDispatcher("/show.jsp").forward(request, response);

            }

    }

     

    show.jsp

    <table border="1" align="center" width="50%">

        <tr>

           <th>图书名称</th>

           <th>图书单价</th>

           <th>图书分类</th>

        </tr>

       

      <c:forEach items="${bookList }" var="book">

        <tr>

           <td>${book.bname }</td>

           <td>${book.price }</td>

           <td>

               <c:choose>

                  <c:when test="${book.category eq 1}"><p style="color:red;">JavaSE分类</p></c:when>

                  <c:when test="${book.category eq 2}"><p style="color:blue;">JavaEE分类</p></c:when>

                  <c:when test="${book.category eq 3}"><p style="color:green;">Java框架分类</p></c:when>

               </c:choose>

           </td>

        </tr>

      </c:forEach>

    </table>

     
    ===============================  

    3 分析

    我们的目标是在用户第一次访问页面时生成静态页面,然后让请求重定向到静态页面上去。当用户再次访问时,直接重定向到静态页面上去。

    我们需要为不同的请求生成静态页面,例如用户访问BookServlet?category=1时,我们要生成静态页面,当用户访问BookServlet?category=2时,也要生成静态页面。即不同的参数生成不同的静态页面!

    我们可以使用category为key,静态页面的路径为value,保存到一个Map中,然后再把Map保存到ServletContext中。没有对应的静态页面时,我们生成静态页面,再重定向到静态页面,如果存在静态页面,那么直接重定向即可。


     
    图片

    图片

    StaticResponse.java

    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() throws IOException {

           return pw;

        }

     

        public void close() throws IOException {

           pw.close();

        }

    }

     

    StaticFilter.java

    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");

                 

           Map<String,String> map = (Map<String, String>) sc.getAttribute("pages");

           if(map == null) {

               map = new HashMap<String,String>();

               sc.setAttribute("pages", map);

           }

          

           if(map.containsKey(key)) {

               res.sendRedirect(req.getContextPath() + "/staticPages/" + map.get(key));

               return;

           }

     

           String html = key + ".html";

           String realPath = sc.getRealPath("/staticPages/" + html);

           StaticResponse sr = new StaticResponse(res, realPath);

           chain.doFilter(request, sr);

           sr.close();

     

           res.sendRedirect(req.getContextPath() + "/staticPages/" + html);

           map.put(key, html);

        }

     

        public void init(FilterConfig fConfig) throws ServletException {

           this.sc = fConfig.getServletContext();

        }

    }



  • 相关阅读:
    最大子数组问题(分治策略实现)
    Solving the Detached Many-to-Many Problem with the Entity Framework
    Working With Entity Framework Detached Objects
    Attaching detached POCO to EF DbContext
    如何获取qq空间最近访问人列表
    Health Monitoring in ASP.NET 2.0
    problem with displaying the markers on Google maps
    WebMatrix Database.Open… Close() and Dispose()
    Accessing and Updating Data in ASP.NET: Retrieving XML Data with XmlDataSource Control
    Create web setup project that has crystal reports and sql script run manually on client system
  • 原文地址:https://www.cnblogs.com/pwc1996/p/4839168.html
Copyright © 2011-2022 走看看