在struts.xml中配置interceptor,对用户请求进行权限校验,只有具备相应权限的用户才能访问相应的资源
时间: 2023-12-14 15:36:45 浏览: 24
在 Struts2 中,可以使用 Interceptor 对用户请求进行权限校验。Interceptor 是一个类,可以截获请求和响应,以实现一些公共的逻辑处理,比如日志记录、权限校验、异常处理等。
下面是一个简单的示例,演示如何在 Struts2 中使用 Interceptor 进行权限校验:
1. 首先在 struts.xml 中定义一个 Interceptor:
```xml
<interceptors>
<interceptor name="authInterceptor" class="com.example.AuthInterceptor"/>
<interceptor-stack name="authStack">
<interceptor-ref name="authInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
```
2. 接着,在需要进行权限校验的 Action 中,使用上面定义的 Interceptor Stack:
```xml
<action name="myAction" class="com.example.MyAction">
<interceptor-ref name="authStack"/>
<result name="success">/success.jsp</result>
<result name="login">/login.jsp</result>
</action>
```
3. 最后,定义 AuthInterceptor 类,实现权限校验逻辑:
```java
public class AuthInterceptor implements Interceptor {
public void init() {}
public void destroy() {}
public String intercept(ActionInvocation invocation) throws Exception {
// 检查用户是否具备相应权限,如果没有,跳转到登录页面
if (!checkAuthorization()) {
return "login";
}
// 如果用户已经登录且具备相应权限,则继续执行 Action
return invocation.invoke();
}
private boolean checkAuthorization() {
// 在这里实现具体的权限校验逻辑
return true;
}
}
```
上面的示例中,AuthInterceptor 实现了 Interceptor 接口,其中的 intercept 方法就是权限校验逻辑的实现。如果用户没有登录或者没有相应的权限,则返回 "login" 结果,跳转到登录页面;否则,继续执行 Action。在实际应用中,可以根据具体的需求,实现自己的权限校验逻辑。