您的位置:首页 > 编程语言 > Java开发

Struts2 转换器 和 拦截器

2016-03-31 23:50 330 查看


Struts2 转换器 和 拦截器

一.类型转换器

Struts 使用大量的类型转换器.例如在Action中存在一个 Integer属性,Struts自动将对应的请求参数转换成Integer属性,而不需要你做任何事情

下面列出部分类型

Integer, Float, Double, Decimal

Date and Datetime

Arrays and Collections

Enumerations

Boolean

BigDecimal

有时候我们需要使用自己的数据类型,这是必须添加自己的转换器来让Struts进行转换.Struts提供了多种接口来自定义类型转换 常用的有两种方式可以实现类型转换,第一种是继承自DefaultTypeConverter,一种是继承自StrutsTypeConverter

第二种方式是对第一种方式的封装,所以使用起来更加简明.下面贴出一个网上的例子:

有这样的一个自定义数据类型Environment

public class Environment {
private String name;
public  Environment(String name)
{
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

对应的转换器:

import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;

public class EnvironmentConverter extends StrutsTypeConverter {
@Override
public Object convertFromString(Map context, String[] values, Class clazz) {
Environment env = new Environment(values[0]);
return env;
}

@Override
public String convertToString(Map context, Object value) {
Environment env  = (Environment) value;
return env == null ? null : env.getName();
}
}

定义好转换器后,接下来将定义好的转换器注册到应用中.同样,有两种方式注册一个转换器.

a.如果转换器只是用于一个特殊的 action,这样创建一个命名为'[action-class]'-converstion.properties属性文件,放置在和action同一目录下.并且在文件中添加

environment=com.tutorialspoint.struts2.EnvironmentConverter,其中environment必须和action中对应的自定义属性名、页面表单属性名一致

b.同样,可以定义一个全局的转换器供整个应用使用.创建一个名为xwork-conversion.properties属性文件, in theWEB-INF/classes文件夹下,内容为:com.tutorialspoint.struts2.Environment
= com.tutorialspoint.struts2.EnvironmentConverter

二、拦截器

拦截器与 struts过滤器、JDK代理同等概念的,通过切面机制 来实现 Action和框架的耦合。和转换器一样,Struts也提供了大量的内置拦截器:

SNInterceptor & Description
1alias

Allows parameters to have different name aliases across requests.
2checkbox

Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked.
3conversionError

Places error information from converting strings to parameter types into the action's field errors.
4createSession

Automatically creates an HTTP session if one does not already exist.
5debugging

Provides several different debugging screens to the developer.
6execAndWait

Sends the user to an intermediary waiting page while the action executes in the background.
7exception

Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection.
8fileUpload

Facilitates easy file uploading.
9i18n

Keeps track of the selected locale during a user's session.
10logger

Provides simple logging by outputting the name of the action being executed.
11params

Sets the request parameters on the action.
12prepare

This is typically used to do pre-processing work, such as setup database connections.
13profile

Allows simple profiling information to be logged for actions.
14scope

Stores and retrieves the action's state in the session or application scope.
15ServletConfig

Provides the action with access to various servlet-based information.
16timer

Provides simple profiling information in the form of how long the action takes to execute.
17token

Checks the action for a valid token to prevent duplicate formsubmission.
18validation

Provides validation support for actions
具体详细内容,可以查阅Stuts2文档。

使用上面的两个内置拦截器timer 和 params,举例说明如何使用拦截器,只要简单的在struts.xml配置文件中配置:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

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

<package name="helloworld" extends="struts-default">

<action name="hello"

class="com.tutorialspoint.struts2.HelloWorldAction"

method="execute">

<interceptor-ref name="params"/>

<interceptor-ref name="timer" />

<result name="success">/HelloWorld.jsp</result>

</action>

</package>

</struts>

当然也可以自己根据业务需求写自己的拦截器,进行一些逻辑处理,为了简洁 实现一个拦截器,通常我们实现AbstractInterceptor抽象类如:

public class MyInterceptor extends AbstractInterceptor {

public String intercept(ActionInvocation invocation)throws Exception{

/* let us do some pre-processing */

String output = "Pre-Processing";

System.out.println(output);

/* let us call action or next interceptor */

String result = invocation.invoke();

/* let us do some post-processing */

output = "Post-Processing";

System.out.println(output);

return result;

}

}框架自身通过第一次调用ActionInvocation对象的invoke方法开始处理后,每次invoke方法被调用,ActionInvocation记录他的状态

并且执行接下来拦截器。当所有配置的拦截器被调用后来,aciton本身被执行。下面图标展示这个过程:



可以想象,为每个action,配置多个拦截器,将很快变得不可控,为此,可以通过Interceptor-Stack进行管理。例子:

<interceptor-stack name="basicStack">

<interceptor-ref name="exception"/>

<interceptor-ref name="servlet-config"/>

<interceptor-ref name="prepare"/>

<interceptor-ref name="checkbox"/>

<interceptor-ref name="params"/>

<interceptor-ref name="conversionError"/>

</interceptor-stack>该配置放置在<package>节点下面,每一个<interceptor-ref>节点引用一个定义好的拦截器或者interceptor-stack.

特别注意:

struts-default.xml中定义了一系列的拦截器和拦截器链同时也定义了一个默认的拦截器defaultStack,一旦定义了默认的拦截器,该拦截器就会对包中的所有的Action起作用,当然如果你的Action中显式地定义了拦截器,默认拦截器就会失去作用,如果想不让他失去作用,也必须显式地定义系统默认的拦截器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: