javaEE之-----------类反射直接封装前台传过来的参数

在JavaEE  WEB中,我们收集form表单传过来的数据,通常是采用值对象的方式,一一去获取,封装,然后将值对象传到后台进行使用。

如:

<span style="font-size:18px;">                String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		String id =request.getParameter("id");
		User user =new User();
		user.setUid(id);
		user.setName(name);
		user.setPwd(pwd);</span>
每次都这样很麻烦,现在我们有了新的技术

采用这两个包就可以实现。

<span style="font-size:18px;">	public void login(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Map<String, String[]> map=req.getParameterMap();
		User user = BeanUtils.populate(User.class, map);
		System.out.println(user);</span>

servlet中我们就只需要调用一下就可以做到,User值对象中,我们前台有的参数就能set,没有的也可以不用理会。

但是我们采用这个需要注意:前台页面代码<input type="text" name="name"/>这个参数一定要对上,和值对象中的要一致,不然会不成功,因为在类反射中,我们都是得到变量名,再去调用set+变量名一个大写进行设置的。

<span style="font-size:18px;">public class BeanUtils {
	public static <T>T populate(T t,Map<String,String[]> map){
		try{
			org.apache.commons.beanutils.BeanUtils.populate(t,map);
			return t;
		}catch(Exception e){
			throw new RuntimeException(e.getMessage(),e);
		}
	}
	public static <T>T populate(Class<T> cls,Map<String,String[]> map){
		try{
			T t = cls.newInstance();
			return populate(t, map);
		}catch(Exception e){
			throw new RuntimeException(e.getMessage(),e);
		}
	}</span>
上面 用到了两个包,只需要将这个相应的参数传过来,我们就可以进行相应的封装(其实用到的就是类反射)

两个包下载地址


发布了107 篇原创文章 · 获赞 30 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/yangxin_blog/article/details/50486924