现在的位置: 首页 > 操作系统 > 正文

在Struts2中使用ModelDrivenaction

2020年02月10日 操作系统 ⁄ 共 2191字 ⁄ 字号 评论关闭

在Struts2中,提供了另外一种直接使用领域对象的方式,那就是让action实现com.opensymphony.xwork2.ModelDriven接口。ModelDriven让你可以直接操作应用程序中的领域对象,允许你在Web层和业务逻辑层使用相同的对象。

ModelDiven接口中只有一个方法,如下

public T getModel();

该方法返回一个接受用户输入数据的对象模型。在页面中,这个模型对象中的属性可以直接通过对象名来访问,嗯不需要使用user.name来访问,在action类中,也不需要为这个对象提供getter和setter方法。

代码如下:

package action;

import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ModelDriven;import entity.User;

public class Model implements Action,ModelDriven<User> { private User user=new User(); @Override public User getModel() { return user; }

@Override public String execute() throws Exception { return SUCCESS; }}

实体类:

package entity;public class User { private String name;

public String getName() { return name; }

public void setName(String name) { this.name = name; }}

首先还是老样子,创建一个login.jsp,登陆后经过Stuts2的拦截器,找到并进入自定义的实现了action接口和ModelDriven接口的Model类

返回SUCCESS,在stuts.xml中定向到success.jsp页面。

在success.jsp页面中,我们只需要如下定义,就可以实现原有功能

<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="s" uri="/struts-tags" %><%@ page isELIgnored="false" %><html><head> <title>Title</title></head><body><s:debug></s:debug><s:fielderror></s:fielderror>Hello <s:property value="name"/><s:iterator value="list" id="str"> <s:property value="str"/></s:iterator>

</body></html>

登陆后的效果如下

那么什么时候应该使用领域对象,什么时候应该实现ModelDriven接口呢?这两种方式其实实际上没有本质的差别,对于大多数的应用,使用任何一种方式都可以。

推荐阅读:

Struts中异步传送XML和JSON类型的数据 http://www.xuebuyuan.com/Linux/2013-08/88247.htm

Struts2的入门实例 http://www.xuebuyuan.com/Linux/2013-05/84618.htm

Struts2学习笔记-Value Stack(值栈)和OGNL表达式 http://www.xuebuyuan.com/Linux/2015-07/120529.htm

struts2文件上传(保存为BLOB格式) http://www.xuebuyuan.com/Linux/2014-06/102905.htm

Struts2的入门实例 http://www.xuebuyuan.com/Linux/2013-05/84618.htm

Struts2实现ModelDriven接口 http://www.xuebuyuan.com/Linux/2014-04/99466.htm

遇到的Struts2文件下载乱码问题 http://www.xuebuyuan.com/Linux/2014-03/98990.htm

Struts2数据验证机制 http://www.xuebuyuan.com/Linux/2016-10/135995.htm

struts2简单示例 http://www.xuebuyuan.com/Linux/2016-11/137146.htm

Struts2绑定对象数组 http://www.xuebuyuan.com/Linux/2017-01/139080.htm

Struts2 s:if标签以及 #,%{},%{#}的使用方法 http://www.xuebuyuan.com/Linux/2016-11/137188.htm

Struts 的详细介绍:请点这里Struts 的下载地址:请点这里

本文永久更新链接地址:http://www.xuebuyuan.com/Linux/2017-03/141203.htm

以上就上有关在Struts2中使用ModelDrivenaction的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.