struts2学习04——数据封装核心机制

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.将表单数据写入实体类中

例如上面的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();
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值