SSM框架使用第六集 - 创建权限验证拦截
从上一集开始,我们已经完成了正常的事务的增删查改操作了,接下来我们要根据SpringAOP机制创建权限拦截功能
- 新建interceptor文件继承HandlerInterceptorAdapter
public class adminInterceptor extends HandlerInterceptorAdapter {
@Resource
private respond respond;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
//验证是否是管理员
if(session.getAttribute("admin")!="true"){
//重置response
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
//输出无权限
PrintWriter pw = response.getWriter();
pw.println(JSONObject.toJSONString(respond.Error("无权限,请登录")));
pw.flush();
pw.close();
return false;
}
//正常继续执行
return true;
}
}
- 配置SpringMVC拦截
<mvc:interceptors>
<mvc:interceptor>
<!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->
<mvc:mapping path="/**/add" />
<mvc:mapping path="/**/remove" />
<mvc:mapping path="/**/update" />
<mvc:mapping path="/**/changeId" />
<mvc:mapping path="/File/**" />
<bean class="cn.cenita.interceptor.adminInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>