• 页面静态化


    页面静态化

    第一步
    写一个小项目,图书管理
    *jsp:link.jsp
    链接页面,四个超链接
    >查看所有
    >查看SE分类
    >查看EE分类
    >查看框架分类
    *show.jsp
    显示查询结果

    Servlet:
    BookServlet
    *findAll()-->查看所有图书
    *findByCateGory-->按分类进行查询

    BookService:略

    BookDao:
    *List<Book> findAll()
    *List<Book> findByCategory(int category)

    domain:Book类

    第二步:什么是页面静态化!
    首次访问去数据库获取数据,然后将数据保存到一个html页面中
    二次访问,就不再去数据库获取了,而是直接显示html

    ---------------------------
    图书管理

    页面静态化

    1、目标:
    给出一个过滤器,把摄入略有请求的资源所做输出保存到html中,重定向到html
    二次访问时,这个html已经存在,那么直接重定向,不用再去访问servlet

    代码:

    CREATE TABLE t_book(
      bid CHAR(32) PRIMARY KEY,
      bname VARCHAR(100),
      price NUMERIC(10,2),
      category INT
    );
    
    INSERT INTO t_book VALUES('b1', 'JavaSE_1', 10, 1);
    INSERT INTO t_book VALUES('b2', 'JavaSE_2', 15, 1);
    INSERT INTO t_book VALUES('b3', 'JavaSE_3', 20, 1);
    INSERT INTO t_book VALUES('b4', 'JavaSE_4', 25, 1);
    
    INSERT INTO t_book VALUES('b5', 'JavaEE_1', 30, 2);
    INSERT INTO t_book VALUES('b6', 'JavaEE_2', 35, 2);
    INSERT INTO t_book VALUES('b7', 'JavaEE_3', 40, 2);
    
    INSERT INTO t_book VALUES('b8', 'Java_framework_1', 45, 3);
    INSERT INTO t_book VALUES('b9', 'Java_framework_2', 50, 3);
    
    SELECT * FROM t_book;
    
    package cn.itcast.domain;
    
    public class Book {
        private String bid;
        private String bname;
        private double price;
        private int category;
        @Override
        public String toString() {
            return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price
                    + ", category=" + category + "]";
        }
        public String getBid() {
            return bid;
        }
        public void setBid(String bid) {
            this.bid = bid;
        }
        public String getBname() {
            return bname;
        }
        public void setBname(String bname) {
            this.bname = bname;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        public int getCategory() {
            return category;
        }
        public void setCategory(int category) {
            this.category = category;
        }
        public Book(String bid, String bname, double price, int category) {
            super();
            this.bid = bid;
            this.bname = bname;
            this.price = price;
            this.category = category;
        }
        public Book() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        
    }
    
    package cn.itcast.dao;
    
    import java.sql.SQLException;
    import java.util.List;
    
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    
    import cn.itcast.domain.Book;
    import cn.itcast.jdbc.TxQueryRunner;
    
    public class BookDao {
        private QueryRunner qr=new TxQueryRunner();
        
        public List<Book> findAll(){
            
            try {
                String sql="SELECT * FROM t_book";
                return qr.query(sql, new BeanListHandler<Book>(Book.class));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        
        public List<Book> findByCategory(int category){
            
            try {
                String sql="SELECT * FROM t_book where category=?";
                Object[] params={category};
                return  qr.query(sql,new BeanListHandler<Book>(Book.class),params);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <c3p0-config>
        <!-- 默认连接配置 -->
        <default-config> 
            <!-- 连接四大参数配置  -->
            <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/demo</property>
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="user">guodaxia</property>
            <property name="password">961012gz</property>
                <!-- 池参数配置 -->
            <property name="acquireIncrement">3</property>
            <property name="initialPoolSize">10</property>
            <property name="minPoolSize">2</property>
            <property name="maxPoolSize">10</property>
        </default-config>
        
        <named-config name="oracle-config">
            <!-- 连接四大参数配置  -->
            <property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:db</property>
            <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
            <property name="user">scott</property>
            <property name="password">961012gz</property>        
            <property name="acquireIncrement">3</property>
            <property name="initialPoolSize">10</property>
            <property name="minPoolSize">2</property>
            <property name="maxPoolSize">10</property>
        </named-config>
        
    </c3p0-config>
    
    package cn.itcast.web.servlet;
    
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import cn.itcast.dao.BookDao;
    import cn.itcast.servlet.BaseServlet;
    
    public class BookServlet extends BaseServlet {
        private BookDao bookDao=new BookDao();
        
        public String findAll(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setAttribute("bookList", bookDao.findAll());
            return "/show.jsp";
        }
        
        public String findByCategory(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String value=request.getParameter("category");
            int category=Integer.valueOf(value);
            request.setAttribute("bookList", bookDao.findByCategory(category));
            return "/show.jsp";
        }
    }
    
    package cn.itcast.web.filter;
    
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    
    public class StaticResponse extends HttpServletResponseWrapper{
    
        private HttpServletResponse response;
        private PrintWriter pw;
        public StaticResponse(HttpServletResponse response,String path) throws FileNotFoundException, UnsupportedEncodingException {
            super(response);
            this.response=response;
            //创建一个与html文件路径和在一起的流对象
            pw=new PrintWriter(path, "utf-8");
        }
        
        public PrintWriter getWriter(){
            //返回一个域html绑定在一起的printWriter对象
            //jsp会使用它进行输出,这样数据都输出到html文件中了、
            return pw;
        }
    
    }
    
    package cn.itcast.web.filter;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class StaticFilter implements  Filter{
        
        FilterConfig fconfig;
        public void destroy() {
            
        }
    
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req=(HttpServletRequest) request;
            HttpServletResponse resp=(HttpServletResponse) response;
            /*
             * 1.第一次访问时,查找请求对应的html页面是否存在,如果存在重定向到html
             * 2.如果不存在,放行!把Servlet访问数据库后,输出给客户端的数据保存到一个html文件中,再重定向到html!
             */
            /*
             * 一、获取category参数!
             * category有四种可能:
             *  * null-->null.html
             *  *1-->1.html
             *  *2-->2.html
             *  *3-->3.html
             *  
             *  html页面的保存路径,htmls目录下
             *  
             *  判断对应的html文件是否存在,如果存在,直接重定向!
             */
            String category=request.getParameter("category");
            String htmlPage=category+".html";
            String htmlPath=fconfig.getServletContext().getRealPath("/htmls");//得到文件的存放目录
            File destFile=new File(htmlPath,htmlPage);
            
            if(destFile.exists()){//如果文件存在
                //重定向到这个文件
                resp.sendRedirect(req.getContextPath()+"/htmls/"+htmlPage);
                return;
            }
            /*
             * 二、如果html文件不存在,我们要生成html
             * 1、放行,show.jsp会做出很多的输出,我们要让它别再输出给客户端,而是输出到我们指定到的一个html文件中
             * 完成:
             *  *掉包response,让他的getWriter()与一个html文件绑定,那么show.jsp的输出就到了一个html文件
             */
            StaticResponse sr=new StaticResponse(resp,destFile.getAbsolutePath());
            
            chain.doFilter(request, sr);//放行,即生成了html文件.这里servlet的内容相当于执行完了jsp,但是jsp中out已经被调班了,写的内容全部到了html页面,show.jsp就是一个模板了
            
            //这时页面已经存在,重定向到html文件
            resp.sendRedirect(req.getContextPath()+"/htmls/"+htmlPage);
        }
    
        public void init(FilterConfig arg0) throws ServletException {
            fconfig=arg0;
        }
    
    }
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'link.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
        <h1>链接页面</h1>
        <a href="<c:url value='BookServlet?method=findAll' />">查看所有</a><br/>
        <a href="<c:url value='BookServlet?method=findByCategory&category=1' />">查看SE</a><br/>
        <a href="<c:url value='BookServlet?method=findByCategory&category=2' />">查看EE</a><br/>
        <a href="<c:url value='BookServlet?method=findByCategory&category=3' />">查看frameWork</a><br/>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'show.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
      <center> <h1>图书列表</h1> </center>
       <table border="1" align="center">
           <tr>
               <th>书名</th>
               <th>单价</th>
               <th>分类</th>
           </tr>
           <c:forEach items="${requestScope.bookList }" var="book">
               <tr>
                   <td>${book.bname }</td>
                   <td>${book.price }</td>
                   <c:choose>
                       <c:when test="${book.category eq 1}"><td style="color:red;">javaSE</td></c:when>
                       <c:when test="${book.category eq 2}"><td style="color:yellow;">javaEE</td></c:when>
                       <c:when test="${book.category eq 3}"><td style="color:blue;">javaFramework</td></c:when>
                   </c:choose>
                   <td></td>
               </tr>
           </c:forEach>
       
       </table>
      </body>
    </html>
    
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name></display-name>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>BookServlet</servlet-name>
        <servlet-class>cn.itcast.web.servlet.BookServlet</servlet-class>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>BookServlet</servlet-name>
        <url-pattern>/BookServlet</url-pattern>
      </servlet-mapping>    
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      
      <filter>
          <filter-name>StaticFilter</filter-name>
          <filter-class>cn.itcast.web.filter.StaticFilter</filter-class>
      </filter>
      
      <filter-mapping>
          <filter-name>StaticFilter</filter-name>
          <servlet-name>BookServlet</servlet-name>
      </filter-mapping>
    </web-app>
    View Code

  • 相关阅读:
    (转)matlab 字符串处理函数
    (原)不明白JNI指针调用顺序
    (转)几种平均数的关系:
    (原+转)继承与虚函数
    (原)给定输入,输出全排列
    (转)发现两个有用的C函数_alloca()、_msize()
    (原)android的JNI中使用C++的类
    (原+转)C++中的const修饰符
    (转)C/C++中static关键字
    JAVA IO 对象流
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5740717.html
Copyright © 2020-2023  润新知