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的更多相关文章

  1. 菜鸟学Struts2——Interceptors

    昨天学习Struts2的Convention plugin,今天利用Convention plugin进行Interceptor学习,虽然是使用Convention plugin进行零配置开发,这只是 ...

  2. struts2笔记(3)

    关于回显: 如果是int型,默认就会回显为0,如果不想让回显,则Integer就好 //**************************************声明式验证************* ...

  3. struts2 基本用法

    Struts2必需库: commons-fileupload.jar.commons-io-1.3.2.jar.freemarker-2.3.16.jar.javassist-3.7.ga.jar.o ...

  4. struts2 文件的上传下载 表单的重复提交 自定义拦截器

    文件上传中表单的准备 要想使用 HTML 表单上传一个或多个文件 须把 HTML 表单的 enctype 属性设置为 multipart/form-data 须把 HTML 表单的method 属性设 ...

  5. Struts2初学习记录

    以下笔记内容来自尚硅谷_Struts2_佟刚老师的视频教程+自己一点点整理 来源免责声明 一. 1. VS 自实现: 1). 搭建 Struts2 的开发环境 2). 不需要显式的定义 Filter, ...

  6. JavaEE高级-Struts2学习笔记

    Struts2是一个用来来发MVC应用的框架,它提供了Web应用程序开发过程中一些常见问题的解决方案: - 对来自用户的输入数据进行合法的验证 - 统一的布局 - 可扩展性. - 国际化和本地化 - ...

  7. Struts自定义拦截器&拦截器工作原理

    0.拦截器的调用原理: 拦截器是一个继承了序列化接口的普通接口.其工作原理是讲需要被拦截的对象作为参数传到intercept()方法内,在方法内部对此对象进行处理之后再执行原方法.intercept( ...

  8. 基于struts2--实现文件上传下载

    1. 文件的上传: 1). 表单需要注意的 3 点 ①. method="post"     ②. enctype="mulitipart/form-data" ...

  9. struts学习笔记(四)

    一. 文件的上传: 1). 表单需要注意的 3 点 2). Struts2 的文件上传实际上使用的是 Commons FileUpload 组件, 所以需要导入 commons-fileupload- ...

随机推荐

  1. Sonar + Jacoco,强悍的UT, IT 双覆盖率统计(转)

    以前做统计代码测试覆盖,一般用Cobertura.以前统计测试覆盖率,一般只算Unit Test,或者闭上眼睛把Unit Test和Integration Test一起算. 但是,我们已经过了迷信UT ...

  2. mac自带apache服务器开启

    mac的os x操作系统自带的有apach服务器, 命令行:   sudo apachectl -v 可查看自带apache版本信息 输入: sudo apachectl start  就开启了apa ...

  3. R 学习1

    首先安装吧 http://cran.rstudio.com/bin/windows/base/R-3.2.1-win.exe 里面既有32位又有64. R有很多包,如果有的包本地没有,来这里搜 htt ...

  4. Apache搭建多个站点方法详解

    www.111cn.net 编辑:Bolshevik 来源:转载 Apache的虚拟主机是一种允许在同一台机器上配置多个不同站点的web服务器环境的,就是iis一样可以创建多站点了,但是apache需 ...

  5. 319. Bulb Switche

    There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every ...

  6. 38. Count and Say

    The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221 ...

  7. C特殊浮点值NaN

    特殊浮点值NaN(Not-a-Number),例如asin()函数返回反正弦值,所以输入参数不能大于1,否则函数返回NaN值,printf()显示为nan,NaN或类似形式.

  8. c 函数及指针学习 8

    联合体 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <stdio.h>   union sa     {     double a;     int b; ...

  9. resin的基本操作

    1.什么是resin?     resin是CAUCHO公司的产品,是一个非常流行的支持servlets和jsp的引擎,速度非常快.Resin本身包含了一个支持HTTP/1.1的WEB服务器.虽然它可 ...

  10. hihoCoder挑战赛23

    hihoCoder挑战赛23 A.Emulator 题意 给一张图,有\(N(N \le 300)\)个点, 给出任意两点之间的最短路. 求最多可以去掉多少条边,使得任意两点的最短路长度不变. 思路 ...