1.在攔截器中獲得用戶登錄的session
在LoginCheckInterceptor中extends AbstractInterceptor
package com.jsu.struts2.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginCheckInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ctx=invocation.getInvocationContext();
String flag =(String)ctx.getContext().getSession().get("flag");
if("ok".equals(flag)){
System.out.println("已登錄、、、");
return invocation.invoke();
}else{
//提示信息,可以通過key值在頁面獲取
ctx.put("err_msg", "對不起,你還木有登錄,請先登錄");
return "error";
}
}
}
2.在LoginAction中
package com.jsu.struts2.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
@Override
public String execute() throws Exception {
ActionContext.getContext().getSession().put("flag", "ok");
System.out.println("OK");
System.out.println(" Action Execute...");
return SUCCESS;
}
}
3.在OrderAction中extends ActionSupport
package com.jsu.struts2.action;
import com.opensymphony.xwork2.ActionSupport;
public class OrderAction extends ActionSupport{
@Override
public String execute(){
System.out.println("開始下訂單、、、");
return SUCCESS;
}
}
4.在error.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> </head>
<body>
Error ${err_msg} <br>
</body>
</html>
5.在struts.xml文件中配置
<struts>
<package name="loginDemo" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="myint1" class="com.jsu.struts2.interceptor.LoginCheckInterceptor"> </interceptor>
<action name="login" class="com.jsu.struts2.action.LoginAction">
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/index.jsp</result>
</action>
<action name="order" class="com.jsu.struts2.action.OrderAction">
<interceptor-ref name="myint1"></interceptor-ref>
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
6.在地址欄發請求
1.http://localhost:8080/struts2_04/order error.jsp頁面輸出:你還沒有登錄,請先登錄
2.先輸入http://localhost:8080/struts2_04/login 控制檯輸出登錄成功
在輸入http://localhost:8080/struts2_04/order 控制檯輸出開始下訂單、、、