码迷,mamicode.com
首页 > 其他好文 > 详细

Struts2 Interceptors

时间:2015-04-01 23:19:58      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

Alias Interceptor : 别名拦截器

<action name="someAction" class="com.examples.SomeAction">
    <!-- The value for the foo parameter will be applied as if it were named bar -->
<!-- 这是这个拦截器唯一的参数,也是唯一的格式要求 --> <param name="aliases">#{ ‘foo‘ : ‘bar‘ }</param>
<!-- 完全不必这么写,因为默认的defaultStack中已经包含了alias拦截器了 --> <interceptor-ref name="alias"/> <interceptor-ref name="basicStack"/> <result name="success">good_result.ftl</result> </action>

别名拦截器的作用是什么呢?下面的例子是目前我能想到的。。。

    <action name="LoginAction" class="struts2.study.action.LoginAction">
      <result name="dispatcher" type="dispatcher">
        /WEB-INF/view/Users.jsp
      </result>
      <result name="redirectAction3" type="redirectAction">
        <param name="actionName">CreateTableAction</param>
        <param name="rows">5</param>
        <param name="colums">10</param>
      </result>
    </action>

    <action name="CreateTableAction" class="struts2.study.action.CreateTableAction">
      <param name="aliases">#{"rows" : "rowsX", "colums" : "columsX"}</param>
      <result>/WEB-INF/view/Table.jsp</result>
    </action>

 

 Chaining Interceptor :拦截器链

<action name="someAction" class="com.examples.SomeAction">
    <interceptor-ref name="basicStack"/>
    <result name="success" type="chain">otherAction</result>
</action>
 
<action name="otherAction" class="com.examples.OtherAction">
    <interceptor-ref name="chain"/>
    <interceptor-ref name="basicStack"/>
    <result name="success">good_result.ftl</result>
</action>

感觉他是redirectAction这种result的基础,用来在action之间进行传递。

 

Checkbox Interceptor : checkbook拦截器

<s:checkbox/>会被render成一个checkbox,同时还会出现一个类似于如下所示的hidden的项目。

<input type="checkbox" name="good" value="true" id="CheckBoxAction2_good">
<
input type="hidden" id="__checkbox_CheckBoxAction2_good" name="__checkbox_good" value="true">
<label for="CheckBoxAction2_good" class="checkboxLabel">Good Enough?</label>

而这个hidden项目会被该拦截器拦截,并且给对应的property(__checkbox_)之后的good设定该有的值。

不然的话,可能action侧接受不到这个值,尤其是没有选择的时候。

所以这个拦截器给他设定一个值:

private String uncheckedValue = Boolean.FALSE.toString();

可见这个值也是可以定制的,但是一般情况下没有必要。。。

 

Conversion Error Interceptor : 转换错误拦截器

一般应该也不会触及,但是原因需要了解一下。

假如一个Integer类型的变量,在页面上输入的值是abc,这个时候肯定会出错。那么出错之后,这个变量的值应该显示为什么呢?如果显示为Integer的默认值0的话,就显得没有意义了,而是应该把abc显示给用户。

This is important because if the value "abc" is submitted and can‘t be converted to an int, we want to display the original string ("abc") again rather than the int value (likely 0, which would make very little sense to the user).

 

Create Session Interceptor :创建session拦截器

Session用来保存好多东西,但是如果当前session是空的话,该拦截器就会创建一个新的session。

 

Exception Interceptor :异常拦截器

在Action中如果出现了异常,那么这个拦截器就会起作用。

他会在struts.xml中遍历所有的exception-mapping,然后找到匹配的mapping信息,这个mapping信息的result可以用来对应action的result的name的值。

    <global-exception-mappings>
      <exception-mapping result="NullPointer" exception="java.lang.NullPointerException" />
      <exception-mapping result="IndexOutOfBounds" exception="java.lang.IndexOutOfBoundsException" />
    </global-exception-mappings>


    <action name="ExceptionAction_*" class="struts2.study.action.ExceptionAction" method="{1}">
      <result>/WEB-INF/view/Exception.jsp</result>
      <result name="NullPointer">/WEB-INF/view/NullPointerException.jsp</result>
      <result name="IndexOutOfBounds">/WEB-INF/view/IndexOutOfBoundsException.jsp</result>
    </action>

 

File Upload Interceptor : 文件上传拦截器

文件上传依赖于如下的jar包

 

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

 

 

 

这个拦截器会拦截form中的所有的file类型的输入类型(input或者s:file)。

假如input或者s:file的name的值为upload的话,action中需要包含如下内容:

// 这个变量任意x
private File anything;
// 这个为文件的名称,需要设定为xFileName
private String anythingFileName;
// 这个为文件的类型,需要设定为xContentType
private Stirng anythingContentType;

public void setUpload(File anything) {
    this.anything = anything;
}

public void setUploadFileName(String anythingFileName) {
    this.anythingFileName = anythingFileName;
}

public void setUploadContentType (String anythingContentType) {
    this.anythingContentType = anythingContentType;
}

 

