Struts2之拦截器

Struts2的拦截器和Servlet的Filter过滤器及其相似,Struts2的拦截器只会处理action类,而servlet的过滤器可处理 servlet,jsp,html等等

拦截器可以说是Struts2的核心,大部分功能都是通过拦截器来实现的,只要我们的包继承了 struts-default

<package name="struts2" extends="struts-default">,就可以使用struts-defaul 里的拦截器


自定义拦截器的步骤

1) 编写拦截器类,需要实现 Interceptor接口,并实现该接口的三个方法:init ,intercept ,destroy

       或者继承 AbstractInterceptor抽象类 ,并实现 intercept 方法就够了

       或者继承 MethodFilterInterceptor抽象类,并实现 doIntercept方法


       分析Interceptor接口 AbstractInterceptor抽象类MethodFilterInterceptor抽象类,三者是存在关系的,

                  MethodFilterInterceptor抽象类继承  AbstractInterceptor抽象类 实现  Interceptor接口                 

2) 在struts.xml 文件中定义拦截器(action标签外)

3) 在struts.xml 文件中 的 action标签内引用 拦截器


如果使用了自定义的拦截器,则在拦截器的最后还要加个

默认拦截器 <interceptor-ref name="defaultStack"></interceptor-ref> ,当自定义拦截器执行了,则默认拦截器不会执行

如果在action内没加任何拦截器,则默认使用默认拦截器


举例:

1.1自定义拦截器的第一种方式:实现 Interceptor接口

package com.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;

//定义一个拦截器1
public class Interceptor1 implements
		com.opensymphony.xwork2.interceptor.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 {
		
		System.out.println("Interceptor1 before");
		String str = invocation.invoke() ;
		System.out.println("Interceptor1 after");		
		return str;
	}

}

1.2自定义拦截器的第二种方式:继承AbstractInterceptor抽象类

package com.struts2.interceptor;

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

//定义一个拦截器2
public class Interceptor2 extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		System.out.println("Interceptor2 before");
		String str = invocation.invoke() ;
		System.out.println("Interceptor2 after");
		return str;
	}

}

1.3自定义拦截器的第三种方式:继承MethodFilterInterceptor抽象类


package com.struts2.interceptor;

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

//定义一个拦截器3,可以拦截自定义的方法,而其他拦截器只拦截 execute方法
public class Interceptor3 extends MethodFilterInterceptor {

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		
		System.out.println("Interceptor3 before");
		String str = invocation.invoke() ;
		System.out.println("Interceptor3 after");
		return str;
	}

}

2.在struts.xml 文件中定义拦截器(action标签外)

<struts>
    
   <package name="struts2" extends="struts-default">
      
      <!-- 定义拦截器 -->
      <interceptors>
          <interceptor name="interceptor1" class="com.struts2.interceptor.Interceptor1">
          </interceptor>
          
          <interceptor name="interceptor2" class="com.struts2.interceptor.Interceptor2">
          </interceptor>
          
          <interceptor name="interceptor3" class="com.struts2.interceptor.Interceptor3"></interceptor>
      </interceptors>


3.在struts.xml 文件中 的 action标签内引用 拦截器

      <action name="action1" class="com.struts2.Action1" method="myExecute">
          <result name="success" type="redirectAction">
              
             <param name="actionName">action2</param> <!-- 重定向到 action2 -->
             
             <!-- 重定向到 action2 并要携带的参数如下, -->
             <param name="usename">${usename}</param>
             <param name="password">${password}</param>
              
          </result>
          
          <!-- 引用拦截器 -->
          <interceptor-ref name="interceptor1"></interceptor-ref>
          <interceptor-ref name="interceptor2"></interceptor-ref>
          <interceptor-ref name="interceptor3">
             <param name="excludeMethods"></param>       
             <param name="includeMethods">execute</param>   
          </interceptor-ref>
          <interceptor-ref name="defaultStack"></interceptor-ref>
      </action>

假如用第三种方式定义拦截器的话,引用拦截器的时候还可以指定拦截的方法,excludeMethods 指定排除方法的拦截,includeMethods 把要拦截的方法包含进来,二者都可以排除多个方法,和包含多个方法,方法名用逗号‘ ’隔开。

就如上面引用拦截器的第三个来说,action 是执行自定义的myExecute()方法的,但 includeMethods包含是execute方法,所以interceptor3拦截器不会执行

如果没有指定拦截器的参数,默认会拦截全部方法


应用一(登录,判断用户是否登录):

1.定义一个拦截器类:

package com.struts2.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.struts2.LoginAction;

public class LoginInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		// 这个 LoginAction 是处理登陆的,当然不用检查session了
		//invocation.getAction() 获取  action类的具体包
		if(LoginAction.class == invocation.getAction().getClass() )
		{
			return invocation.invoke();
		}
		
		Map map =invocation.getInvocationContext().getSession();
		
		if(null == map.get("usename"))
		{
			 return Action.LOGIN; //如果用户还没登陆,跳到login页面
		}
		
		return invocation.invoke();
	}

}

2.在struts.xml中定义 拦截器,和一个拦截器栈,注意 拦截器栈后也要加一个默认拦截器,

接着再把我们定义的拦截器栈,设为默认的拦截器,这样的作用是拦截全部action,很显然拦截全部action不是我们所要的,我们还需要一些action不被拦截,上面的拦截器已经处理了,就在 intercept方法内,加了

if(LoginAction.class == invocation.getAction().getClass() )
        {
            return invocation.invoke();
        }

就可以不对其进行 判断有没session


在struts.xml中定义 拦截器,和一个拦截器栈默认的拦截器

注意 默认拦截器 定义的位置,是在interceptor外的

<struts>
    
   <package name="struts2" extends="struts-default">
      
      <!-- 定义拦截器 -->
      <interceptors>
                 
          <interceptor name="LoginInterceptor" class="com.struts2.interceptor.LoginInterceptor">
          </interceptor>
          
          <!-- 定义一个拦截器栈 , -->
          <interceptor-stack name="MyDefaultInterceptor">
              <interceptor-ref name="LoginInterceptor"></interceptor-ref>
              <!-- 记得加上默认拦截器 -->
              <interceptor-ref name="defaultStack"></interceptor-ref>
          </interceptor-stack>
         
      </interceptors>
      
          <!-- 定义自己的默认拦截器 -->
          <default-interceptor-ref name="MyDefaultInterceptor">           
          </default-interceptor-ref>

3.定义一个全局的结果,在package标签下定义:

      <global-results>
          <result name="myexception1">/error.jsp</result>
          <result name="login">/logingo.jsp</result>
      </global-results>
这个全局结果 <result name="login">/logingo.jsp</result> 会被 LoginInterceptor拦截器的  Action.LOGIN;  找到


4.具体处理登录的action类

package com.struts2;

import java.util.Map;

import com.exception.MyException ;
import com.opensymphony.xwork2.ActionContext;

public class LoginAction {
	
	private String usename ;
	private String password ;
	
	public String getUsename() {
		return usename;
	}
	public void setUsename(String usename) {
		this.usename = usename;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	//这个方法不可少
	public String execute() throws Exception
	{
		if(!"hello".equals(usename) || !"world".equals(password))
		{
			throw new MyException("用户名或密码错误,您发现了吧!");
		}
		Map session = ActionContext.getContext().getSession();
		session.put("usename", usename) ;
		return "success" ;
	}

}

5.登陆界面logingo.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'logingo.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    
    <form action="login">
        <input type="text" name="usename" /><br/>
        <input type="password" name="password" /><br/>
        <input type="submit" value="登录"/>
    </form>
    
    
  </body>
</html>













































  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值