github代码:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service
全部内容:
1.拦截器配置
2.全局的异常捕捉
1.拦截器配置
1.1 重写WebMvcConfigurerAdapter中的addInterceptors方法自定义拦截器
package com.kawa.interceptor; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class SPBWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter{
/**
* 拦截器的配置规则
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 添加拦截规则
// excludePathPatterns 排除拦截
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/register","/login");
super.addInterceptors(registry);
}
}
1.2 自定义拦截器
package com.kawa.interceptor; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; /**
*
* @author Administrator
*
*
*/
public class LoginInterceptor implements HandlerInterceptor{ private final static Logger logger = Logger.getLogger(LoginInterceptor.class); @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
throws Exception { } @Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception { } @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("---------------------------拦截器-----------------------");
return true;
} }
2 全局异常捕捉
package com.kawa.config; import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; /**
* 全局异常捕捉
* @author Administrator
*
*/
@ControllerAdvice
public class GlobaExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String,String>> globaException(HttpServletRequest request,Exception exception){
Map<String,String> map = new HashMap<>();
map.put("code","500");
map.put("result","error");
map.put("message","网络高峰期,等待红绿灯!");
return new ResponseEntity<Map<String,String>>(map, HttpStatus.OK);
}
}