获取请求数据时,一般来说都要先检查再使用。
先写好test.html
<!DOCTYPE html>
<html>
<head>
<title>传数据给GetRequestInf</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<!--客户机给服务器传数据的形式-->
<!--形式一:利用超链接-->
<a href="/RequestTest/servlet/GetRequestInf?username=xxx">checked</a>
<!--形式二:从form表单提交-->
<form action="/RequestTest/servlet/GetRequestInf" method="post">
UserName1<input type="text" name="username"></br>
UserName2<input type="text" name="username"></br>
PassWord <input type="password" name="password"></br>
<input type="submit" value="submit">
</form>
</body>
</html>
配置好User.java
package RequestDemo;
public class User
{
private String UserName[];
private String PassWord;
public String[] getUserName()
{
return UserName;
}
public void setUserName(String[] userName)
{
UserName = userName;
}
public String getPassWord()
{
return PassWord;
}
public void setPassWord(String passWord)
{
PassWord = passWord;
}
}
再写好GetRequestInf.java
package RequestDemo;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
public class GetRequestInf extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//根据名称获取客户机带过来的指定名称的值,若有多个,则只能获取第一个
String value = request.getParameter("username");
//检查value是否为空
if(value!=null && !value.trim().equals(""))
{
System.out.println(value);
}
//获取所有名称和值(为方便起见,此处未检查提交字符是否为空,开发中应检查)
Enumeration e = request.getParameterNames();
while(e.hasMoreElements())
{
String nameString = (String) e.nextElement();
String valueString = request.getParameter(nameString);
System.out.println(nameString + "=" + valueString);
}
//根据名称获取客户机带过来的指定名称的所有值
String[] values = request.getParameterValues("username");
for(int i=0;values!=null && i<values.length;i++)
{
System.out.println(values[i]);
}
//利用JavaBean获取客户机带过来的所有值
Map<String,String[]> map = request.getParameterMap();
User user = new User();
try
{
//用来将一些 key-value的值映射到 bean中的属性
BeanUtils.populate(user,map);
} catch (Exception exception)
{
exception.printStackTrace();
}
System.out.println(user);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
其在web.xml中的相关配置为:
<servlet>
<servlet-name>GetRequestInf</servlet-name>
<servlet-class>RequestDemo.GetRequestInf</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetRequestInf</servlet-name>
<url-pattern>/servlet/GetRequestInf</url-pattern>
</servlet-mapping>