其实这样一来就可以完成文件的上传了,只不过我们没有对上传的文件进行处理而已。

        // 在tomcat的项目路径下开辟一个名称为images的文件夹
     String realpath = ServletActionContext.getServletContext().getRealPath("/images"); if (image != null) {
// 创建该文件的副本,路径,名称 File savefile
= new File(new File(realpath), imageFileName);
// 查看是否存在images文件夹,不存在的话创建该文件夹
if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs(); // 把file对象拷贝到文件的副本处 FileUtils.copyFile(image, savefile); }

 

还可以多文件上传

jsp

  <s:form action="MultiFileUploadAction" enctype="multipart/form-data" method="post" namespace="/">
    <input type="file" multiple="multiple" name="multifile" />
    <s:submit />
  </s:form>
  <s:form action="MultiFileUploadAction" enctype="multipart/form-data" method="post" namespace="/">
    <input type="file" name="multifile" />
    <input type="file" name="multifile" />
    <input type="file" name="multifile" />
    <s:submit />
  </s:form>

java

基于List形式的:

    // 上传的文件
    private List<File> images = new ArrayList<File>();
    // 文件名称
    private List<String> imageFileNames = new ArrayList<String>();
    // 文件类型
    private List<String> imageContentTypes = new ArrayList<String>();

    public String execute() throws Exception {
        for (File image : images) {
            System.out.println(image.length());
        }
        for (String imageFileName : imageFileNames) {
            System.out.println(imageFileName);
        }
        for (String imageContentType : imageContentTypes) {
            System.out.println(imageContentType);
        }
        return "success";
    }

    public void setMultifile(List<File> image) {
        this.images = image;
    }

    public void setMultifileFileName(List<String> imageFileName) {
        this.imageFileNames = imageFileName;
    }

    public void setMultifileContentType(List<String> imageContentType) {
        this.imageContentTypes = imageContentType;
    }

基于数组形式的:

    // 上传的文件
    private File[] images;
    // 文件名称
    private String[] imageFileNames;
    // 文件类型
    private String[] imageContentTypes;

    public String execute() throws Exception {

        for (File image : images) {
            System.out.println(image.length());
        }

        for (String imageFileName : imageFileNames) {
            System.out.println(imageFileName);
        }

        for (String imageContentType : imageContentTypes) {
            System.out.println(imageContentType);
        }

        return "success";
    }

    public void setMultifile(File[] image) {
        this.images = image;
    }

    public void setMultifileFileName(String[] imageFileName) {
        this.imageFileNames = imageFileName;
    }

    public void setMultifileContentType(String[] imageContentType) {
        this.imageContentTypes = imageContentType;
    }

 

参数的设定:

<struts>
<
constant name="struts.multipart.maxSize" value="1000000" /> <constant name="struts.multipart.saveDir" value="D:/tmp" /> <action >
<interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/gif</param> </interceptor-ref>
</action>
<action > <interceptor-ref name="fileUpload"> <param name="maximumSize">500000</param> </interceptor-ref> </action>
<action> <interceptor-ref name="fileUpload"> <param name="allowedTypes">text/plain</param> </interceptor-ref>
</action>
</struts>

 

I18n Interceptor : 国际化拦截器

java.util.ResourceBundle,java提供的能够用来从properties文件中读取key-value对的类。

        ResourceBundle chineseMessage = ResourceBundle.getBundle("message", Locale.CHINESE);
        ResourceBundle chinaMessage = ResourceBundle.getBundle("message", Locale.CHINA);
        ResourceBundle usMessage = ResourceBundle.getBundle("message", Locale.US);

     usMessage.getString("hello");

 

ResourceBundle.getBundle("message", Locale.CHINESE)

第二个参数,用来指定国际化的国家,常用的:

US : Locale.US, _en_US

CHINA : Locale.CHINA, _zh_CN

JAPAN : Locale.JAPAN, _ja_JP

 

以上为背景,struts给我们提供了方便的国际化支持。

 

struts.xml

  <!-- i18n -->
  <constant name="struts.custom.i18n.resources" value="resource" />
  <constant name="struts.i18n.encoding" value="UTF-8" />

jsp

  Message From Properties :
  <s:text name="label" />
  <hr />
  <a href="I18NAction?request_locale=zh_CN">简体中文</a>
  <br />
  <a href="I18NAction?request_locale=en_US">English</a>

java

    public String execute() throws Exception {
        Locale locale = Locale.getDefault();
        ActionContext.getContext().getSession().put("WW-TRANS-I18N-LOCALE", locale);
        return SUCCESS;
    }

java中获取properties信息

getText("label");
getText("fromat", "test");

properties

label=LABEL
#这里可是从0开始数的啊.... fromat
=this is {0}

 

 

Token Interceptor/Token Session Interceptor : 令牌session拦截器

这是一个用来防止二次提交以及后退提交的拦截器。

大体是通过<s:token />在页面上生成一个令牌,然后session中存放另外一个值,这两个值应该是相同的。

而二次提交的时候,这两个值就不相同了,然后抛出一个错误信息。

 

实现方式:

1 jsp中的<s:form>中需要有<s:token />

2 struts.xml中需要给package追加拦截器链或者给action追加拦截器链。这个地方是必须的,因为默认的defaultStack拦截器链中没有包含这两个拦截器。

3 action中需要配置一个<result name="invalid.token">some...</result>

 

 

http://struts.apache.org/docs/interceptors.html

 

Struts2 Interceptors

标签:

原文地址:http://www.cnblogs.com/voctrals/p/4374835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!