@Service
public class AnnotationService {
@Action(name = "注解式拦截add操作,我是注解的name值")
public void add() {
System.out.println("AnnotationService的添加方法被调用了");
}
}
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg", "额外信息");
}
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
//过滤ID
webDataBinder.setDisallowedFields("id");
}
@ExceptionHandler(value = Exception.class)
public ModelAndView exception(Exception e, WebRequest request) {
//跳转到错误页面,已经不用了吧
ModelAndView m = new ModelAndView("error");
m.addObject("errorMessage", e.getMessage());
return m;
}
}
@GetMapping("/testOne2")
public String testOne2(@ModelAttribute("msg") String msg) {
System.out.println("请求到了");
throw new IllegalArgumentException("非常抱歉,参数异常。" + msg);
}
以前写的一个
@ResponseBody
@ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
public ResponseEntity<Pesponsibles> methodArgumentNotValidExceptionHandler(Exception e, BindingResult bindingResult) {
Pesponsibles p = new Pesponsibles();
// 如果没有参数异常则直接返回错误信息
if (bindingResult.hasErrors()) {
//有异常下面处理
} else {
//bindingResult没有异常,但是exception有异常
p.setDefaultMessage(e.getMessage());
return new ResponseEntity<>(p, HttpStatus.BAD_REQUEST);
}
p.setField("bindingResult错误字段");
//如果包含错误
if (bindingResult.hasErrors()) {
//获取到 所有错误
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
// 如果有参数异常,则获取default message,并返回
StringBuilder message = new StringBuilder("提示:");
//拼接 错误
fieldErrors.forEach(i -> message.append(i.getDefaultMessage()).append("!"));
p.setDefaultMessage(message.toString());
// pesponsibles.setError_msg(fieldErrors);
return new ResponseEntity<>(p, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(p, HttpStatus.BAD_REQUEST);
}
过滤器
过滤器代码
public class LogCostFilter implements Filter {
//@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("测试");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("Execute cost=" + (System.currentTimeMillis() - start));
}
@Override
public void destroy() {
}
}
配置类
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogCostFilter());
registration.addUrlPatterns("/*");
registration.setName("LogCostFilter");
registration.setOrder(1);
return registration;
}
}