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(); } }
原文地址:https://www.cnblogs.com/jeanfear/p/9167564.html
时间: 2024-10-09 04:24:49