Struts2自定义拦截器实例
摘自:《Struts 2.0从入门到精通》 崔群法 王咏梅 李有军 编著
此拦截器作用:过滤网站评论中不良字符串。
一、评论页面news.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<form id="form1" name="form1" action="public.action" method="post">
<table width="70%" border="0" align="center">
<tr>
<td>标题:<input type="text" name="title" /></td>
</tr>
<tr>
<td>评论内容</td>
</tr>
<tr>
<td><textarea name="content" cols="40" rows="5"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="提交"></td>
</tr>
</table>
</form>
二、ACTION:DefaultAction.java
package tmq.action;
import com.opensymphony.xwork2.ActionSupport;
public class DefaultAction extends ActionSupport{
private String title;
private String content;
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
public void setContent(String content){
this.content=content;
}
public String getContent(){
return content;
}
public String execute(){
return this.SUCCESS;
}
}
三、拦截器:LoginInterceptor.java
package tmq.interceptor;
import tmq.action.*;
import java.util.Map;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation ai)throws Exception{
Object o=ai.getAction();
if(o!=null){
if(o instanceof DefaultAction){
DefaultAction action=(DefaultAction)o;
String content=action.getContent();
if(content.contains("TMD")){
content=content.replaceAll("TMD","***");
action.setContent(content);
}
return ai.invoke();
}
return Action.LOGIN;
}else{
return Action.LOGIN;
}
}
}
四、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>
<package name="testInterceptor" extends="struts-default">
<interceptors>
<interceptor name="replace" class="tmq.interceptor.LoginInterceptor" />
</interceptors>
<action name="public" class="tmq.action.DefaultAction">
<result name="success">/success.jsp</result>
<result name="login">/login.jsp</result>
<interceptor-ref name="defaultStack" />
<interceptor-ref name="replace" />
</action>
</package>
</struts>
五、success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
标题:<s:property value="title" /> <br>
评论内容:<s:property value="content" />
六、运行:
在浏览器中运行news.jsp文件打开评论页面,提交后通过web.xml中的FilterDispatcher核心控制器
、struts.xml中自定义的拦截器及struts默认拦截器、ACTION、success.jsp,在success.jsp页面中
显示拦截器所拦截的信息,从而输出我们想要的信息。
struts2拦截器
最新推荐文章于 2023-04-30 00:38:07 发布