View Code
package com.wyf.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
public class FirstServlet extends HttpServlet implements Servlet {
public FirstServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.log("执行doGet()方法... "); // 调用Servlet自带的日志输出信息到控制台
this.execute(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.log("执行doPost()方法... "); // 调用Servlet自带的日志输出信息到控制台
this.execute(req, resp);
}
public void execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8"); // 设置resp的编码格式
req.setCharacterEncoding("UTF-8"); // 设置resp的编码格式
String reqURL = req.getRequestURI();// 设置访问该Servlet的URL
String method = req.getMethod(); // 设置访问Servlet的方法,GET活POST
String param = req.getParameter("param");// 设置客户端提交的参数param的值
resp.setContentType("text/html"); // 设置文档类型为HTML
PrintWriter out = resp.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC\" -//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<html>");
out.println("<head><title>A Servlet</title></head>");
out.println("<body>");
out.println("以" + method + "方式访问该页面,取到的param参数为:" + param + "<br/>");
out
.println("<form action='"
+ reqURL
+ "' method='get'><input type='text' name='param' value='param String'><input type='submit' value='以get方式查询界面"
+ reqURL + "'></form>");
out
.println("<form action='"
+ reqURL
+ "' method='post'><input type='text' name='param' value='param String'><input type='submit' value='以post方式查询界面"
+ reqURL + "'></form>");
// 有客户端浏览器读取该文档的更新时间
out
.println("<script>document.write('本页面最后的更新时间:'+ document.lastModified);</script>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
}
运行结果:
(1) FirstServlet: 执行doPost()方法...
(2)FirstServlet: 执行doGet()方法...
这里显示了doGet()和doPost()方法的区别,区别总结如下,