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

Struts2 拦截器机制

2016-12-14 15:44 204 查看

什么是拦截器?

Struts拦截器类似于过滤器,在请求到达action之前进行一系列预处理,结束action之后反向调用一系列拦截器。

如何使用拦截器?

<?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>

<package name="publish" namespace="/publish" extends="struts-default">
<interceptors>
<!-- 定义拦截器 -->
<interceptor name="dirtyinter" class="king.zyt.interceptor.PublisInterceptor"></interceptor>
</interceptors>

<action name="publish" class="king.zyt.controller.PublisAction" method="publish">
<!-- 配置该action要穿过的拦截器 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="dirtyinter"></interceptor-ref>
<result name="success">/show.jsp</result>
</action>
</package>

</struts>


敲黑板

一个action写一个配置文件里 然后Struts.xml去调用具体的Struts-xxx.xml。都写一个里太乱

酱紫

struts.xml

<include file="struts-publish.xml"></include>
<include file="struts-user.xml"></include>
<include file="struts-tags.xml"></include>
<include file="struts-books.xml"></include>
<include file="struts-upload.xml"></include>


如何自定义拦截器

三种实现方式

实现Interceptor接口

继承AbstractInterceptor类,此类实现了Interceptor接口,空实现的init()和destroy()方法

继承MethodFilterInterceptor,可实现针对方法的过滤拦截

写一个发表评论的页面,当发表成功后,显示他刚发表的言论。要求:发表言论中带有不适当的言论,变成*

(打游戏骂人怎么把你屏蔽的,嗯哼~)

一般继承abstractInterceptor

1 先写一个interceptor。(定义个拦截器包,别往controller层放了)

package king.zyt.interceptor;

import king.zyt.controller.PublisAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PublisInterceptor extends AbstractInterceptor {

@Override
public String intercept(ActionInvocation invocation) throws Exception {
Object object = invocation.getAction();
if (object instanceof PublisAction) {
PublisAction publisAction = (PublisAction) object;
String content = publisAction.getContent();
publisAction.setContent(content.replaceAll("你大爷", "***"));
}
return invocation.invoke();
}

}


定义一个表单提交页面default.jsp

<form action="publish/publish" method="post">
评论<input type="text" name="content"><br>
<input type="submit" value="提交">
</form>


开发publishAction

package king.zyt.controller;

import com.opensymphony.xwork2.ActionSupport;

/**
*
* @author Oracle
*  拦截器action
*/
public class PublisAction {
private String content;

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String publish(){

return SUCCESS;
}

}


action此刻就是跳转用的,把一个页面的填写的值传到另一个页面,此处是用的值栈(下一篇说),

所以publish()方法里没实现,显示页面是这样的

<body>
<h2>提交的评论是:${content }</h2>
</body>


别忘了在配置里配置啊!!!

特别强调

上一篇文章里我说action里向后台传数据,可以写私有属性或者实体对象!但是一定要写get set 方法!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2.0 拦截器