Servlet和BeanUtils框架的联合使用(5)

package cn.wwh.www.web.request;

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 com.sun.org.apache.commons.beanutils.BeanUtils;

/**
 *类的作用:利用BeanUtils来将数据存储到实例对象中(这个是一个关键技术)
 * 
 *在浏览器中输入:http://localhost:8080/Summer_Exercise7/RequestBeanUtils?name=wwh&age=
 * 22&salary=12000.23&hobbies=football&hobbies=run
 * 
 * @author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-7-30 下午05:39:32
 */
public class RequestBeanUtils extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


BeanUtils bean = new BeanUtils();
User user = new User();


// 获取客户端输入的所有的参数
Enumeration name = request.getParameterNames();
while (name.hasMoreElements()) {
// 逐一的取出key值
String key = (String) name.nextElement();
// 获取key对应的values值
String[] values = request.getParameterValues(key);

try {
// 将数据逐一的放入到User对象中
bean.setProperty(user, key, values);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


// 将数据写回到服务器中
response.getOutputStream().write(
("<br/>" + user.toString() + "<br/>").getBytes());
System.out.println("" + user.toString());

}

}

User.java:

public class User {
// 名字
private String name;
// 年龄
private int age;
// 薪水
private double salary;
private String[] hobbies;

}


浏览器的地址栏中输入:

http://localhost:8080/Summer_Exercise7/RequestBeanUtils?name=wwh&age= 22&salary=12000.23&hobbies=football&hobbies=run

浏览器输出的结果:

User age=22, hobbies=[football, run], name=wwh, salary=12000.23

这个代码理解上没有任何的难度,但是红色的地方是关键的技术,利用的BeanUtils狂降将所有的数据一次性的设置到User对象中(这种做法非常好)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值