1、web目录下的hello.html
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>菜鸟教程(runoob.com)title>
head>
<body>
<form action="HelloForm" method="get">
网址名:<input type="text" name="name">
<br />
网址:<input type="text" name="url">
<input type="submit" value="提交">
form>
body>
html>
2、src下的HelloForm.java
public class HelloForm extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloForm(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
//设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();//准备输入
String title ="使用get方法读取表单数据";
//表单输入的数据中有中文则需要转码
String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
String doType = " \n";
out.println(doType +
"\n" +
"" + title +"\n" +
"\"#f0f0f0\">\n" +
"\"center\"> "+ title + "
\n" +
"\n" +
"站点名:"
+ name +"\n"+
"网址:"
+ request.getParameter("url")+"\n"+
"\n" +
"");
}
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}
2、设置一下web-xml
<servlet>
<servlet-name>HelloFormservlet-name>
<servlet-class>HelloFormservlet-class>
servlet>
<servlet-mapping>
<servlet-name>HelloFormservlet-name>
<url-pattern>/HelloFormurl-pattern>
servlet-mapping>
3、试输入网址名和网址,然后点击"提交"按钮,Gif 演示如下:
读取所有的表单参数
1、ReadParams.java
public class ReadParams extends HttpServlet {
private static final long serialVersionUID = 1L;
public ReadParams(){
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "读取所有的表单数据";
String docType =
"\"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"\n" +
"\"utf-8\">" +title +"\n"
+"body bgcolor=\"#f0f0f0\">\n" +
"\"center\">" + title +"
" +
"\"100%\" border=\"1\" align=\"center\">\n" +
"\"#949494\">\n" +
"参数名称 | 参数值 | \n"+
"
\n");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()){//刚开始的时候Enumeration的游标指向-1,所以可以全部遍历
String paramName = (String)paramNames.nextElement();
out.println("" + paramName + " | \n");
String[] paramValues = request.getParameterValues(paramName);
//读取单个值的数据
if(paramValues.length == 1){
String paramValue = paramValues[0];
if(paramValue.length() == 0)
out.println("没有值 | ");
else
out.println("" + paramValue +" | ");
}
else{//读取多个数据
out.println("");
for(int i = 0;i < paramValues.length;i++){
out.println("- "
+paramValues[i]);
}
out.println(" | ");
}
out.println("
");
}
out.println("\n
\n