活学活用 Struts

来源:互联网 发布:手持式数据终端器 编辑:程序博客网 时间:2024/06/13 06:02

作者:calvin, guangnian0412

1.概述 

    Struts大家都很熟悉,不再详细介绍,另请请参阅 

1. Pragmatic Struts :SpringSide推荐的最新最Pragmatic用法。

2. SpringSide的Struts封装,SpringSide封装的Struts的CRUD Action基类,默认拥有CRUD的方法,大家可以自行扩展,或者这参考其思路重新封装。

1.1 参考书籍

《Jakarta Struts Cookbook》2005 O'Reilly,在铁手的博客上有部分中文翻译。

2. Spring与Struts的整合

2.1 在struts-config.xml中加入ContextLoaderPlugIn

ContextLoaderPlunIn是Struts 1.1+ 的插件,用来为 Struts 的 ActionServlet 加载 Spring的Application Context。这个Context引用 WebApplicationContext (由 ContextLoaderListener 加载) 作为它的父Context。默认的context文件是映射的 ActionServlet 的名字,加上 -servlet.xml后缀。 如果 ActionServlet 在 web.xml 里面的定义是 action, 那么默认的文件就是 /WEB-INF/action-servlet.xml

格式如下:

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"/>

2.2 在Struts-config.xml中加入DelegatingRequestProcessor

 用Spring的DelegatingRequestProcessor重载Struts 默认的 RequestProcessor。这样当收到一个针对Action的请求时,DelegatingRequestProcessor会自动从Spring Context中查找对应的Action Bean。

格式如下:

<controller><set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/></controller>

2.3 建立struts-config.xml与action-servlet.xml中Action与Bean的对应关系

 连接 struts-config.xmlaction-servlet.xml 中的 Action与Bean的桥梁是action 的"path"和 bean 的"name"。如果你在 struts-config.xml 文件中有如下配置:<action path="/users" .../>
 你必须在 action-servlet.xml 中将 Action bean 的名字定义为 "/users":<bean name="/users" class="..."/>
设定完以后,action的type属性可以省略不写,因为所有的Action都在Spring Context中寻找。注意这里bean用的是name属性,而不是id,因为"/"在id属性中是非法字符。

3.输入校验与消息显示

      校验依旧比较麻烦,使用commons-validator 1.3版,使用struts 1.3.5带的validator-rules.xml。可选的validator 以 validator-rules.xml 中定义的为准。

 3.1  定义  

    注意validaton.xml的头声明需改为1.3

<!DOCTYPE form-validation PUBLIC        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"        "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

      编写validation.xml,如

<form name="userForm">            <field property="name" depends="required">                <arg0 key="user.name"/>            </field></form>

并在resources/i18n/messages.properties 里加入需要的message,如user.name = User Name

     struts-config.xml 加入

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">        <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/></plug-in>

   3.2 客户端JS校验:

   在每个form.jsp的form 加入onsubmit="return validateUserForm(this)", 其中UserForm是validation.xml中的form名

    在jsp最后加入

<html:javascript formName="userForm" staticJavascript="false" cdata="false"/><script type="text/javascript" src="<c:url value="/scripts/validator.jsp"/>"></script>

 3.3 服务端校验:

ActionMessages errors = form.validate(mapping, request);        if (!errors.isEmpty()) {            saveErrors(request, errors);            return mapping.findForward("edit");        }

3.4 出错信息的显示:

   信息参见message.jsp,可显示信息或错误。

   在希望显示信息的地方加入<%@ include file="/commons/messages.jsp" %>

   如果希望同时在列里面显示出错,加入<span class="fieldError"><html:errors property="user.name"/></span>

 

附录:Pragmatic Struts 

Pragmatic Struts

    Struts 1.2 其实已经大不同,只要大家有简约的态度,即使我们日常的Struts,同样可以写得非常精简,不一定要如传统观念认为的那么繁重,从而节约每天编码的时间。

    Struts与Spring结合的基本知识请阅读Struts使用要点。

1.DispatchAction

     以一个Controller响应一组动作绝对是Controller界的真理,Struts的DispatchAction同样可以做到这点。

<action path="/admin/user" name="userForm" scope="request" parameter="method" validate="false">    <forward name="list" path="/admin/userList.jsp"/></action>

    其中parameter="method" 设置了用来指定响应方法名的url参数名为method,即/admin/user.do?method=list 将调用UserAction的public ActionForward list(....) 函数。   

    public ActionForward unspecified(....) 函数可以指定不带method方法时的默认方法。

