在搭建ssm框架课设时,使用到了拦截器和异常映射。写完管理员的功能后,尝试写教师功能跳转请求的时候一直提示我一个实体转换错误
卡了一个下午一直想不到问题在哪,为啥我发出一个请求还没有执行到我的controller就抛出了异常。仔细看了我之前搭的框架,发现我拦截了所有的请求做了判断
private ModelAndView commonResolve(String viewName, Exception exception, HttpServletRequest request, HttpServletResponse response ) throws IOException {
// 1. 判断当前请求类型
boolean judgeResult = CrowdUtil.judgeRequestType(request);
// 2. 如果为Ajax请求
if (judgeResult) {
// 3. 创建 ResultEntity 对象
ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage());
// 4. 创建Gson对象
Gson gson = new Gson();
// 5. 将ResultEntity对象转换为JSON字符串
String json = gson.toJson(resultEntity);
// 6. 将JSON字符作为响应体返回给浏览器
response.getWriter().write(json);
// 7. 上面已经通过原生response对象返回了响应,因此不再提供ModelAndView对象
return null;
}
// 8. 如果不是Ajax请求,则创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
// 9. 将Exception对象存入模型
modelAndView.addObject(CrowdConstant.ATTR_NAME_EXCEPTION, exception);
// 10. 设置对应的视图名称
modelAndView.setViewName(viewName);
return modelAndView;
}
//登录失败异常处理方法
@ExceptionHandler(value = LoginFailedException.class)
public ModelAndView resolveLoginFailedException(NullPointerException exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
String viewName = "admin-login";
return commonResolve(viewName,exception,request,response);
}
又使用拦截器对所有请求执行前进行了检查
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 1.通过request对象获取Session对象
HttpSession session = request.getSession();
System.out.println("尝试了强转");
// 2.尝试从Session域获取Admin对象,在登陆的hanler中登陆成功后存入了ATTR_NAME_LOGIN_ADMIN
// Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
Admin admin=(Admin)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
// 3.判断Admin对象是否为空
if (admin == null) {
// 4.抛出异常
System.out.println("抛出了异常");
throw new AccessForbidden(CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);
}
// 5. 若admin不为空,则返回true放行
return true;
}
}
问题就出在这个强转上,当我登陆了teacher后 将teacher存入了常量类,但我还拿admin来判断的。找到这里,突然想到可以用这个来做权限控制,通过不同的权限变量在请求发出后执行前进行判断,达到不同用户对不同方法的操作权限。