实现一个登陆权限验证的功能
message.jsp:
<body>
message:${message }
</body>
login.jsp:
<%
request.getSession().setAttribute("user", "tom");
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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">
</head>
<body>
成功登录!
</body>
</html>
Action:
public class MainAction { private String message;
public String mainPage(){
message="welcome you!";
return "message";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
} }
拦截器:
public class PermissionsInterceptor implements Interceptor {
private static final long serialVersionUID = 1L; @Override
public String intercept(ActionInvocation invocation) throws Exception {
Object user=ActionContext.getContext().getSession().get("user");
if(user!=null){
return invocation.invoke();
}else{
ActionContext.getContext().put("message", "你没有权限制执行该操作!");
return "message";
}
} @Override
public void destroy() {
} @Override
public void init() {
}
}
Struts.xml:
<struts>
<constant name="struts.118n.encoding" value="UTF-8"></constant>
<constant name="struts.action.extension" value="do"></constant>
<package name="mainPackage" namespace="/cn" extends="struts-default">
<interceptors>
<interceptor name="permissions" class="cn.interceptor.PermissionsInterceptor" />
<interceptor-stack name="permissionsStack">
<!-- defaultStack 系统默认拦截器,在执行自定认拦截器之前必须加入系统默认拦截器,否则系统默认拦截器无法使用 -->
<interceptor-ref name="defaultStack" />
<interceptor-ref name="permissions" />
</interceptor-stack>
</interceptors>
<!-- 默认拦截器,程序内的所有Action都被拦截器拦截到 如果Action内又引入新的拦截器,此拦截器将被覆盖 -->
<!-- <default-interceptor-ref name="permissionsStack"></default-interceptor-ref> -->
<global-results>
<result name="message">/WEB-INF/message.jsp</result>
</global-results>
<action name="main_*" class="cn.actions.MainAction" method="{1}">
<interceptor-ref name="permissionsStack" />
</action>
</package>
</struts>
当用户没有访问login.jsp为Session添加User时,访问(http://localhost:9000/Struts4/cn/main_mainPage.do),被拦截器拦截到,报出”你没有权限制执行该操作!“的错误;
当用户执行过login.sjp以后显示”welcom you!“