手记

request请求参数的获取+BeanUtils框架--学习笔记

取得请求体相关的信息

  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;    }}

0人推荐
随时随地看视频
慕课网APP