Struts 2学习笔记——拦截器相关

 

一、添加国际化支持

默认的struts-deault.xml文件中已经定义了国际化拦截器,内容如下

<!—定义国际化拦截器-->
<interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>

该拦截器会在Action执行前执行,默认情况下,会读取用户请求中的request_locale参数,并将参数值存入session(key=WW_TRANS_I18N_LOCALE)

通过改变拦截器的两个参数,可以改变默认值(parameterName:request_locale,attributeName:WW_TRANS_I18N_LOCALE)

使用国际化拦截器的方法如下:

1、配置struts.custom.i18n.resources常量,可以在struts.properties文件中做以下配置(globalMessages是起的一个名字)

#在属性文件中定义BaseName
struts.custom.i18n.resources=globalMessages

2、按照basename_language_country.properties的命名规则添加资源文件

下面添加两个资源文件,汉语(中国)globalMessages_zh_CN.properties

result=\u7ED3\u679C
英语(美国)globalMessages_en_US.properties
result=Result

3、引用方式

继承了ActionSupport的Action文件中

System.out.println(getText("result"));

JSP文件中

<s:text key="result"/>

4、补充

除了可以在struts.properties中配置struts.custom.i18n.resources常量,还可以在struts.xml文件中配置

<!-- I18N资源文件为globalMessages -->
<constant name="struts.custom.i18n.resources"   value="globalMessages" />

或者在web.xml文件中配置

<!--定义struts.custom.i18n.resources常量-->
<init-param>
     <param-name>struts.custom.i18n.resources</param-name>
     <param-value>globalMessages</param-value>
</init-param>

 

二、对Action做粗略的性能评估

在struts.xml配置文件的<action></action>之间,加入

<interceptor-ref name="timer"></interceptor-ref>

在默认情况下,所有的Action都会调用默认的拦截器栈——defaultStack,使用上面的interceptor-ref可以覆盖默认的拦截器或拦截器栈,

指定的Action将会调用这里指定的拦截器timer,这个拦截器由内置的struts-default.xml文件定义。

这时再访问该Action,进行了两次访问,控制台输出了下面的结果

2012-1-17 12:35:59 com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
信息: Executed action [//i18n!execute] took 234 ms.
2012-1-17 12:36:08 com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
信息: Executed action [//i18n!execute] took 109 ms.

首次运行时,timer拦截器要进行一些初始化工作,第一次的时间是不准确的。通过后面的时间,可以进行一些粗略的性能评估。

 

三、自定义拦截器

1、创建拦截器类,Struts 2 的拦截器是一个实现了com.opensymphony.xwork2.interceptor.Interceptor接口的类,

也可以通过继承com.opensymphony.xwork2.interceptor.AbstractInterceptor来间接实现

2、实现或覆盖父类的intercept方法,实现拦截器的处理逻辑。

在intercept方法中,可以通过ActionContext.getContext()的静态方法中取得JavaServlet相关的对象,例如取得Session可以

ActionContext.getContext().getSession()

在intercept方法中,可以调用参数中ActionInvocation对象的invoke调用action继续处理用户请求,也可以用return直接返回一个逻辑视图(不再执行action)

3、注册到配置文件


在struts.xml文件中添加新建的拦截器信息,在<package></package>之间添加

<interceptors>
     <interceptor name="" class=""></interceptor>
</interceptors>

其中name是为自定义拦截器起得名字,class是添加的类的路径

 

4、使用自定义拦截器

同(二、对Action做粗略的性能评估),在<action></action>之间加入interceptor-ref标签

posted @ 2012-01-17 14:48  石莹  阅读(1837)  评论(0编辑  收藏  举报