Struts2day03Struts2.o拦截器

本文介绍Struts2框架中的拦截器开发流程,包括自定义拦截器类、配置拦截器及与默认拦截器的组合使用。通过实例演示如何实现一个简单的拦截器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Struts2.0拦截
   拦截器:为访问Action的请求增加额外功能
           保证程序的继续执行
2.如何开发一个拦截器
    1.开发一个类 implements Interceptor
    2.struts.xml配置文件
      1    <!-- 声明拦截器 -->
     <interceptors>
        <interceptor name="MyInterceptor" class="zx.struts2.day3.interceptor.MyInterceptor"></interceptor>
     </interceptors>
         自定义了拦截器,Struts2.0提供的默认拦截器失效

      2.在需要调用拦截器的action中配置
         在Action中引用拦截器的顺序决定了拦截器的执行顺序
     如果有多个拦截器是成组调用时,可以设置拦截器栈

 

1.写一个类MyInterceptor implements Interceptor接口

package com.jsu.struts2.interceptor;

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

public class MyInterceptor implements Interceptor {
	/**初始化资源*/
        public void init() {
	}
       	/*
	 * 拦截器的核心功能 @ActionInvocation
	 * 1.获得ActionContext:request,session,application... 
	 * 2.保证程序的继续执行
	 * 3.获得用户访问的Action对象信息 
	 * 4.获得值栈(valueStack)
	 */
        public String intercept(ActionInvocation invocation) throws Exception {
		System.out.println("Interceptor start....");
                // invocation.invoke()执行之前,都会在访问Action之前执行
                String path = invocation.invoke();
                // invocation.invoke()执行之后,都会在访问Action之后执行
                System.out.println("Interceptor end....");
		return path;
	}
         /* 释放资源 */
        public void destroy() {
	}
}

 2.写一个Action MyAction extends ActionSupport

package com.jsu.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport {
	public String execute(){
		System.out.println("execute Action");
		return SUCCESS;
	}
}

 3.配置Struts.xml文件

   自定义拦截器在package标签下面,action标签上面

<struts>
	<package name="loginDemo" namespace="/" extends="struts-default">
	<!-- 自定义拦截器 -->
	<interceptors>
		<interceptor name="MyInterceptor" class="com.jsu.struts2.interceptor.MyInterceptor"></interceptor>
	</interceptors>
	<!-- 配置拦截器 -->
	<action name="my" class="com.jsu.struts2.action.MyAction">
	<interceptor-ref name="MyInterceptor"></interceptor-ref>
	<interceptor-ref name="defaultStack"></interceptor-ref>
		<result>/login.jsp</result>
	</action>	
	</package>
</struts>

 在login.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head> </head>
  <body>
     <center>
   <form action="my.action" method="post">
   userName:<input type="text" name="username"/> <br>
   passWord:<input type="text" name="pwd"/><br>
   <input type="submit" value="Submit"/>
   </form>
   </center>
  </body>
</html>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值