版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou920786312/article/details/89420941
代码写有执行顺序
@ControllerAdvice //1控制器建言,组合注解,含@Component
public class ExceptionHandlerAdvice {
@ExceptionHandler(value = Exception.class)//异常全局处理
// 在@RequestMapping执行后执行
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView modelAndView = new ModelAndView("error");// error页面
modelAndView.addObject("errorMessage", exception.getMessage());
return modelAndView;
}
@ModelAttribute //所有使用@RequestMapping注解的都可以获取该键值对,且在@RequestMapping执行前执行
public void addAttributes(Model model) {
model.addAttribute("msg", "AA"); //3
}
@InitBinder //定制WebDataBinder,在在@RequestMapping执行前执行,在上面addAttributes后执行
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("id"); //5
}
}
-------------------------------
@Configuration
@EnableWebMvc// 开启Mvc
@EnableScheduling
@ComponentScan("com.wisely.highlight_springmvc4")
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {//视图解析器
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {//静态资源
registry.addResourceHandler("/assets/**").addResourceLocations(
"classpath:/assets/");// 3
}
}
--------------------------
public class WebInitializer implements WebApplicationInitializer {//1
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MyMvcConfig.class);
ctx.setServletContext(servletContext); //2
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); //3
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(true);//1
}
}
-------------------------
public class DemoObj {
private Long id;
private String name;
public DemoObj() {
super();
}
public DemoObj(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
----------------------
@Controller//1
public class HelloController {
@RequestMapping("/index")
public String getSomething(@ModelAttribute("msg") String msg, DemoObj obj){//1
throw new IllegalArgumentException("非常抱歉,参数有误:"+ msg);
}
}