Struts2 - Conversion Plugin

转载:http://www.cnblogs.com/ikuman/archive/2013/11/04/3403073.html

1、struts2自2.1以后推荐使用Convention Plugin支持struts零配置支持(引入jar:struts2-convention-plugin-2.x.x.jar)
①convention默认扫描所有实现com.opensymphony.xwork2.Action的类和指定包路径下以Action结尾的类名
②struts.convention.package.locators指定默认的根packages,struts.convention.action.packages指定搜索的packages下的action,

struts.convention.exclude.packages指定忽略的packages
③默认视图路径:WEB-INF/content(可通过struts.convention.result.path修改)
2、results和resultcodes
①容器启动后,convention会自动加载所有action和jsp
②可以指定不同的结果页面,action-resultcode.jsp
③可以认为默认匹配顺序为actionName+resultcode+suffix>actionName+suffix


URL


Result


File that could match


Result Type


/hello


success


/WEB-INF/content/hello.jsp


Dispatcher


/hello


success


/WEB-INF/content/hello-success.htm


Dispatcher


/hello


success


/WEB-INF/content/hello.ftl


FreeMarker


/hello-world


input


/WEB-INF/content/hello-world-input.vm


Velocity


/test1/test2/hello


error


/WEB-INF/content/test/test2/hello-error.html


Dispatcher

3、chain链
①一个action调用同一个包中的另一个action
②若一个action未定义相对应的resultcode的result,且同一个包中有形如action-resultcode的action,如:

package com.example.actions;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport; 

public class HelloAction extends ActionSupport {
    @Action("foo")
    public String foo() {
        return "bar";
    }

    @Action("foo-bar")
    public String bar() {
        return SUCCESS;
    }
}

此时,若未定义"foo-bar"的result,则convention尝试在同一个包下寻找action名为”foo-bar”的action。如果找到这样的action,
convention将会调用并返回相关联的result。
4、XWork packages
①为了避免冲突,可将action放在一个自定义XWORK的package下
②package命名由action所在的Java包,action对应的URL中namespace部分以及action的parent XWork package三个部分组成,即:

<java-package>#<namespace>#<parent-package>

③parent XWork package 值在属性 struts.convention.default.parent.package 中指定(默认为convention-default)

<constant name="struts.convention.default.parent.package" value="convention-default"/>

5、Annotation reference
Convention使用很多注解来重写默认插件的action到url的映射和result路径。同时,也可以通过修改parent XWork package
通过使用@Action注解,Convention plugin可以改变action映射的url,同时也可以使一个action对应多个url地址,例如:

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;

public class HelloWorld extends ActionSupport {
  @Action("/different/url")
  public String execute() {
    return SUCCESS;
  }
}

这时,action映射的url地址将是/different/url,如果没有定义@Result,则该namespace下的action路径将被当作result path,即WEB-
INF/content/different/url.jsp
通过@Actions注解,一个方法可以对应多个url路径,如:

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

public class HelloWorld extends ActionSupport {
  @Actions({
    @Action("/different/url"),
    @Action("/another/url")
  })
  public String execute() {
    return SUCCESS;
  }
}

另外一种使用@Action和@Actions的例子是在一个Action类中定义多个方法,使用不同的注解,对应不同的url,如:

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

public class HelloWorld extends ActionSupport {
  @Action("/different/url")
  public String execute() {
    return SUCCESS;

  }

  @Action("url")
  public String doSomething() {
    return SUCCESS;
  }
}

第二个方法中的相对路径注解不推荐使用,它的路径将取决与package对应的namespace而不是由Action注解决定
Interceptor和interceptor stacks同样可以使用注解,下面的例子使用了validation interceptor和defaultStack interceptor stack:

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

public class HelloWorld extends ActionSupport {
  @Action(interceptorRefs={@InterceptorRef("validation"), @InterceptorRef("defaultStack")})
  public String execute() {
    return SUCCESS;
  }

  @Action("url")
  public String doSomething() {
    return SUCCESS;
  }
}

InterceptorRefs可用于方法或Action类,若用于类上,则对所有方法有效

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

@InterceptorRefs({
    @InterceptorRef("interceptor-1"),
    @InterceptorRef("defaultStack")
})
public class HelloWorld extends ActionSupport {
  @Action(value="action1", [email protected]("validation"))
  public String execute() {
    return SUCCESS;
  }

