String getParameter(String name) 取得表单中指定名字的表单项值
String[] getParameterValues(String name) 取得表单中指定名字的表单项的所有值
下面附带一个例子:
//index.html
测试Servlet页面 //MyServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
public MyServlet() {//构造函数
super();
}
public void destroy() {//销毁时将调用的方法
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
//处理以GET方式提交过来的表单数据
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);//直接调用doPost方法
}
//处理以Post方式提交上来的表单数据
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");//设置响应采用的编码方式
String name = request.getParameter("name");//从提交上来的表单中取name文本框的值
name = new String(name.getBytes("ISO8859-1"),"gb2312");//将字符编码转换为gb2312
PrintWriter out = response.getWriter();
ServletContext context = getServletContext();//得到整个Web应用的ServletContext对象
int count = 1;//从1开始起计
if (context.getAttribute("count")==null){//如果是第一位访客
context.setAttribute("count",new Integer(count));//设置计数器初始值
}else{//如果不是第一位访客
count = Integer.parseInt(context.getAttribute("count").toString());//取出现有的计数值
count++;//计数加1
context.setAttribute("count",new Integer(count));//更新计数器内容
}
out.println("");
out.println("
A Servlet");
out.println(" ");
out.println(name+", 你好!你是第"+count+"位访客!");//实现简单问好
out.println(" ");
out.println("");
out.flush();
out.close();
}
//本Servlet装载到容器后将自动执行的初始化方法
public void init() throws ServletException {
// Put your code here
}
}