struts2的数据封装,主要是借助java反射机制实现的,下面通过简单的代码示例来回顾一下今天的学习。
通过模型驱动的方式,我们在Action中,常会出现以下的代码:
public class LoginServlet extends BaseServlet {
Users us = new Users();
public String execute() throws Exception {
System.out.println(us.getUsername());
System.out.println(us.getPassword());
return "success";
}
public Users getModel() {
return us;
}
}
struts2框架,将数据的封装工作完成了,我们只需要定义一个实例对象,并按照规定语法来编写,就可以自动的获取到页面表单的数据,并封装到实例类中,例如上面的us实例。
为了完成从页面获取数据,并将其封装到实例类中,需要以下步骤:
1.在请求发送过来,进入action之前,先执行getModel方法,获取要将表单数据封装到哪个实体类中
2.得到该对象后,我们可以获得 类类型
3./获得类类型之后, 获取类属性
4.request.getParameterNames()获取表单提交的数据名
5.从而获取表单提交的数据
6.如果表单中数据name和实体类中的属性名一致
7.将表单数据写入实体类中
2.得到该对象后,我们可以获得 类类型
3./获得类类型之后, 获取类属性
4.request.getParameterNames()获取表单提交的数据名
5.从而获取表单提交的数据
6.如果表单中数据name和实体类中的属性名一致
7.将表单数据写入实体类中
例如上面的LoginServlet相当于在struts2开发中的Action,那么他的父类BaseServlet就相当于struts2开发中的ActionSupport类
则根据上面的分析,我们可以实现出BaseServlet中doPost的代码:
public class BaseServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Method method = this.getClass().getDeclaredMethod("getModel", null);
Object ob = method.invoke(this, null);
System.out.println(ob);
Field[] fd = ob.getClass().getDeclaredFields();
Enumeration<String> em = request.getParameterNames();
while(em.hasMoreElements()){
String fieldName = em.nextElement().toString();
System.out.println("表单的属性名:"+fieldName);
for(int i=0;i<fd.length;i++){
if(fd[i].getName().equals(fieldName)){
String val = request.getParameter(fd[i].getName());
fd[i].setAccessible(true);
fd[i].set(ob, val);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}