Servlet程序演示doGet()和doPost()方法

ContractedBlock.gif ExpandedBlockStart.gif 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()方法的区别,区别总结如下,

 

 


 

转载于:https://www.cnblogs.com/FCWORLD/archive/2011/10/19/2218240.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值