版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yubu_/article/details/75073989
拦截器定义
public class PermissionInterceptor extends HandlerInterceptorAdapter {
@Autowired
private AdminUserRoleService adminUserRoleService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
//如果用户还没有登录,让用户去登录
if (adminUser == null) {
//返回json格式的权限不足信息
if (CommonUtils.isEmpty(request.getHeader("x-requested-with"))) {
response.getWriter().print("需要重新登录");
} else {
response.getWriter().print(JsonUtils.toJson(AjaxResult.errorInstance("需要重新登录")));
}
return false;
}
//请求路径
String servletPath = request.getServletPath();
//检查权限
boolean result = adminUserRoleService.checkPermission(adminUser.getId(), servletPath);
if (result) {
return true;
} else {
//返回json格式的权限不足信息
if (CommonUtils.isEmpty(request.getHeader("x-requested-with"))) {
response.getWriter().print("权限不足");
} else {
response.getWriter().print(JsonUtils.toJson(AjaxResult.errorInstance("权限不足")));
}
return false;
}
}
}
拦截器配置
<mvc:interceptors>
<!-- 管理员权限拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/adminUser/*" />
.........
<mvc:exclude-mapping path="/adminUser/login.do"/>
<mvc:exclude-mapping path="/adminUser/logout.do"/>
<mvc:exclude-mapping path="/adminUser/updatePassword.do"/>
<bean class="com.rupeng.web.interceptor.PermissionInterceptor" />
</mvc:interceptor>
</mvc:interceptors>