struts2自定義攔截器的示例代碼
題目:使用struts2自定義攔截器,完成用戶登陸才能訪問權限的實現(xiàn)
- 在session中存放user變量表示用戶登陸,若user為空則用戶沒有登陸,反之登陸
- 顯示提示信息(請先登錄)
定義攔截器
在struts.xml中定義攔截器使用標簽<Intercaptors>、<Intercapter>。
<interceptors>
<interceptor name="test" class="Intercaptor.Intercaptor" />
<interceptor-stack name="testStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="test" />
</interceptor-stack>
</interceptors>
注:當我們?yōu)槟硞€action添加Intercaptor時就會放棄struts2的其他的攔截器,所以我們要把自定義的攔截器放在一個一個攔截器棧中。
name屬性就是Intercaptor.Intercaptor類在服務器上的一個實例
class屬性就是這個攔截器的的類
實現(xiàn)攔截器
攔截器的java類要實現(xiàn)Intercaptor這個接口和里面的方法intercept()。我們這里攔截的條件是用戶是否登陸,也就是session中的user變量是否為空。
public class Intercaptor implements Interceptor{
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
Object user=ActionContext.getContext().getSession().get("user");
if(user!=null){
return invocation.invoke();
}
ActionContext.getContext().put("message", "請先登陸");
return "success";
}
}
實現(xiàn)業(yè)務邏輯
在action中添加攔截器
<action name="Action" class="Action.Action">
<interceptor-ref name="test"></interceptor-ref>
<result name="success">Message.jsp</result>
</action>
其他
action的實現(xiàn)
public class Action extends ActionSupport{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() throws Exception {
return "success";
}
}
index.jsp
<body>
用戶狀態(tài):${user!=null?"已登陸":"未登陸"}<br>
<a href="UserLogin.jsp" rel="external nofollow" >用戶登陸</a>
<a href="UserQuit.jsp" rel="external nofollow" >用戶退出</a>
<form action="<%request.getContextPath(); %>/testIntercaptor/Action">
<input type="submit" value="登陸后的操作">
</form>
</body>

UserLogin.jsp
在request.getSesssion中存放user變量
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
登陸成功
<%
request.getSession().setAttribute("user", "user");
response.setHeader("refresh", "1;url=index.jsp");
%>
UserQuit.jsp
移除request.getSesssion中user變量
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
退出成功
<%
request.getSession().removeAttribute("user");
response.setHeader("refresh", "1;url=index.jsp");
%>
Message.jsp
簡單是輸出message和debug
<body>
${message } <br/>
<s:debug></s:debug>
</body>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
簡單談談java的異常處理(Try Catch Finally)
在程序設計中,進行異常處理是非常關鍵和重要的一部分。一個程序的異常處理框架的好壞直接影響到整個項目的代碼質(zhì)量以及后期維護成本和難度。2016-03-03
使用WebUploader實現(xiàn)上傳文件功能(一)
這篇文章主要為大家詳細介紹了使用WebUploader實現(xiàn)上傳文件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
Spring Security實現(xiàn)身份認證和授權的示例代碼
在 Spring Boot 應用中使用 Spring Security 可以非常方便地實現(xiàn)用戶身份認證和授權,本文主要介紹了Spring Security實現(xiàn)身份認證和授權的示例代碼,感興趣的可以了解一下2023-06-06
說說@ModelAttribute在父類和子類中的執(zhí)行順序
這篇文章主要介紹了@ModelAttribute在父類和子類中的執(zhí)行順序,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