2.No FormBean

    Struts 1.2.7 之后一共有三种方法,不需要定义FormBean Java类也不需要在struts-config.xml里详细定义formBean的每个属性。

    第一种是appfuse里使用的,定义DynaValidatorForm里,内嵌一个pojo属性.

<form-bean name="userForm" type="org.apache.struts.validator.DynaValidatorForm">            <form-property name="user" type="org.appfuse.model.User"/></form-bean>
//取得form DynaActionForm userForm = (DynaActionForm) form;User user = (User) userForm.get("user");//设置formuserForm.set("user",user);

    第二种是用BeanValidatorForm,直接把Pojo作FormBean,无需继承于FormBean接口。

<form-bean name="userForm" type="org.springside.helloworld.domain.User"/>
//取得form BeanValidatorForm userForm = (BeanValidatorForm) form;User user = (User) userForm.getInstance();//设置formBeanUtils.copyProperties(userForm, user);

    第3种是用LazyValidatorForm ,特别适合于FormBean中并不包含POJO商业对象所有属性的情况,因为通常项目里都属于这种情况,所以springside默认使用lazyValidatorForm.

    比如User对象 有 id,name,status三个属性,而form表单中只有id和name两个input框,如果使用方法1,2,直接把user 作为 form bean,  user对象的status因为没设值,将为null,  copy 到作为商业对象的user时,就会以null覆盖原值。而lazyBean就没有这个问题,如果form中没有status属性,它不会将它copy给商业对象。

    另外,apache commons-beantuils 1.7.0的lazybean仍有小bug,需要使用commons-1.7.1 snapshot版,而且它直接提供下载的snapshot版缺少了几个class,应使用springside提供的版本。

<form-bean name="bookForm" type="org.apache.struts.validator.LazyValidatorForm"/>
BeanUtils.copyProperties(user, form);

       注意User对象被自动绑定,默认Integer id 在空值时会被赋值为0,需要增加converter,让其默认为null,虽然也可以在web.xml里进行相关配置,但还是在基类里配置了比较安全。

static {ConvertUtils.register(new IntegerConverter(null), Integer.class);}

3. struts-config.xml使用通配符

     对一些CRUD的Action,可以使用通配符,如果这批action里某个action某个方法还存在特殊路径,可以在代码里直接new ActionForward("/foo.jsp");

<action path="/admin/*" name="{1}Form" parameter="method" scope="request" validate="false">            <forward name="list" path="/WEB-INF/pages/admin/{1}List.jsp"/>            <forward name="edit" path="/WEB-INF/pages/admin/{1}Form.jsp"/>            <forward name="success" path="/admin/{1}.do?method=list" redirect="true"/></action>

  4. 一些不必受困于Struts机制的简化写法

    一些简便直接的方法,大家可不必太受困于Struts的机制:

  4.1 不在struts-config.xml配置jsp路径,直接在代码里跳转

     用于某些需要在代码里动态拼装的路径:

return new ActionForward("/foo/bar.jsp");orreturn new ActionForward("/foo/bar.jsp",true);//redirect

   4.2 不走jsp,直接输出字符串

ActionForward execute(....){    try {            response.setContentType("text/html;charset=UTF-8");            response.getWriter().write(text);    } catch (IOException e) {            log.error(e);    }    return null;}

 4.3. 不依赖Struts Taglib,EL直接输出FormBean 属性

普通FormBean:${bookForm.image}

LazyValidatorForm:${bookForm.map.image} 

其中bookForm 是formBean名。另一种输出属性的方式是使用jodd-form, 设<jodd:form bean="bookForm">

4.4 不用i18N地使用Message与Error

   Struts的ActionMessages很常用,但只接收i18N的key作为输入参数,老定义i18n很麻烦,偏方之一就是设一个message= {0},然后直接new ActionMessage("message", message);

5. 终极化简--StrutsEntityAction

 SpringSide封装的EnttiyCRUDAction,,每个包含了CRUD操作的Action仅需如下代码,详细请阅读SpringSide的Struts封装

public class UserAction extends StrutsEntityAction<User,UserManager> {     private UserManager userManager;     public void setUserManager(UserManager userManager) {           this.userManager = userManager;     }   }
原创粉丝点击