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>