JavaWeb_(Struts2框架)拦截器interceptor
此系列博文基于同一个项目已上传至github 传送门
JavaWeb_(Struts2框架)Struts创建Action的三种方式 传送门
JavaWeb_(Struts2框架)struts.xml核心配置、动态方法调用、结果集的处理 传送门
JavaWeb_(Struts2框架)Log4j的配置以及解决中文乱码 传送门
JavaWeb_(Struts2框架)参数传递之接收参数与传递参数 传送门
JavaWeb_(Struts2框架)Ognl小案例查询帖子 传送门
JavaWeb_(Struts2框架)Action中struts-default下result的各种转发类型 传送门
JavaWeb_(Struts2框架)拦截器interceptor 传送门
创建拦截器的两种方式
第一种:继承MethodFilterInterceptor父类【推荐】
package com.Gary.web.intercept; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; //第一种创建拦截器的方式 public class MyIntercept extends MethodFilterInterceptor{ @Override protected String doIntercept(ActionInvocation invocation) throws Exception { //放行 return invocation.invoke(); } }
第二种:实现Interceptor接口
package com.Gary.web.intercept; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; //第二种创建拦截器的方法 public class Intercept implements Interceptor{ @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init() { // TODO Auto-generated method stub } @Override public String intercept(ActionInvocation invocation) throws Exception { // TODO Auto-generated method stub //放行 return invocation.invoke(); } }
在struts.xml中配置拦截器
<interceptors> <!-- 注册拦截器 --> <interceptor name="myIntercept" class="com.Gary.web.intercept.MyIntercept"></interceptor> <!-- 注册拦截器栈 --> <interceptor-stack name="myStack"> <!-- 引入自己创建的拦截器 --> <interceptor-ref name="myIntercept"></interceptor-ref> <!-- 引入strtus给你写好的拦截器(20个拦截器) --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 指定包中的默认拦截器栈 --> <default-interceptor-ref name="myStack"></default-interceptor-ref>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true"></constant> <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- name:配置包名 namespace:给action的访问路径定义一个命名空间 --> <package name="MyPackage" namespace="/" extends="struts-default"> <interceptors> <!-- 注册拦截器 --> <interceptor name="myIntercept" class="com.Gary.web.intercept.MyIntercept"></interceptor> <!-- 注册拦截器栈 --> <interceptor-stack name="myStack"> <!-- 引入自己创建的拦截器 --> <interceptor-ref name="myIntercept"></interceptor-ref> <!-- 引入strtus给你写好的拦截器(20个拦截器) --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 指定包中的默认拦截器栈 --> <default-interceptor-ref name="myStack"></default-interceptor-ref> <!-- 增加动态方法调用的安全性 --> <global-allowed-methods>regex:.*</global-allowed-methods> <!-- action:配置action类 name:决定了action访问的资源名称 servlet:url-pattern class:action的完整类名 method:指定调用action中的哪个方法来去处理请求 --> <action name="LoginAction_*" class="com.Gary.web.UserAction" method="{1}"> <!-- 默认为转发 redirect设置为重定向 --> <result name="success" type="redirect">/index.html</result> <!-- 默认为转发 --> <result name="error">/login.jsp</result> </action> <action name="LoginActionDefault" class="com.Gary.web.DefaultAction" method="execute"> </action> <action name="LoginActionImpl_*" class="com.Gary.web.ImplAction" method="{1}"> <!-- 转发到LoginActionDefault --> <result name="defaultAction" type="chain">LoginActionDefault</result> <!-- 重定向到Action(LoginAction_*) --> <result name="toLogin" type="redirectAction"> <param name="actionName">LoginAction_login</param> <param name="username">${username}</param> <param name="password">${password}</param> </result> </action> </package> <package name="PastePackage" namespace="/" extends="struts-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="PasteAction_*" class="com.Gary.web.PasteAction" method="{1}"> <result name="index">/index.jsp</result> </action> </package> </struts>
配置拦截器(拦截器只能控制访问Action,不能控制访问jsp)
在UserAction.java中当用户登陆成功时,放置user到ActionContext域中
boolean success = userService.findUser(user); if(success) { ActionContext.getContext().getSession().put("user", user); return "success"; }else{ ServletActionContext.getRequest().setAttribute("error", "用户名或密码错误!!!"); return "error"; }
实现MyIntercept.java拦截器
protected String doIntercept(ActionInvocation invocation) throws Exception { System.out.println("MyIntercept"); //获取session Map<String, Object> session = ActionContext.getContext().getSession(); //获取session中的user Object object = session.get("user"); //判断session中是否有数据 if(object!=null) { //有,放行 return invocation.invoke(); } else { //没有,重定向到login.jsp return "toLogin"; } }
局部拦截器
<action name="LoginActionDefault" class="com.Gary.web.DefaultAction" method="execute"> <result name="tologin" type="redirect">/login.jsp</result> </action>
全局拦截器:如果每一个action都要单独配置一个局部兰机器,就会显得很麻烦,这时就可以使用<global-results>标签配置全局拦截器
<default-interceptor-ref name="myStack"></default-interceptor-ref> <global-results> <result name="toLogin" type="redirect">/login.jsp</result> </global-results>
配置放行登陆方法login的拦截器
<interceptors> <!-- 注册拦截器 --> <interceptor name="myIntercept" class="com.Gary.web.intercept.MyIntercept"></interceptor> <!-- 注册拦截器栈 --> <interceptor-stack name="myStack"> <!-- 引入自己创建的拦截器 --> <interceptor-ref name="myIntercept"> <param name="excludeMethods">login</param> </interceptor-ref> <!-- 引入strtus给你写好的拦截器(20个拦截器) --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>
此时,当用户未登录时,拦截器会拦截LoginActionDefault请求,并重定向到login.jsp中。当用户登陆后,会放行LoginActionDefault请求,并在控制台输出通过System.err.println("这是一个普通的action");输出红色的【这是一个普通的action】
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="css/index.css"> </head> <div class="dvhead"> <div class="dvlogo"> <a href="index.html">你问我答</a> </div> <div class="dvsearch">10秒钟注册账号,找到你的同学</div> <div class="dvreg"> 已有账号,立即 <a href="login.html">登录</a> </div> </div> <div class="dvContent"> <div class="dvquesleft"> <div class="dvqstitle"> <image class="imgbean" src="images/bean.jpg"> <span class="qsTitle">问答</span> <span class="back"><ab href="">《《返回上一页</a></span> </div> <div class="dvtabhead"> <div class="tabheads tabcurrent">全部问题</div> <div class="tabheads">我的问题</div> <div class="tabheads">关注问题</div> <div class="tabheads">问题标签</div> </div> <div class="tabContent"> <div class="dvtags"> <a class="curenttag">待解决</a><span class="line"></span><a>高分</a><span class="line"></span><a>新回答</a><span class="line"></span><a>已解决</a> </div> <div class="tab"> <s:iterator value="pasteList" var="paste"> <div class="dvques"> <div class="quesCount"> <div class="count"><s:property value="id"/></div> <div class="ques">回答数</div> </div> <div class="quesContent"> <div class="quesTitle"> <s:property value="offer"/> <image src="images/bean.jpg" class="bean"> <span class="spanques"><s:property value="title"/></span> </div> <div class="qContent"><s:property value="content"/></div> <div class="tags"> <span class="tag">excel</span><span class="tag">程序</span> </div> <div class="quesUser"> <image src="images/0.gif" class="imguser" /> <div class="userName"> <s:property value="#user.username"/> <div class="liulan">浏览(9) 30分钟前</div> </div> </div> </div> </div> </s:iterator> </div> <div class="tab hidden">2</div> <div class="tab hidden">3</div> <div class="tab hidden">4</div> </div> </div> <div class="dvquesright"> <div> <buton class="btnques" onclick="location.href='add.html'">提个问题</buton> </div> <div class="dvorder"> <div class="orderTitle">专家排行榜</div> <div class="users"> <image class="userface" src="images/0.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> <div class="users"> <image class="userface" src="images/1.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> <div class="users"> <image class="userface" src="images/2.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> <div class="users"> <image class="userface" src="images/3.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> <div class="users"> <image class="userface" src="images/4.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> <div class="users"> <image class="userface" src="images/5.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> <div class="users"> <image class="userface" src="images/6.gif" /> <div class="dvuser"> <div class="userTitle">陈有龙</div> <div class="userdeital">大牛6级 豆:14006</div> </div> </div> </div> </div> </div> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function() { $(".tabheads").click(function() { $(".tabheads").removeClass("tabcurrent").eq($(this).index()).addClass("tabcurrent"); $(".tab").hide().eq($(this).index()).show(); }); }); </script> <body> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true"></constant> <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- name:配置包名 namespace:给action的访问路径定义一个命名空间 --> <package name="MyPackage" namespace="/" extends="struts-default"> <interceptors> <!-- 注册拦截器 --> <interceptor name="myIntercept" class="com.Gary.web.intercept.MyIntercept"></interceptor> <!-- 注册拦截器栈 --> <interceptor-stack name="myStack"> <!-- 引入自己创建的拦截器 --> <interceptor-ref name="myIntercept"> <param name="excludeMethods">login</param> </interceptor-ref> <!-- 引入strtus给你写好的拦截器(20个拦截器) --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 指定包中的默认拦截器栈 --> <default-interceptor-ref name="myStack"></default-interceptor-ref> <global-results> <result name="toLogin" type="redirect">/login.jsp</result> </global-results> <!-- 增加动态方法调用的安全性 --> <global-allowed-methods>regex:.*</global-allowed-methods> <!-- action:配置action类 name:决定了action访问的资源名称 servlet:url-pattern class:action的完整类名 method:指定调用action中的哪个方法来去处理请求 --> <action name="LoginAction_*" class="com.Gary.web.UserAction" method="{1}"> <!-- 默认为转发 redirect设置为重定向 --> <result name="success" type="redirect">/index.html</result> <!-- 默认为转发 --> <result name="error">/login.jsp</result> </action> <action name="LoginActionDefault" class="com.Gary.web.DefaultAction" method="execute"> </action> <action name="LoginActionImpl_*" class="com.Gary.web.ImplAction" method="{1}"> <!-- 转发到LoginActionDefault --> <result name="defaultAction" type="chain">LoginActionDefault</result> <!-- 重定向到Action(LoginAction_*) --> <result name="toLogin" type="redirectAction"> <param name="actionName">LoginAction_login</param> <param name="username">${username}</param> <param name="password">${password}</param> </result> </action> </package> <package name="PastePackage" namespace="/" extends="struts-default"> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="PasteAction_*" class="com.Gary.web.PasteAction" method="{1}"> <result name="index">/index.jsp</result> </action> </package> </struts>
package com.Gary.web.intercept; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; //第一种创建拦截器的方式 public class MyIntercept extends MethodFilterInterceptor{ @Override protected String doIntercept(ActionInvocation invocation) throws Exception { System.out.println("MyIntercept"); //获取session Map<String, Object> session = ActionContext.getContext().getSession(); //获取session中的user Object object = session.get("user"); //判断session中是否有数据 if(object!=null) { //有,放行 return invocation.invoke(); } else { //没有,重定向到login.jsp return "toLogin"; } } }