简单的实现登录拦截及统一异常处理(自定义异常)

webmvc配置类:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport{

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns("/user/login");
    }
}

注:registry.addInterceptor(拦截器类对象).addPathPatterns("需要拦截的请求路径").excludePathPatterns("可以放行的请求路径");

 

拦截器类,这里为登录拦截

public class LoginInterceptor implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean preHandle(HttpServletRequest hServletRequest, HttpServletResponse hServletResponse, Object object) throws Exception {
        // 案例采用session存储登录用户,所以从session获取登录用户
     HttpSession session
= hServletRequest.getSession(); TUser tUser=(TUser)session.getAttribute("user");
// 判断session里是否能取出用户
if(tUser==null) { returnErrorMessage(hServletResponse, "当前操作需要先进行用户登录"); return false; } return true; } private void returnErrorMessage(HttpServletResponse response, String errorMessage) throws IOException { response.setCharacterEncoding("utf-8"); Map<String, Object> var=new HashMap<>(); var.put("success", false); var.put("errorMessage", errorMessage); response.setContentType("application/json"); PrintWriter out = response.getWriter(); ObjectMapper mapper = new ObjectMapper(); String jsonOfRST =mapper.writeValueAsString(var); out.print(jsonOfRST); out.flush(); } }

到这里实现了简单的登录拦截,但是上面通过response对象获取的输出流来写入错误信息,下面采用自定义异常来处理

 

异常类

public class UnloggedException extends RuntimeException{
    private static final long serialVersionUID = 181074719716690931L;
    
    public UnloggedException() {
        super("当前操作需要先进行登录");
    }
}

修改拦截器类的preHandle方法,于是returnErrorMessage方法可以去掉了

@Override
    public boolean preHandle(HttpServletRequest hServletRequest, HttpServletResponse hServletResponse, Object object) throws Exception {
        HttpSession session = hServletRequest.getSession();
        TUser tUser=(TUser)session.getAttribute("user");
        if(tUser==null) {
            throw new UnloggedException();
        }
        return true;
    }

最后配置异常处理类

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JSONObject handleException(Exception e) {
        return ActionHelper.responseFailed(e.getMessage());
    }
}

上面的返回值及ActionHelper为我使用的返回工具类,依赖为com.alibaba的fastjson,版本参考1.2.49。

可以根据实际情况修改返回方式及返回值。

此后所有的异常,都可以通过自定义异常的方式,交由异常处理类来进行处理,返回结果。

posted @ 2018-09-27 22:24  涛先森の日常  阅读(1561)  评论(0编辑  收藏  举报