活学活用 Struts (转)

2024-03-27 08:58
文章标签 struts 活学活用

本文主要是介绍活学活用 Struts (转),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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 加入οnsubmit="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;     }   }


Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=2064431

这篇关于活学活用 Struts (转)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/851584

相关文章

在struts.xml中,如何配置请求转发和请求重定向!

<span style="font-size:18px;"><span style="white-space:pre"> </span><!--<strong>下面用请求转发action </strong>,<strong>这样过去id不会丢</strong>,如果用重定向的话,id会丢 --><result name="updatePopedom"<span style="color:#ff00

修改struts中:fielderror.ftl 模板

在项目登录页面: 当验证码输入有误时,应该提示:验证码输入有误,请重新输入 ,但是页面出现乱了! 错误原因: 在产生错误信息时,页面中增加了<ul> <li><span></span></li></ul>标签,该如何修改改, 解决方法(一): 在项目的src下,新建文件夹:template.simple,在文件夹里面放修改好的fielderror.ftl文件。 fi

Struts 2的工作流程

基本简要流程如下:1、客户端浏览器发出HTTP请求。2、根据web.xml配置,该请求被 FilterDispatcher接收。3、根据struts.xml配置,找到需要调用的Action类和方法, 并通过IoC方式,将值注入给Aciton。4、Action调用业务逻辑组件处理业务逻辑,这一步包含表单验证。5、Action执行完毕,根据 struts.xml中的配置找到对应的返回结果result

struts2 struts.xml常用常量配置

<constant name="struts.i18n.encoding" value="UTF-8" /> 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 <constant name="struts.ui.theme" value="simple" /> 设置页面struts标签的样式     <consta

struts 页面取值问题

Struts2中的OGNL表达式语言是对Xwork的OGNL的封装。我们要理解一下几点:  1 . Struts2 中将 ActionContext 作为 OGNL 的上下文环境( ActionContext 内部含有一个 Map 对象)   2 . Struts2 中的 OGNL 表达式语言的根对象是一个 ValueStack , ValueStack 中的每一

struts和struts2的区别

2012-07-08 14:30 liujunzyf | 分类:JAVA相关 | 浏览8116次 分享到: 2012-07-08 14:41 提问者采纳 你问的应该是 struts1 和struts2 的区别:Struts2与Struts1的对比 1,在Action实现类方面: Struts1要求Action类继承一个抽象基类;Str

struts通配符配置

通配符配置 <!--method属性值为1表示匹配一个*。如用户的请求是book_add.action。则name的属性值是book_add,method的属性值是add  --><action name="book_*" class="action.AddBook" method="{1}"><result name="success">/success.jsp</result><

struts.xml与Web.xml的配置

web.xml的配置 <?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://jav

Struts2控制器以及struts.xml与web.xml的配置(1)

MVC设计模式 MVC设计模式的宗旨是把一个Web应用的输入、处理和输出流程按照Model、View、和Controller的方式进行分离,这样一个应用就被分成3个层:模型层、视图层、和控制层。 视图(view):视图代表用户交互界面。MVC对于视图的处理仅限于视图中数据的采集与处理以及用户的请求处理,而不包括对视图中业务流程的处理。 模型(Model):表示业务数据与业务逻辑,它是Web应

struts 1

Struts 1 配置文件 Struts 1 应用的配置文件有两个分别是web.xml与struts-config.xml文件。其中,web.xml文件时配置所有Web应用的,而struts-config.xml文件时Struts 1专用配置为文件。 web.xml的文件配置 <?xml version="1.0" encoding="UTF-8"?><web-app xmlns="htt