首先你需要下载工具类jar,可到官网进行下载
commons-beanutils-1.9.3.jar
commons-logging-1.2.jar
简单使用
1.首先你需要一个实体类
里面一定要实现get/set方法
公有的构造函数
如:
package com.lxy.entity;
public class User {
private String username;
private String password;
public User() {
super();
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
简单使用:
bean工具类里主要使用到的方法
BeanUtils.populate(bean, properties);
第一参数为类的对象,第二个为传过来的多个参数
BeanUtils.populate(user, request.getParameterMap());
这样的就可以帮你封装好一个User对象了
<form action="FiveServlet" method="get">
用户名:<input type="text" name=username><br>
密码:<input type="text" name=password><br>
<input type="submit" value="登录">
</form>
传过来的参数的name一定要和实体类中的属性名一样,否则会不成功。
当然这只是简单的用法,不够灵活,不仅可以灵活的处理不同方式的编码问题,还可以更灵活的传一个对象进来,不需要每次都new,只需要传个class进来,利用反射进行处理,我们可以给它封装个方法
package com.lxy.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
public class WebUtil {
public static <T> T parse(Class c,HttpServletRequest request ){
//先获取请求方式
String method = request.getMethod();
//post请求方式处理编码
if("post".equalsIgnoreCase(method)){
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Object instance = null;
//给对象的属性方法设置相应的值
try {
instance = c.newInstance();
BeanUtils.populate(instance, request.getParameterMap());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//请求方式处理编码,需要把原来的值再重新设置编码
if("get".equalsIgnoreCase(method)){
try {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
//获取属性名
String fieladName = field.getName();
//获取get/set方法
String getMethod = "get"+(char)(fieladName.charAt(0)-32)+fieladName.substring(1);
String setMethod = "set"+(char)(fieladName.charAt(0)-32)+fieladName.substring(1);
Method method1 = c.getDeclaredMethod(getMethod, null);
//属性的类型
Class type = field.getType();
Method method2 = c.getDeclaredMethod(setMethod, type);
//获取getXXX()方法的值
String invoke = (String)method1.invoke(instance, null);
//进行编码
String str = new String(invoke.getBytes("iso-8859-1"), "utf-8");
method2.invoke(instance,str);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return (T)instance ;
}
}