Java Web笔记之Servlet(1)

今天在学习Servlet时,使用浏览器显示的网页效果与预期的有差异,仔细查找发现实<!DOCTYPE>声明的问题,截图如下:

代码如下: 

package secondServlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 87826386236823L;


    /**
     * 以GET方式访问页面时执行该函数
     * 执行doGet方法会执行getLastModified方法,如果浏览器发现getLastModified方法返回
     * 的数值与上次返回的数值相同,则认为该文档没有更新,浏览器采用缓存而不执行doGet方法
     * 如果getLastModified方法返回-1,则认为是时刻更新的,总是执行该函数 
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.log("执行doGet方法...");
        
        this.execute(request, response);
    }

    /**
     * 以POST方式访问页面时执行该函数.执行前不会执行getLastModified方法
     * 
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.log("执行doPost方法...");
        
        this.execute(request, response);
    }
    
    
    @Override
    public long getLastModified(HttpServletRequest request){
        this.log("执行 getLastModified方法...");
        return 0;
    }
    
    
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
    
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String param = request.getParameter("param");
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
//        out.println("<!DOCTYPE HTML>");
        out.println("<HTML>");
        out.println("  <head><title> A Servlet</title></head>");
        out.println("  <body>");
        out.println("  以 " + method + " 方式访问该页面. 取到的param参数为: " + param + "<br/>");
        
        out.println("  <form action='" + requestURI + "' method='get'> <input type='text' name='param' value='param string'><input type='submit' value='以GET方式查询页面 RequestServlet'></form>");
        out.println("  <form action='" + requestURI + "' method='post'> <input type='text' name='param' value='param string'><input type='submit' value='以POST方式提交到页面  RequestServlet'></form>");
        out.println("  <script>document.write('本页面最后更新时间: ' + document.lastModified + '<br/>'); </script>");
        out.println("  <script>document.write('本页面URL: ' + location  + '<br/>'); </script>");
        out.println("  </body>");
        out.println("</HTML>");
        out.flush();
        out.close();
        
    }

}
原文地址:https://www.cnblogs.com/datapool/p/6195884.html