token验证,如果验证失败,抛出自定义异常,返回结果固定格式
Posted jeanfear
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了token验证,如果验证失败,抛出自定义异常,返回结果固定格式相关的知识,希望对你有一定的参考价值。
spring-mvc.xml
<!-- json转换器 --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" id="jsonMessageConverter"> </bean> <!-- 统一异常处理类,需要在web.xml中将默认的异常处理器关闭 --> <bean class="com.xxx.common.fitter.TokenExceptionResolver" id="handlerExceptionResolver"> <!-- 注入一个json转换器 --> <property name="jsonMessageConverter" ref="jsonMessageConverter"> </property></bean>
切面类
只是满足条件后,抛出异常
throw new TokenException("无权限");
TokenExceptionResolver类
import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import com.xxx.common.bean.JsonResultBean; import com.xxx.common.util.EifiniConstant; import com.xxx.common.exception.TokenException; public class TokenExceptionResolver implements HandlerExceptionResolver{ // json转换器 // 将异常信息转json private HttpMessageConverter<JsonResultBean> jsonMessageConverter; public HttpMessageConverter<JsonResultBean> getJsonMessageConverter() { return jsonMessageConverter; } //依赖注入三种方式之一setter注入 public void setJsonMessageConverter( HttpMessageConverter<JsonResultBean> jsonMessageConverter) { this.jsonMessageConverter = jsonMessageConverter; } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { TokenException tokenException; if(ex instanceof TokenException){ tokenException = (TokenException)ex; // 异常信息解析 HttpOutputMessage outputMessage = new ServletServerHttpResponse(response); try { //将exceptionResultInfo对象转成json输出,这里使用spring异常处理的工具 jsonMessageConverter.write(new JsonResultBean(EifiniConstant.ERROR,tokenException.getMessage()), MediaType.APPLICATION_JSON, outputMessage); } catch (HttpMessageNotWritableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ // tokenException = new TokenException("未知错误"); } return new ModelAndView(); } }
以上是关于token验证,如果验证失败,抛出自定义异常,返回结果固定格式的主要内容,如果未能解决你的问题,请参考以下文章