Struts2拦截器简单示例

拦截器(Interceptor)是Struts 2的核心组成部分。很多功能(Feature)都是构建在拦截器基础之上的,服务器空间,例如文件的上传和下载、国际化、转换器和数据校验等,Struts 2利用内建的拦截器,完成了框架内的大部分操作。

在Struts 2文档中对拦截器的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制,使开发者可以定义一个特定的功能模块,这个模块可以在Action执行之前或者之后运行,也可以在一个Action执行之前阻止Action执行。同时也提供了一种可以提取Action中可重用的部分的方式

拦截器在Struts2中的示意图:

),最后一个一个地调用列表中的拦截器

拦截器时序图如下图所示:

,香港服务器租用,在用户看来,香港服务器租用,好像没有配置拦截器。

Hello World拦截器示例.

程序要演示的是显示地让拦截器调用Action,来体会拦截器的用途。

一般情况下我们都会先写出一个Action,然后配置struts.xml文件

MyAction.java

public class MyAction extends ActionSupport { //以下属性信息都是从前台(JSP页面获得) private String username; private String mymsg; private String password1; private String password2; private Date birthday; public String execute(){ if(username!=null&&this.getPassword1().equals(this.getPassword2())&&!this.getUsername().trim().equals(“”)){ //输出调试信息 System.out.println(“Action信息,正在执行Action….”); return SUCCESS; }else{ return INPUT; } } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMymsg() { return mymsg; } public void setMymsg(String mymsg) { this.mymsg = mymsg; } public String getPassword1() { return password1; } public void setPassword1(String password1) { this.password1 = password1; } public String getPassword2() { return password2; } public void setPassword2(String password2) { this.password2 = password2; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }

自定义拦截器MyInterceptor.java

public class MyInterceptor extends AbstractInterceptor { //拦截方法 public String intercept(ActionInvocation invocation) throws Exception { MyAction myA=(MyAction) invocation.getAction(); System.out.println(“拦截器信息:hello world 拦截器”); //执行action或者下一个拦截器 String result=invocation.invoke(); System.out.println(“拦截器信息:Action执行完毕”); return result; } }

下面我们开始配置struts.xml文件

任何的限制,都是从自己的内心开始的。

Struts2拦截器简单示例

相关文章:

你感兴趣的文章:

标签云: