如下图:1.在网页中有这样一个表单,填写表单之后需要将表单内容保存到数据库中
处理关系图:
2.对应的数据库表的内容为:
3.对应的JavaBean为:
package com.yangguang.domain;
import java.io.Serializable;
//分类
public class Category implements Serializable {
private String id;//UUID
private String name;
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
现在需要的就是将1,2,3通过处理按照上图联系起来(1->2->3)
需要依赖两个jar包:
commons-beanutils-20030211.134440.jar
commons-logging-1.1.3.jar
在Servlet中,我们获取到Web端发来的请求,所以,将Request请求中的表单数据调用我们编写的处理类FillBeanUtil
相关代码如下:
Servlet中:
private void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从请求里面将数据进行封装
Category category = fillBeanUtil.fillBean(request,Category.class);
category.setId(UUID.randomUUID().toString());
businessService.addCategory(category);
//转到一个界面
request.setAttribute("msg", "保存成功!");
request.getRequestDispatcher("/manager/savaSuccess.jsp").forward(request, response);
}
FillBeanUtil类的实现:
package com.yangguang.util;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
/**
* 封装请求数据到JavaBean中
* @author yangguang
*2017年8月24日
*/
//Class<T> calzz可以接受任何类型的javaBean,使用泛型调用者不用进行强制性转换
public class fillBeanUtil {
public static <T> T fillBean(HttpServletRequest request,Class<T> clazz) {
try {
//创建封装数据的bean
T bean = clazz.newInstance();
BeanUtils.copyProperties(bean,request.getParameterMap());
return bean;
} catch (Exception e) {
throw new RuntimeException();
}
}
}
增加部分:
其实还有另外一种方法:不使用BeanUtils,利用Java反射机制:表单数据自动封装到JavaBean
链接:http://www.cnblogs.com/zxb5116/p/3747025.html