取得請求體相關的信息
a)request.getParameter(String):String
b)request.getParameterValues(String):String[]
注意:在GET請求方式下,若是參數不一致,返回null,可能出現空指針異常
c)BeanUtils框架可以自動將String參數設置到JavaBean對象中(commons-beanutils-1.8.0.jar、commons-logging.jar)
1)無需理會參數的類型,個數,可是參數名必定要和JavaBean中的字段一致
2)String->8種基本類型自動轉換,非8種基本類型能夠註冊轉換器材
3)String或String[]類型的參數自動感知裝配
java代碼:
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
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;
import cn.web.request.domain.User;
public class Rdome3 extends HttpServlet {
//http://localhost:8080/day04/Rdome3?username=jack&age=30&salary=5000&likes=dance&likes=sing回車
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//分別取得的客戶端提交的信息
String strUsername =request.getParameter("username");
String strAge = request.getParameter("age");
String strSalary = request.getParameter("salary");
String[] strLikes = request.getParameterValues("likes"); //一對多;
//判斷
BeanUtils bu = new BeanUtils();
User user = new User();
Enumeration<String> enums = request.getParameterNames();
while(enums.hasMoreElements())
{
String keys = enums.nextElement();
String[] values = request.getParameterValues(keys);
try {
bu.setProperty(user, keys, values);
} catch (Exception e) {
e.printStackTrace();
}
}
//處理中文
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write("用戶名:" + strUsername + "<br/>");
pw.write("年齡:" + strAge + "<br/>");
pw.write("指望薪水:" + strSalary + "<br/>");
pw.write("愛好個數:" + strLikes + "<br/>");
pw.flush();
pw.close();
}
}
user.java
public class User {
private String username;
private int age;
private double salary;
private String[] likes;
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String[] getLikes() {
return likes;
}
public void setLikes(String[] likes) {
this.likes = likes;
}
}