简单实现Struts2的权限拦截器
程序员文章站
2022-05-28 16:13:53
...
Action请求类
package action;
public class SystemAction {
public String execute() {
return "success";
}
}
自定义拦截器
package interceptors;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class PermissionInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String currentUser = (String)ActionContext.getContext().getSession().get("currentUser");
if (null != currentUser) {
// 执行Action中的方法或调用其后的拦截器
return invocation.invoke();
}
return "fail"; // 当前用户为null时跳转至fail视图
}
}
Struts2核心配置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="strutsCore" namespace="/interceptor" extends="struts-default">
<interceptors>
<!-- 注册自定义PermissionInterceptor拦截器 -->
<interceptor name="permissionInterceptor" class="interceptors.PermissionInterceptor"/>
</interceptors>
<action name="systemAction" class="action.SystemAction">
<!-- 为Action关联自定义拦截器,此后系统默认的拦截器自动失效 -->
<interceptor-ref name="permissionInterceptor"/>
<!-- 开启strust-default.xml中的默认拦截器栈 -->
<interceptor-ref name="defaultStack"/>
<result name="success">/welcome.jsp</result>
<result name="fail">/fail.jsp</result>
</action>
</package>
</struts>
视图:index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>This is page index!</h2>
</body>
</html>
视图:welcome.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h2>This is page welcome!</h2>
</body>
</html>
视图:login.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<% session.setAttribute("currentUser", "WanAkiko"); %>
<h2>提示:登录成功,WanAkiko,欢迎回来!</h2>
</body>
</html>
视图:logout.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Logout</title>
</head>
<body>
<% session.removeAttribute("currentUser"); %>
<h2>提示:当前用户已退出!</h2>
</body>
</html>
视图:fail.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fail</title>
</head>
<body>
<h2>This is page fail!</h2>
</body>
</html>
使用Chrome与IE对自定义拦截器进行测试
测试结果:项目启动后即访问index.jsp,此时若未登录,则通过SystemAction访问的是fail.jsp,若进入login.jsp后再次对SystemAction进行请求则访问welcom.jsp,此后若再执行logout.jsp后又执行SystemAction则亦会进入fail.jsp,由此可见我们自定义的权限拦截器确实在生效。
上一篇: SpringMVC 跨域请求