您的位置:首页 > 产品设计 > UI/UE

将request容器中的参数封装到javabean中

2013-12-08 21:02 387 查看
WEB开发中,将表单提交的数据封装到bean中,这样servlet处理起来,不需要多次调用request.getParameters方法来获取request容器的参数,将request参数封装到bean中,方便servlet来处理;代码也会更加清晰和优雅。下面是一个例子。

//example,将request对象封装到T的对象中

public static <T> T request2Bean(HttpServletRequest request,Class<T> clazz){

try{
T t = clazz.newInstance(); //申请一个对象

//自定义转换类,对日期进行转换
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
if (value == null) {
return null;
}
if (!(value instanceof String)) {
throw new ConversionException("conversion error");
}
String str = (String) value;
if (str.trim().equals("")) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(str);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}, Date.class);

Enumeration<String> e = request.getParameterNames();
while(e.hasMoreElements()){
String name = e.nextElement();
String value = request.getParameter(name);
BeanUtils.setProperty(t, name, value);
}
return t;
}catch (Exception e) {
throw new RuntimeException(e);
}

}
//demo,User对象

public class User {
private String id;
private String name;
private String gender;
private String type;
private String cellphone;
private Date birthday;
private String email;
private String prefences;
private String description;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPrefences() {
return prefences;
}
public void setPrefences(String prefences) {
this.prefences = prefences;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}

}

//servlet

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
try{
User user = WebUtils.request2Bean(request, User.class);//将request容器中的参数封装到User类中
BusinessService service = BusinessServiceFactory.newInstance().createService();
service.add(user);

request.setAttribute("message", "客户添加成功!!");
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "客户添加失败!!");
}

request.getRequestDispatcher("/message.jsp").forward(request, response);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