`
ye5562402
  • 浏览: 7611 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

preparable和ModenDriven拦截器

阅读更多
最近读starting struts2 online,里面有一节Move CRUD Operations into the same Action,提供了Move CRUD Operations into the same Action大概的sample,于是进行了补充,记录下来,以备使用。

一、思路
在这本书里,lan roughley提到在结合preparable和ModenDriven拦截器实现Move CRUD Operations into the same Action,采用通配符的方式为所有的crud只写一个action配置,当然,这也要求相关文件的命名和目录组织的时候要遵循一定的要求,示例如下:

<action name="**" 的形式似乎不行,不得以改成了"*_*"了,哈哈,要是能改成"^_^"就更好了
注:在struts.xml中增加<constant name="struts.enable.SlashesInActionNames" value="true" />,可以使用"*
    public String delete() throws Exception {
        log.info("delete the person");
        service.deletePerson(id);
        return SUCCESS;
    }

   
    public String edit() {
        return "input";
    }

   
    public String update() throws Exception {
        if (id == null || id.length() == 0) {
            log.info("add the person");
            service.addPerson(person);
        } else {
            log.info("update the person");
            service.updatePerson(person);
        }
        return SUCCESS;
    }

   
    public String view() {
        return SUCCESS;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public PersonService getService() {
        return service;
    }

    public void setService(PersonService service) {
        this.service = service;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Person getModel() {
        return person;
    }
}
 

PersonListAction.java  :


package com.work.action.person;

import java.util.List;

import com.work.action.BaseSupport;
import com.work.model.Person;
import com.work.service.PersonService;

public class PersonListAction extends BaseSupport {
    private static final long serialVersionUID = 1810482163716677456L;
    private List<Person> people;
    private PersonService service=new PersonServiceImpl(); ;

    public String execute() throws Exception {
        log.info("list persons");
        people = service.getAllPersons();
        return SUCCESS;
    }

    public List<Person> getPeople() {
        return people;
    }

    public void setPeople(List<Person> people) {
        this.people = people;
    }

    public PersonService getService() {
        return service;
    }

    public void setService(PersonService service) {
        this.service = service;
    }
}
paramsPrepareParamsStack
这里需要说一下关键的paramsPrepareParamsStack拦截器,其中params拦截器出现了两次,第一次位于servletConfig和prepare之前,更在modelDriven之前,因此会将http://localhost:8080/diseaseMS/person/Person_edit.action?id=202中的参数id注入到action中,而不是model中,之后prepare将根据这个id,从服务层提取model。

下面是paramsPrepareParamsStack的英文注释:

An example of the params-prepare-params trick. This stack  is exactly the same as the defaultStack, except that it  includes one extra interceptor before the prepare interceptor:the params interceptor.
This is useful for when you wish to apply parameters directly to an object that you wish to load externally (such as a DAO or database or service layer), but can't load that object  until at least the ID parameter has been loaded. By loadingthe parameters twice, you can retrieve the object in the prepare() method, allowing the second params interceptor toapply the values on the object.

 


<interceptor-stack name="paramsPrepareParamsStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="params"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
</interceptor-stack>
PersonServiceImpl.java

package com.work.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.work.model.Person;

public class PersonServiceImpl implements PersonService {
   
    private List<Person> personList;

    public PersonServiceImpl() {
        personList = new ArrayList<Person>();
        Person p1 = new Person("202", "name1", "beijing");
        Person p2 = new Person("203", "name2", "beijing");
        Person p3 = new Person("204", "name3", "tianjing");
        personList.add(p1);
        personList.add(p2);
        personList.add(p3);

    }

    public void addPerson(Person person) {
        if (person == null) {
            throw new RuntimeException("add kong");
        }
        person.setId(getID(200));
        personList.add(person);
    }

    public void deletePerson(String personID) {
        int target = findLocation(personID);
        if (target != -1)
            personList.remove(target);
    }

    public List<Person> getAllPersons() {
        return personList;
    }

    public void updatePerson(Person person) {
        if (person == null) {
            throw new RuntimeException("update kong");
        }
        int target = findLocation(person.getId());
        personList.remove(target);
        personList.add(person);
       
    }

    private int findLocation(String personID) {
        int target = -1;
        for (int i = 0; i < personList.size(); i++) {
            if (personID.equals(personList.get(i).getId())) {
                target = i;
                break;
            }
        }
        return target;
    }

    public Person find(String personID) {
        Person person = null;
        int target = findLocation(personID);
        if (target != -1) {
            person = personList.get(target);
        }
        return person;
    }
   
    private String getID(int round) {
        Random rand = new Random();
        int needed = rand.nextInt(round) + 1; // 1-linesum+1
        return needed+"";
    }

}

下面就是jsp文件了,就只贴部分了:edit.jsp:
<s:form action="Person_update.action" >
    <s:textfield label="your ID" name="id" readonly="true"/>
    <s:textfield label="Please enter your name" name="name" required="true"  />
    <s:textfield label="Please enter your homeaddr" name="homeAddr" required="true"/>   
    <s:submit />
</s:form>

view.jsp

 

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>person view</title>
</head>

<body>
<s:actionerror />
<table>
    <tr>
        <td>id</td>
        <td>name</td>
        <td>address</td>
        <td></td>
        <td></td>
    </tr>
    <s:iterator value="people">
        <tr>
            <td><s:property value="id" /></td>
            <td><s:property value="name" /></td>
            <td><s:property value="homeAddr" /></td>
            <td><s:url id="update" action="Person_edit.action" >
                <s:param name="id">
                    <s:property value="%{id}" />
                </s:param>
            </s:url> <s:a href="%{update}">修改</s:a>
            </td>

            <td><s:url id="delete" action="Person_delete.action">
                <s:param name="id">
                    <s:property value="%{id}" />
                </s:param>
            </s:url> <s:a href="%{delete}">删除</s:a>
            </td>
        </tr>
    </s:iterator>
</table>
<ul>
    <li><a href="<s:url action="Person_input"/>">Create a new person</a></li>

</ul>
</body>
</html>


三、总结
优点:适用与crud比较的应用程序,大幅减少action的配置信息

其他:

1、也可以不实现modeldriven接口,只不过要在jsp中加上model.properity

2、这种方式在某种程度上透露了action中的方法名称给客户端,是否会带来安全性的问题



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cmtony2008/archive/2009/04/30/4138818.aspx
分享到:
评论

相关推荐

    Java详解ModelDriven和Preparable拦截器.doc

    Java详解ModelDriven和Preparable拦截器 本资源主要讲解了Java中的ModelDriven和Preparable拦截器,旨在解决Action类中包含JavaBean的业务属性的问题。通过使用ModelDriven拦截器,可以将冗余代码抽取出来,把操作...

    [尚硅谷]_封捷_ModelDriven和Preparable拦截器.pdf

    [尚硅谷]_封捷_ModelDriven和Preparable拦截器.pdf

    深入浅出Struts2

    第10章 Model Driven和Preparable拦截器 第11章 持久层 第12章 文件的上传 第13章 文件的下载 第14章 提高Struts应用程序的安全性 第15章 防止重复提交 第16章 调试与性能分析 第17章 进度条 第18章 定制拦截器 第19...

    深入浅出Struts2(附源码)

    第10章 Model Driven和Preparable拦截器 196 10.1 把动作与模型隔离开 196 10.2 Model Driven拦截器 197 10.3 Preparable拦截器 201 10.4 小结 206 第11章持久层 207 11.1 DAO模式 207 11.1.1 DAO模式的最...

    Javaweb技术文档

    封捷_ModelDriven和Preparable拦截器 张晓飞_Tomcat的设计模式分析 张晓飞_Tomcat系统架构分析 张晓飞_UML模型图 张晓飞_WEB书城. 张晓飞_正则表达式学习手册 HTTP协议简介_封捷 JNDI原理_张晓飞 Servlet_封捷 Web...

    深入浅出Struts 2 .pdf(原书扫描版) part 1

    第10章 Model Driven和Preparable拦截器 196 10.1 把动作与模型隔离开 196 10.2 Model Driven拦截器 197 10.3 Preparable拦截器 201 10.4 小结 206 第11章 持久层 207 11.1 DAO模式 207 11.1.1 DAO模式的最简单实现...

    struts+spring+hibernate整合

    Spring4.0、Struts2.3.15、Hibernate4.2.4、jQuery1.9.1涉及到了诸多开发时的细节:ModelDriven、Preparable 拦截器、编写自定义的类型转换器、Struts2 处理 Ajax、OpenSessionInViewFilter、迫切左外连接、Spring ...

    MySQL prepare语句的SQL语法

    MySQL prepare语法: PREPARE statement_name FROM preparable_SQL_statement; /*定义*/ EXECUTE statement_name [USING @var_name [, @var_name] …]; /*执行预处理语句*/ {DEALLOCATE | DROP} PREPARE statement_...

    MySQL中预处理语句prepare、execute与deallocate的使用教程

    PREPARE stmt_name FROM preparable_stmt EXECUTE stmt_name [USING @var_name [, @var_name] ...] - {DEALLOCATE | DROP} PREPARE stmt_name 举个栗子: mysql&gt; PREPARE pr1 FROM 'SELECT ?+?'; Query OK, 0 r

Global site tag (gtag.js) - Google Analytics