一暑刃、為什么要自定義攔截器
在struts2里面有很多攔截器揽咕,這些攔截器是struts2封裝的功能乡恕,但是在實(shí)際開(kāi)發(fā)中,struts2里面攔截器中可能沒(méi)有要使用的功能尔觉,這個(gè)時(shí)候需要自己寫攔截器實(shí)現(xiàn)功能
二凉袱、攔截器的結(jié)構(gòu)
1、源代碼看攔截器結(jié)構(gòu)
-
繼承類
-
在接口里面有三個(gè)方法
2侦铜、開(kāi)發(fā)中寫類专甩,繼承
- 繼承MethodFilterInterceptor:它可以讓action里一些方法不進(jìn)行攔截
3、讓攔截器和action有關(guān)系
- 不是action調(diào)用攔截器的方法钉稍,而是通過(guò)配置文件方式建立關(guān)系
三涤躲、自定義登錄攔截器
1、需求
在項(xiàng)目中贡未,有許多action的超鏈接种樱,實(shí)現(xiàn)只有是登錄的狀態(tài)蒙袍,才可以點(diǎn)擊action的超鏈接實(shí)現(xiàn)功能,如果不是登錄缸托,點(diǎn)擊action鏈接返回登錄頁(yè)面
2左敌、登錄狀態(tài):session域?qū)ο髮?shí)現(xiàn)
- 登錄成功后,把數(shù)據(jù)放到session里面
- 判斷session是否有值俐镐,可以知道登錄狀態(tài)
3矫限、實(shí)現(xiàn)登錄的基本功能
login.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 'login.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>
<div align="center">
<h1>Login</h1>
<h3 style="color: red">${requestScope.msg }</h3>
<form action="${pageContext.request.contextPath }/checklogin" method="post">
username:<input type="text" name="username"/><br><br>
passwork:<input type="password" name="password"/><br><br>
<input type="submit" value="login"/>
</form>
</div>
</body>
</html>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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 'index.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>
<c:if test="${''!=sessionScope.username && null!=sessionScope.username }">
歡迎 ${sessionScope.username }
</c:if>
<c:if test="${''==sessionScope.username || null==sessionScope.username }">
<a href="${pageContext.request.contextPath }/login.jsp"> 您好請(qǐng)登錄!</a>
</c:if>
<br>
<a href="${pageContext.request.contextPath }/hehe">點(diǎn)我·····</a>
<br>
<a href="${pageContext.request.contextPath }/haha">點(diǎn)我·····</a>
</body>
</html>
CheckLogin.java
package work.zhangdoudou.Action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import work.zhangdoudou.Bean.UserBean;
public class CheckLogin extends ActionSupport implements ModelDriven<UserBean>{
private UserBean user;
@Override
public String execute() throws Exception {
HttpServletRequest request=ServletActionContext.getRequest();
if ("manman".equals(user.getUsername())&&"520".equals(user.getPassword())) {
// 登錄成功
//向session放值
request.getSession().setAttribute("username", user.getUsername());
System.out.println(SUCCESS);
return SUCCESS;
}else{
//登錄失敗
request.setAttribute("msg", "賬號(hào)或密碼錯(cuò)誤佩抹!");
System.out.println(ERROR);
return ERROR;
}
}
@Override
public UserBean getModel() {
if (null==user) {
user=new UserBean();
}
return user;
}
}
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>
<constant name="false" value="struts.enable.DynamicMethodInvocation"/>
<constant value="true" name="struts.devMode"/>
<package name="default" extends="struts-default" namespace="/">
<!--name:訪問(wèn)名稱 -->
<action name="checklogin" method="execute" class="work.zhangdoudou.Action.CheckLogin">
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>struts2.Filter</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>
4叼风、添加登陸攔截器
(1)判斷是否登錄:判斷session里面是否有username的值
(2)攔截器的實(shí)現(xiàn)過(guò)程
- 創(chuàng)建一個(gè)類,繼承MethodFilterInterceptor類
- 重寫MethodFilterInterceptor里的方法棍苹,寫攔截器邏輯
攔截器類Filter.java
package work.zhangdoudou.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.client.Invocation;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class Filter extends MethodFilterInterceptor{
//這個(gè)方法里面寫攔截器邏輯
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
//判斷session是否有username值
//得到session
HttpServletRequest request=ServletActionContext.getRequest();
Object object=request.getSession().getAttribute("username");
//判斷
if (null!=object) {
//登陸狀態(tài)
//做類似于放行操作
return invocation.invoke();
}else{
//不是登陸狀態(tài)
//不登錄不執(zhí)行action的方法无宿,返回登陸頁(yè)面
request.setAttribute("msg", "請(qǐng)登錄!");
return "error";
}
}
}
(3)配置action和攔截器的關(guān)系(注冊(cè)攔截器)
- 在要攔截的action標(biāo)簽所在的package標(biāo)簽里聲明攔截器
- 在具體的action標(biāo)簽里使聲明的攔截器
- struts2里面執(zhí)行很多默認(rèn)攔截器枢里,但是如果在action里面配置自定義攔截器
問(wèn)題:默認(rèn)的攔截器不會(huì)執(zhí)行了
解決:把默認(rèn)的手動(dòng)配置一次
特點(diǎn):配置的攔截器會(huì)對(duì)action所有方法都會(huì)攔截
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>
<constant name="false" value="struts.enable.DynamicMethodInvocation"/>
<constant value="true" name="struts.devMode"/>
<package name="default" extends="struts-default" namespace="/">
<!-- 聲明攔截器 -->
<interceptors>
<interceptor name="login" class="work.zhangdoudou.Filter.Filter"></interceptor>
</interceptors>
<!--name:訪問(wèn)名稱 -->
<action name="checklogin" method="execute" class="work.zhangdoudou.Action.CheckLogin">
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
<action name="hehe" method="execute" class="work.zhangdoudou.Action.hehe">
<!-- 使用自定義的攔截器 -->
<interceptor-ref name="login"></interceptor-ref>
<!-- 默認(rèn)攔截器手動(dòng)使用一次 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
5孽鸡、配置攔截器,不要對(duì)action的所有方法都進(jìn)行攔截
- 直接通過(guò)配置方式讓action里面某些方法不進(jìn)行攔截
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>
<constant name="false" value="struts.enable.DynamicMethodInvocation"/>
<constant value="true" name="struts.devMode"/>
<package name="default" extends="struts-default" namespace="/">
<!-- 聲明攔截器 -->
<interceptors>
<interceptor name="login" class="work.zhangdoudou.Filter.Filter"></interceptor>
</interceptors>
<!--name:訪問(wèn)名稱 -->
<action name="checklogin" method="execute" class="work.zhangdoudou.Action.CheckLogin">
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
<action name="hehe" method="execute" class="work.zhangdoudou.Action.hehe">
<!-- 使用自定義的攔截器 -->
<interceptor-ref name="login"></interceptor-ref>
<!-- 默認(rèn)攔截器手動(dòng)使用一次 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
<action name="haha" method="haha" class="work.zhangdoudou.Action.hehe">
<!-- 使用自定義的攔截器 -->
<interceptor-ref name="login">
<!-- 配置某些方法不進(jìn)行攔截 name屬性excludeMethods -->
<param name="excludeMethods">haha</param>
</interceptor-ref>
<!-- 默認(rèn)攔截器手動(dòng)使用一次 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/index.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
6栏豺、實(shí)現(xiàn)效果
點(diǎn)擊攔截進(jìn)行登錄
點(diǎn)擊不攔截