  @Action(value="action2")
  public String doSomething() {
    return SUCCESS;
  }
}
注意:如果遇到"Unable to find interceptor class referenced by ref-name XYZ",则说明在convention扫描Action类时,没有Interceptor指定的拦截器。处理方式为:1使用@ParentPackage注解(或者指定struts.convention.default.parent.package)指定定义了该Interceptor的package;2创建一个package并继承定义了该Interceptor的package,同时使用@ParentPackage(或者 struts.convention.default.parent.package)指定该package

同时也可以指定params参数,使用 {"key0", "value0, "key1", "value1" ... "keyN", "valueN"}形式

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

public class HelloWorld extends ActionSupport {
  @Action([email protected](value="validation",params={"programmatic", "false", "declarative", "true}))
  public String execute() {
    return SUCCESS;
  }

  @Action("url")
  public String doSomething() {
    return SUCCESS;
  }
}

若未指定interceptors,则使用default stack
如果将@Action,@Actions用于Action类,若该类中定义了execute,则该方法将用于action映射,否则应用的方法取决于请求
对于结果注解@Results可分为全局和局部,全局@Results定义在Action类,对所有方法有效,局部@Results定义在方法上,只对该方法有效

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

@Results({
  @Result(name="failure", location="fail.jsp")
})
public class HelloWorld extends ActionSupport {
  @Action(value="/different/url",
    results={@Result(name="success", location="http://struts.apache.org", type="redirect")}
  )
  public String execute() {
    return SUCCESS;
  }

  @Action("/another/url")

  public String doSomething() {
    return SUCCESS;
  }
}

在@Results注解中可以使用@params, {"key0", "value0, "key1", "value1" ... "keyN", "valueN"}

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

public class HelloWorld extends ActionSupport {
  @Action(value="/different/url",
    results={@Result(name="success", type="httpheader", params={"status", "500", "errorMessage", "Internal Error"})}
  )
  public String execute() {
    return SUCCESS;
  }

  @Action("/another/url")
  public String doSomething() {
    return SUCCESS;
  }
}

从2.1.7版本后,@Results可以被子类继承
对于@Namespace注解可应用于Action类和packages中,在类上使用时为非完全限定

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;

@Namespace("/custom")
public class HelloWorld extends ActionSupport {
  @Action("/different/url")
  public String execute() {
    return SUCCESS;
  }

  @Action("url")
  public String doSomething() {
    return SUCCESS;
  }
}

该Action类对应两个url: /different/url和/custom/url

@org.apache.struts2.convention.annotation.Namespace("/custom")
package com.example.actions;

应用于package时,子包不继承该namespace
对于@ResultPath允许改变默认的结果存放地址,该注解可用于Action类和package

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ResultPath;

@ResultPath("/WEB-INF/jsps")
public class HelloWorld extends ActionSupport {
  public String execute() {
    return SUCCESS;
  }
}

经过注解,该Action类对应的result地址为/WEB-INF/jsps,而不是默认的/WEB-INF/content
对于@ParentPackage允许应用为Action类或java package定义不同的parent Struts package,也可以通过struts.convention.default.parent.package指定

package com.example.actions;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;

@ParentPackage("customXWorkPackage")
public class HelloWorld extends ActionSupport {
  public String execute() {
    return SUCCESS;
  }
}

对于@ExceptionMappings可以指定Action类或方法的异常映射

@ExceptionMappings({
    @ExceptionMapping(exception = "java.lang.NullPointerException", result = "success", params = {"param1", "val1"})
})
public class ExceptionsActionLevelAction {

    public String execute() throws Exception {
        return null;
    }
}
public class ExceptionsMethodLevelAction {
    @Action(value = "exception1", exceptionMappings = {
            @ExceptionMapping(exception = "java.lang.NullPointerException", result = "success", params = {"param1", "val1"})
    })
    public String run1() throws Exception {
        return null;
    }
}

对于jar包,Convention plugin默认不会扫描其中的Action,若希望扫描,则需要配置struts.convention.action.includeJars

<constant name="struts.convention.action.includeJars" value=".*?/myjar1.*?jar(!/)?,.*?/myjar2*?jar(!/)?">

注意,此处正则表达式匹配的是jar的路径而不是文件名,该路径下应包含jar并以"!/"结尾
Convention plugin可以自动重载配置的修改,扫描Action的改动,若要启用该功能,需要配置

<constant name="struts.devMode" value="true"/>
<constant name="struts.convention.classes.reload" value="true" /> 

生产环境下,强烈建议不使用该功能
6、Tips
①确保action的namespace与locators中的一个匹配,在locators后面的包路径后面,将作为action的namespace,同时将用于定位results。例如对于位
于"my.example.actions.orders"路径下的ViewAction将对应映射‘/orders/view.action‘,并且结果必将位于/WEB-INF/content/orders,类似/WEB-
INF/content/orders/view-success.jsp
②使用Configuration Browser查看action映射
③打开跟踪或调试,如log4j中增加:log4j.logger.org.apache.struts2.convention=DEBUG
常见问题
①‘There is no Action mapped for namespace /orders and action name view.‘这意味着URL /orders/view.action为对应任何一个action类,检查namespace和该
名称的action
②‘No result defined for action my.example.actions.orders.ViewAction and result success‘这意味者action已成功映射到Url,但是Convention插件没有找到
success result,检查视图文件是否存在,类似/WEB-INF/content/orders/view-success.jsp
③‘java.lang.Exception: Could not load org/apache/velocity/runtime/resource/loader/ClasspathResourceLoader.class‘这发生在
struts.convention.action.includeJars匹配外部jar包时
④当使用自定义interceptor stack时,发生‘Unable to find interceptor class referenced by ref-name XYZ‘这意味着convention插件在解析actions时,没有继
承该Interceptor定义的那个package,解决方式有两种1)使用 @ParentPackage(或struts.convention.default.parent.package)指定定义了该拦截器的package;2)自
定义package并继承定义了该Interceptor的package,并使用@ParentPackage(或struts.convention.default.parent.package)指定
7、重写convention实现rent.package)指定

<bean type="org.apache.struts2.convention.ActionNameBuilder" name="MyActionNameBuilder" class="example.SultansOfSwingNameBuilder"/>
<constant name="struts.convention.actionNameBuilder" value="MyActionNameBuilder"/>

8、convention插件配置:

Name Default Value Description
struts.convention.action.alwaysMapExecute true Set to false, to prevent Convention from creating a default mapping to "execute" when there are other methods annotated as actions in the class
struts.convention.action.includeJars   Comma separated list of regular expressions of jar URLs to be scanned. eg. ".*myJar-0\.2.*,.*thirdparty-0\.1.*"
struts.convention.action.packages   An optional list of action packages that this should create configuration for (they don‘t need to match a locator pattern)
struts.convention.result.path /WEB-INF/content/ Directory where templates are located
struts.convention.result.flatLayout true If set to false, the result can be put in its own directory: resultsRoot/namespace/actionName/result.extension
struts.convention.action.suffix Action Suffix used to find actions based on class names
struts.convention.action.disableScanning false Scan packages for actions
struts.convention.action.mapAllMatches false Create action mappings, even if no @Action is found
struts.convention.action.checkImplementsAction true Check if an action implements com.opensymphony.xwork2.Action to create an action mapping
struts.convention.default.parent.package convention-default Default parent package for action mappins
struts.convention.action.name.lowercase true Convert action name to lowercase
struts.convention.action.name.separator - Separator used to build the action name, MyAction -> my-action. This character is also used as the separator between the action name and the result in templates, like action-result.jsp
struts.convention.package.locators action,actions,struts,struts2 Packages whose name end with one of these strings will be scanned for actions
struts.convention.package.locators.disable false Disable the scanning of packages based on package locators
struts.convention.exclude.packages org.apache.struts.*,
org.apache.struts2.*,
org.springframework.web.struts.*,
org.springframework.web.struts2.*,
org.hibernate.*
Packages excluded from the action scanning
struts.convention.package.locators.basePackage   If set, only packages that start with its value will be scanned for actions
struts.convention.relative.result.types dispatcher,velocity,freemarker The list of result types that can have
locations that are relative and the result location (which is the
resultPath plus the namespace) prepended to them
struts.convention.redirect.to.slash true A boolean parameter that controls whether or
not this will handle unknown actions in the same manner as Apache,
Tomcat and other web servers. This handling will send back a redirect
for URLs such as /foo to /foo/ if there doesn‘t exist an action that
responds to /foo
struts.convention.classLoader.excludeParent true Exclude URLs found by the parent class loader from the list of URLs scanned to find actions (needs to be set to false for JBoss 5)
struts.convention.action.eagerLoading false If set, found action classes will be
instantiated by the ObjectFactory to accelerate future use, setting it
up can clash with Spring managed beans
时间: 2024-11-05 12:23:15

Struts2 - Conversion Plugin的相关文章

Struts2 Convention Plugin ( struts2 零配置 )

Struts2 Convention Plugin ( struts2 零配置 ) convention-plugin 可以用来实现 struts2 的零配置.零配置的意思并不是说没有配置,而是通过约定大于配置的方式,大量通过约定来调度页面的跳转而使得配置大大减少.考虑到某种因素,这里采用 myeclipse 作为示例 IDE,环境 : JDK 1.6 myeclipse 8.6.1 struts 2.1.8 web.xml <filter>       <filter-name>

记录struts2 json plugin 对字符串数组类型的处理

当前项目中,一开发人员在action中定义了一个字符串数组类型的属性,需要以json格式返回到页面(先不论这种设计是否最优), 结果在做页面调试时发现总是无法在ajax的success方法中获取到该属性.后台action调试发现该数组已经正确赋值,get 方法也没有问题,action相关代码如下: private String[] traceList; private String unitName; ... public String queryTrace(){ unitName = "tes

基于struts2的ajaxfileupload异步上传插件的使用

实例: jsp页面 <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E

JSON查看小工具

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等).这些特性使JSON

JQUERY插件JqueryAjaxFileUplaoder----更简单的异步文件上传

异步上传相信大家都做过类似的功能,JqueryAjaxFileUploader为我们提供了更简单的实现和使用方式.不过既然是JQUERY的插件那么它所依赖的环境大家都懂得.JqueryAjaxFileUploader并不华丽,也没有提供美化文件上传控件的css,它并不像jQuery File Upload(喜欢的同学可以去尝试下),提供了美观的样式和专门的图片预览.多任务上传等等, JqueryAjaxFileUploader 所拥有的很简单,只是异步上传文件的功能,当然这并不排除由你亲自为它披

jquery之ajaxfileupload异步上传插件

来自:http://www.blogjava.net/sxyx2008/archive/2010/11/02/336826.html 由于项目需求,在处理文件上传时需要使用到文件的异步上传.这里使用Jquery Ajax File Uploader这个组件下载地址:http://www.phpletter.com/download_project_version.php?version_id=6服务器端采用struts2来处理文件上传.所需环境:jquery.jsajaxfileupload.j

程序员开发书籍汇总

文件类型 文件名称 更新时间 pdf 浅谈ACEGI配制 .pdf 2015/10/9 pdf AJAX In Action.pdf 2015/10/9 pdf Ajax.pdf 2015/10/9 txt AjaxHttpRequest.txt 2015/10/9 pdf AJAXInAction.pdf 2015/10/9 pdf Ajax经典案例开发大全.pdf 2015/10/9 pdf AJAX开发简略(含续一).pdf 2015/10/9 pdf AJAX开发简略.pdf 2015/

SSH 架构

这几天学习了 ssh 架构,中间出了好多错误,现在终于整理好了,就记录下来 ssh机构的框架构成,以及它们的作用 struts2 :这个框架主要用做控制处理的,其核心是 Contraller ,即 ActionServlet.而 ActionServlet 的核心是 struts.xml.用于分配处理web请求需要执行哪个业务逻辑. spring :spring 可以理解为粘合剂的作用.它把这三个框架糅合在一起使用.利用本身的控制反转(IOC) 来达到解耦的目的. Hibernate:及时数据持

maven(一) maven到底是个啥玩意~

我记得在搞懂maven之前看了几次重复的maven的教学视频.不知道是自己悟性太低还是怎么滴,就是搞不清楚,现在弄清楚了,基本上入门了.写该篇博文,就是为了帮助那些和我一样对于maven迷迷糊糊的人.有福了,看完基本上你就会发现原来这么简单. 参考博文:通俗理解maven 该篇文章篇幅很长,大概的思路如下 maven的介绍,初步认识,获取jar包的三个关键属性 --> 介绍仓库(获取的jar包从何而来)-->用命令行管理maven项目(创建maven项目) --> 用myeclipse创