SpringMVC拦截器返回值不能自定义的解决办法
2017-01-04 16:27
465 查看
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { int httpCode = xxx; response.sendError(httpCode,"error message"); return false; }
这样做的话,前端每次都只能拿到状态码,好像拿不到具体的错误内容。然后,我换了种方式。
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestContent = getRequestBody(request); log.debug("requestContent:{}", requestContent); LoginParam param = map.fromJson(requestContent, LoginParam.class); log.debug("param:{}", param); if (StringUtils.isBlank(param.getCode())) { returnErrorMessage(response, "请输入验证码"); return false; } //验证码是否验证通过 ... boolean validPass = isValidUser(request, param); if (validPass) { return true; } returnErrorMessage(response, "用户名或密码错误,请重新尝试。"); log.debug("Error"); return false; } private void returnErrorMessage(HttpServletResponse response, String errorMessage) throws IOException { Result rst = new Result(); rst.setCode("0"); rst.setMessage(errorMessage); response.setContentType("application/json"); //Get the printwriter object from response to write the required json object to the output stream PrintWriter out = response.getWriter(); //Assuming your json object is **jsonObject**, perform the following, it will return your json object ObjectMapper mapper = new ObjectMapper(); String jsonOfRST = "{\"result\":" + mapper.writeValueAsString(rst) + ",\"data\":null}"; out.print(jsonOfRST); out.flush(); }
上面这种办法就是,不返回标准的HttpStatus401,而是改用200,这样的话,前端好处理。
相关文章推荐
- 微服务框架Spring Cloud介绍 Part2: Spring Cloud与微服务
- 分享微信开发Html5轻游戏中的几个坑
- springmvc实现url路由功能
- spring aop 无法代理父类方法 的解决方法
- Spring MVC过滤器-超类 GenericFilterBean
- 一个jar包里的网站
- 一个jar包里的网站之文件上传
- 一个jar包里的网站之返回对媒体类型
- Spring和ThreadLocal
- Spring Boot 开发微服务
- Spring AOP动态代理-切面
- 使用MVC微信支付返回get_brand_wcpay_request:fail
- Spring整合Quartz(JobDetailBean方式)
- Spring整合Quartz(JobDetailBean方式)
- C# MVC模式下商品抽奖功能实现
- Zend的MVC机制使用分析(二)
- ASP.NET MVC 4 捆绑和缩小实例介绍
- asp.net mvc实现简单的实时消息推送
- ASP.NET Mvc开发之查询数据