1、首先有以下jar包。不是全部都是必须的。
2、配置一下web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>intercerpt</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3、写一个main.jsp页面
<s:head></s:head>
<meta charset="utf-8">
<title>main.jsp</title>
</head>
<body>
<!-- 通过判断有没有登录,来决定能不能 访问主页 -->
主页
<%System.out.print("main.jsp"); %>
</body>
</html>
4、写一个类UserAction,注意要继承ActionSupport
package com.controller;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
public String sayHello(){
System.out.println("sayhello执行了");
return "success";
}
}
5、写一个拦截器类Myintercerpt,注意要继承 AbstractInterceptor
package com.intercerpt;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Myintercerpt extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation arg0) throws Exception {
/* //这种写法与下面写法(注释掉放行那行代码)有一样的效果
System.out.println("Myintercerpt1拦截器 执行了");
return "sucess"; */
System.out.println("Myintercerpt1拦截器 执行了");
//invoke (放行)
String value = arg0.invoke(); //如果注释掉这行,就会拦截了sayHello方法
//返回值就是结果类型<result name="success">中的name值
//return value; //value与struts里面的<result name=""一致,即success
return "hello world"; //也是可以的
}
}
6、写一个struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="p1" extends="struts-default">
<!-- 要先声明拦截器,否则不被识别,那么默认的就要被覆盖了 -->
<interceptors>
<interceptor name="check" class="com.intercerpt.Myintercerpt"></interceptor>
</interceptors>
<action name="sayHello" class="com.controller.UserAction" method="sayHello">
<!-- 声明拦截器之后,要引入拦截器,它才会起作用 -->
<interceptor-ref name="check"></interceptor-ref>
<result name="success">/main.jsp</result>
</action>
</package>
</struts>
7、运行时要在路径最后加上sayHello才会促发动作执行,如果在拦截器类Myintercerpt里面注释了放行语句,那么UserAction类里面的sayHello方法就会被拦截,即不会在控制台输出“sayhello执行了”。