Spring MVC常见面试题

Spring MVC简介

Spring MVC框架是以请求为驱动,围绕Servlet设计,将请求发给控制器,然后通过模型对象,分派器来展示请求结果视图。简单来说,Spring MVC整合了前端请求的处理及响应。

Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

Spring MVC优缺点

Spring MVC具有以下优点:

(1) 可以支持各种视图技术,而不仅仅局限于JSP。

(2) 可以和 Spring 框架无缝集成,这是其它 Web 框架所不具备的。

(3) 清晰的角色分配:前端控制器(DispatcherServlet),请求处理器映射(HandlerMapping),处理器适配器(HandlerAdapter),视图解析器(ViewResolver)。

(4) 支持各种请求资源的映射策略,支持RESTful 编程风格的请求。

(5) 采用了灵活的配置方法,可以通过XML配置或注解的方式实现。

(6) Spring MVC中的Controller类是POJO(纯Java对象),它们的测试很容易,可以用JUnit等测试框架进行测试。

(7) 可以与其他框架集成,如OpenAPI(Swagger),可以为API文档和开发者交互提供支持。

Spring MVC也存在以下缺点:

(1) Spring MVC 与 Servlet API 耦合严重,难以脱离容器独立运行。

(2) 与其他框架相比,Spring MVC的学习曲线相对较陡峭,需要花费一定的时间学习和理解其工作原理和机制。

Spring MVC执行流程简介

Spring MVC执行流程如下:

(1) 用户通过浏览器将HTTP请求发送到前端控制器 DispatcherServlet;

(2) DispatcherServlet 收到请求后,调用处理器映射器HandlerMapping。HandlerMapping根据请求url找到具体的处理器 ,生成处理器执行链HandlerExecutionChain(包括处理器对象和处理器拦截器),并返回给DispatcherServlet。也就是说,uri和controller的映射是统一放在HandlerMapping中。

(3) DispatcherServlet根据处理器Handler获取处理器适配器HandlerAdapter。

(4) HandlerAdapter处理一系列的操作,如:参数封装,数据格式转换,数据验证等操作。Spring 中的处理器的实现多变,比如用户的处理器可以实现 Controller 接口或者 HttpRequestHandler 接口,也可以用 @RequestMapping 注解将方法作为一个处理器等,这就导致 Spring MVC 无法直接执行这个处理器。所以这里需要一个处理器适配器,由它去执行处理器。简言之,因为Handler格式不固定的,所以在处理请求时需要HandlerAdapter做适配 。然后,HandlerAdapter调用Handler。需要说明的是,这里的Handler就是Controller。

(5) HandlerAdapter回去Handler执行结果并返回ModelAndView 给DispatcherServlet。

(6) DispatcherServlet将ModelAndView传给ViewReslover视图解析器。ViewReslover解析后返回具体View

(7) DispatcherServlet对View进行渲染视图(即将模型数据model填充至视图中)。

(8) View向浏览器返回HTTP响应。

DisPatcherServlet 前端控制器

Spring MVC核心组件。用户在浏览器输入url发起请求后,首先会到达DisPatcherServlet,由它来调用其他组件来配合工作的完成。DisPatcherServlet的存在大大降低了组件之间的耦合性。

HandlerMapping 处理器映射器

记录url与Handler的映射,方式有注解、XML配置等。

HandlerAdapter 处理器适配器

通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

HandLer 处理器

也称控制器(就是日常开发的Controller,也即业务代码)。对用户的请求进行处理。Spring用一个非常抽象的方式实现了一个控制层,允许用户创建多种用途的控制器。

注意,Handler是单例模式,所以在多线程访问的时候,可能存在线程安全问题。注意,不建议使用多例模式,因为随着请求的增加,会频繁的创建对象。对于可能存在的多线程安全问题,尽量在设计的时候,将控制器定义成无状态的。如果确实需要维持状态,推荐使用ThreadLocal隔离不同线程。

ViewResolver 视图解析器

ViewResolver负责解析view视图,并进行渲染(将Model数据填充到View),将处理结果通过页面展示给用户看。

View 视图

View是一个接口,实现类支持不同的View类型(JSP、Freemarker等)。一般情况下需要通过页面标签或者页面模板技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

过滤器(Filter)

Spring Boot中过滤器是基于 Servlet 过滤器实现。Servlet 过滤器是可用于 Servlet 编程的 Java 类,有以下目的:

(1) 在客户端的请求访问后端资源之前,拦截这些请求。

(2) 在服务器的响应发送回客户端之前,处理这些响应。

Filter是在Servlet 2.3之后增加的新功能。过滤器是以一种组件的形式绑定到Web应用程序当中,当存在多个过滤器时,过滤器采用了"链式"方式处理。

Spring Boot中使用过滤器

过滤器一般用于完成通用的操作,如:登录验证、统一编码处理、敏感字符的过滤等。

(1) 实现Filter接口

java 复制代码
/**
 * @Author: courage007
 */
public class CustomFilter implements Filter {
    private String url;
    /**
     * 可以初始化Filter在web.xml里面配置的初始化参数
     * filter对象只会创建一次,init方法也只会执行一次。
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.url = filterConfig.getInitParameter("URL");
        System.out.println("init() method. URL is: " + this.url);
    }

    /**
     * 每一次请求资源时,url匹配后会执行。
     * 主要的业务代码编写方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("before doFilter() method");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("after doFilter() method");
    }

    /**
     * 在销毁Filter时自动调用  
     * 如果服务器是正常关闭,则会执行destroy方法。只执行一次。  
     * 注意,不是方法调用完毕后执行
     */
    @Override
    public void destroy() {
        System.out.println("destroy() method" );
    }
}

(2) 注册过滤器到Spring容器

完成过滤器的定义后,接下来就是将过滤器自动注入到Spring容器中。

两种实现方式:(a) 使用@WebFilter注解+@ServletComponentScan注解;(b)实例化FilterRegistrationBean。

  • (a) 使用@WebFilter注解 + @ServletComponentScan注解
    首先使用@WebFilter注解标注过滤器实现。其中urlPatterns用于指明过滤器针对的url。如果一个url上存在多个过滤器,还需使用指定过滤器的优先级(使用@Order注解、实现Ordered接口、配置文件指定优先级等)
java 复制代码
/**
 * @Author: courage007
 */
@Order(1)
@WebFilter(filterName = "customFilter",
        urlPatterns = "/*" ,
        initParams = { @WebInitParam(name = "URL", value = "http://localhost:8080")})
public class CustomFilter implements Filter {
    // 实现
}

然后,添加@ServletComponentScan注解。这样在启动的过程中,会自动扫描使用@WebFiter标注的类到Spring容器。

java 复制代码
@SpringBootApplication
@ServletComponentScan
public class SpringDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }
}
  • (b) 实例化FilterRegistrationBean
    FilterRegistrationBean 是Spring Boot提供的接口。推荐使用这种方式使用过滤器。相比第一种方式,这种方式将过滤器的使用与过滤器的定义分离,有利于更好复用过滤器。
java 复制代码
/**
 * @Author: courage007
 */
@Configuration
public class WebConfig {
    //Register Filter
    @Bean
    public FilterRegistrationBean<CustomFilterRegisteredBySpringBootBean> registerCustomFilter() {
        FilterRegistrationBean<CustomFilterRegisteredBySpringBootBean> filterRegBean = new FilterRegistrationBean<>();
        filterRegBean.setFilter(new CustomFilterRegisteredBySpringBootBean());
        // 指定匹配url
        filterRegBean.addUrlPatterns("/*");
        // 指定顺序
        filterRegBean.setOrder(2);
        return filterRegBean;
    }
}
使用过滤器处理CORS问题

过滤器支持处理CORS(Cross-Origin Resource Sharing,跨源资源共享)问题,示例代码如下:

java 复制代码
@Component
public class CORSFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
        throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Credentials", "true");
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH");
            res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
            if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
                response.getWriter().println("ok");
                return;
            }
            chain.doFilter(request, response);
        }

        @Override 
        public void destroy() {
        
        }

        @Override 
        public void init(FilterConfig filterConfig) throws ServletException {
            
        }
}

需要说明的是,过滤器只是处理跨域访问问题的一种方式,Spring MVC也提供了@CrossOrigin注解等方式,还需根据自己的业务场景合理选择。

拦截器(Interceptor)

拦截器依赖于Spring MVC框架。在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。一般简单的功能又是通用的,且每个请求都要去处理的,比如判断token是否失效可以使用Spring MVC的HandlerInterceptor。对于复杂的,比如缓存,需要高度自定义的就用Spring AOP方式处理。对于Service层更多用Spring AOP,controller层有必要用到request和response时,可以用拦截器。

拦截器(Interceptor)和过滤器(Filter)都是AOP编程思想的实现,主要的不同有以下几点:

(1) 实现原理不同。

Interceptor是基于java的反射机制的,而Filter是基于函数回调。

(2) 使用规范不同。

Filter是Servlet规范规定的,是Servlet容器支持的。而Interceptor是Spring框架规范的,是Spring容器支持的。

(3) 作用范围不同。

Interceptor只能对Controller请求起作用,而Filter则可以对几乎所有的请求起作用。如对其他的一些比如直接访问静态资源的请求,则没办法进行拦截处理。Interceptor可以访问Controller上下文、值栈里的对象,而Filter不能访问。在Controller的生命周期中,Interceptor可以多次被调用,而Filter只能在容器初始化时被调用一次。

(4) 使用的资源不同。

Interceptor也是一个Spring组件,归Spring管理,因此能使用Spring里的任何资源、对象,如Service对象、数据源、事务管理等。而Filter则不能。

(5) 使用深度不同。

Filter只在Servlet前后起作用。而Interceptor能够深入到方法前后、抛出异常前后等。

Spring中开发优先使用拦截器。如果拦截器无法满足需求(如非Controller场景下方法调用),则再尝试使用过滤器。

Spring MVC中拦截器的使用

Spring MVC中的Interceptor拦截请求是通过HandlerInterceptor来实现的。在Spring MVC中定义一个拦截器主要有两种方式,第一种方式是要实现HandlerInterceptor接口,或者是其它实现了HandlerInterceptor接口的类,比如HandlerInterceptorAdapter。第二种方式是实现WebRequestInterceptor接口,或者其它实现了WebRequestInterceptor的类。这里以HandlerInterceptor接口为例,介绍如下实现拦截器。

(1) 实现Interceptor接口

示例代码如下:

java 复制代码
/**
 * 自定义拦截器
 *
 * @Author: courage007
 */
public class CustomInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("previous handle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post handle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
        System.out.println("after Completion");
    }
}

自定义拦截器实现了HandlerInterceptor接口。该接口声明了三个方法:

(a) preHandle:预处理回调方法,该方法会在控制器方法前执行。其返回值表示是否中断后续操作。当其返回值为true时,表示继续向下执行(如调用下一个拦截器或处理器);当其返回值为false时,会中断后续的所有操作(包括调用下一个拦截器和控制器类中的方法执行等),此时需要通过response来产生响应。

(b) postHandle:后处理回调方法,该方法会在控制器方法调用之后。可以通过此方法对请求域中的模型和视图做出进一步的修改。在该阶段可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。

© afterCompletion:该方法会在整个请求完成,即视图渲染结束之后执行。整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion。

(2) 注册已实现Interceptor接口

示例代码如下:

java 复制代码
/**
 * 实现WebMvcConfigurer接口
 *
 * @Author: courage007
 */
@Configuration
public class CustomInterceptorConfig implements WebMvcConfigurer {  
    /**
     * 重写添加拦截器方法
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor())
                .addPathPatterns("/**")
                .order(1);//指定执行顺序,数值越小越优先
    }
}

多个拦截器的处理

Spring MVC支持在一个uri中定义多个拦截器。多个拦截器使用使用order接口设置优先级。多个拦截器的执行顺序基于"职责链模式"执行。以有两个拦截器为例,拦截器中方法的先后执行顺序如下:

监听器(Listener)

监听器就是一个实现特定接口的程序,这个程序专门用于监听一个对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行。

监听器使用

在Spring Boot 应用中,监听器既可以使用Servlet容器的,也可以Spring的。

Servlet提供监听器使用

Servlet中监听器是在application,session,request三个对象创建、销毁或往其中添加修改删除属性时自动执行代码的功能组件。其中application对象相关的有ServletContextListener和ServletContextAttributeListener,session对象相关的有HttpSessionListener和HttpSessionAttributeListener,request对象相关的有ServletRequestListener和ServletRequestAttributeListener。这里以ServletContextListener为例,说明下Servlet监听器的使用。

  • (1) 实现ServletContextListener接口

除了实现ServletContextListener接口外,还需使用@WebListener标注类。

java 复制代码
/**
 * @Author: courage007
 */
@WebListener
public class CustomServletRequestListener implements ServletRequestListener {
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("---------------------------->请求创建");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("---------------------------->请求销毁");
    }
}
  • (2) 使用@ServletComponentScan注解

在Spring Boot启动使用或在一个配置类上添加@ServletComponentScan注解,这样就可以将@WebListener的Bean自动添加到Spring容器中。

Spring 提供监听器使用

Spring Boot事件监听的流程如下:(1) 自定义事件,一般是继承ApplicationEvent抽象类;(2)定义事件监听器,一般是实现ApplicationListener接口;(3) 注册监听器,启动的时候,需要把监听器加入到spring容器中;(4)发布事件。

  • (1) 自定义事件
    创建一个自定义事件时,只需要继承ApplicationEvent抽象类。
java 复制代码
/**
 * @Author: courage007
 */
public class CustomSpringApplicationEvent extends ApplicationEvent {
    public CustomSpringApplicationEvent(Object source) {
        super(source);
    }
}
  • (2) 定义事件监听器并指定事件
    定义事件监听器用于响应绑定的事件。自定义事件监听器实现ApplicationListener。
java 复制代码
/**
 * @Author: courage007
 */
public class CustomSpringApplicationListener implements ApplicationListener<CustomSpringApplicationEvent> {
    @Override
    public void onApplicationEvent(CustomSpringApplicationEvent customSpringApplicationEvent) {
        System.out.println("======spring监听自定义的事件======");
        System.out.println(customSpringApplicationEvent.getClass());
    }
}
  • (3) 注册事件监听器
    如果需要事件监听器生效,还需将事件监听器注册到Spring中。常见的事件监听器的注册方法有四种:(a) SpringApplication.addListeners 添加监听器;(b) 把监听器纳入到spring容器中管理;© 使用context.listener.classes配置项配置;(d) 使用@EventListener注解。
    (a) SpringApplication.addListeners 添加监听器
java 复制代码
@SpringBootApplication
@ServletComponentScan
public class SpringDemoApplication {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringDemoApplication.class);
        // 配置事件监听器
        application.addListeners(new CustomSpringApplicationListener());
        ConfigurableApplicationContext context = application.run(args);
    }
}

(b) 把监听器纳入到Spring容器中管理

如使用@Component注解将监听器注册到Spring容器中。

java 复制代码
@Component
public class CustomSpringApplicationListener implements ApplicationListener<CustomSpringApplicationEvent> {
    @Override
    public void onApplicationEvent(CustomSpringApplicationEvent customSpringApplicationEvent) {
        System.out.println("======spring监听自定义的事件======");
        System.out.println(customSpringApplicationEvent.getClass());
    }
}

© 使用context.listener.classes配置项

在配置文件(application.properties)中添加自定义事件监听器。

properties 复制代码
context.listener.classes=com.github.courage007.springdemo.listener.CustomSpringApplicationListener

(d) 使用@EventListener注解

还可以在方法上面加入@EventListener注解,且该类需要纳入到spring容器中管理。

java 复制代码
/**
 * @Author: courage007
 */
@Component
public class AnnotationEventListener {
    @EventListener
    public void registerCustomSpringApplicationEvent(CustomSpringApplicationEvent customSpringApplicationEvent) {
        System.out.println(customSpringApplicationEvent.getClass());
    }
}
  • (4) 发布事件
    发布事件时,既可直接使用ConfigurableApplicationContext实例发布,也可以使用ApplicationContext实例或ApplicationEventPublisher实例发布。
java 复制代码
@SpringBootApplication
@ServletComponentScan
public class SpringDemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(SpringDemoApplication.class, args);
        // 发布事件
        context.publishEvent(new CustomSpringApplicationEvent(new Object()));
    }
}
多个监听器执行顺序

一个事件上可能包含多个监听器,有时需要保证这些监听器的执行顺序。可以使用 @Order注解来标记事件的监听执行顺序,对于异步的监听器,只保证按顺序将监听器丢入进线程池。

监听器异步执行

默认情况,监听器是同步的,也就是说只有当监听器的处理方法执行完成后,才会执行剩下的步骤。对于耗时很长且不影响后续业务的方法(如:将事件记录到数据库中),可以使用异步的方式处理事件。

java 复制代码
@Async
@EventListener
public void ApiEventListener(ApiEvent event){
  System.out.println("收到Api调用事件,内容 {} ", event.getContent());
}

使用 @Async 标记事件处理器为异步方法。默认情况下,Spring没有开启Async,使用 @EnableAsync 注解使 @Async 有效。如果默认的线程策略不能满足需求,还需指定线程池。

Spring MVC使用

Spring MVC的控制器(Handler)是不是单例模式?

是单例模式,所以在多线程访问的时候,可能存在线程安全问题。注意,不建议使用多例模式,因为随着请求的增加,会频繁的创建对象。对于可能存在的多线程安全问题,尽量在设计的时候,将控制器定义成无状态的。如果确实需要维持状态,推荐使用ThreadLocal隔离不同线程。

Spring MVC常用的注解有哪些?

@Controller和@RestController

在Spring MVC 中可以使用@Controller标记一个类的方式,完成Controller的定义。此外,为了简化使用,还可以使用@RestController注解。@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

Controller注解下,Controller中的方法可以返回JSP、html、JSON、XML等各种类型的数据,使用@ResponseBody注解后,无法返回JSP、HTML等视图相关的数据,只能返回JSON、XML等视图无关的数据。

简单来说,如果需要返回JSON、XML等视图无关的数据,如果使用@Controller注解,还需额外补充@ResponseBody注解,如果使用@RestController注解,则无需额外的操作。

@RestController注解定义如下:

java 复制代码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

可以看到@RestController是一个组合注解,组合了@Controller注解和@ResponseBody注解。

@RequestMapping 和 @GetMapping和@PostMapping和@PutMapping和@DeleteMapping和@PatchMapping

@RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

RequestMapping注解有六个属性,下面分成三类进行说明:

(1) value, method

value:指定请求的实际地址,指定的地址可以是URI Template 模式。

method:指定请求的method类型,GET、POST、PUT、DELETE等。

(2) consumes,produces

consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html。

produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。

(3) params,headers

params:指定request中必须包含某些参数值,才让该方法处理该请求。

headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。

@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping 都是在 @RequestMapping 中使用 method 属性来声明 HTTP 请求所使用的方法类型。对应关系如下:
在日常的开发中,推荐使用@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping等注解,除非无法满足需要,再使用@RequestMapping注解。

@PathVariable和@RequestParam

@PathVariable用于将URL中的值绑定到参数上。具体来说,首先在@RequestMapping的value中使用URI template({变量名}),然后在@RequestMapping注解方法的需要绑定的参数前,使用@PathVariable指定变量名(如果变量名和参数名一致也可以不指定),这样URL中的值就绑定到参数上。使用示例如下:

java 复制代码
@RestController
@RequestMapping("/testPathVariable")
public class TestPathVariable {
    /*
     * URI模板指定了一个变量名为id的变量,当控制器处理请求时会将 id 替换为正确的值
     *
     * 若请求为 testPathVariable/user/29,则uid=29,输出29
     *
     * */
    @GetMapping("/user/{id}")
    public void testPathVariable(@PathVariable("id") String userId) {
        System.out.println(userId);
        return;
    }
}

@RequestParam注解用于将指定的请求参数赋值给方法中的形参。有三个属性:

(1) value:请求参数名

(2) required:是否必需,默认为 true,即 请求中必须包含该参数,如果没有包含,将会抛出异常(可选配置)

(3) defaultValue:默认值,如果设置了该值,required 将自动设为 false,即使required设置为true(可选配置)

使用示例如下:

java 复制代码
@RestController
@RequestMapping("/testRequestParam")
public class TestRequestParam {
    @GetMapping("/user")
    public void testRequestParam(@RequestParam(value="name") String userName) {
        System.out.println(username);
        return;
    }
}

这个时候,如果请求"/testRequestParam/user?name=foo",就可将请求参数赋值给方法中的形参。

@ResponseBody

@ResponseBody 注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

注意,这里返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

@ControllerAdvice和@ExceptionHandler

Spring 提供了使用@ControllerAdvice处理异常的方法。开发者可以通过实现一个 ControlerAdvice 类,来处理控制器类抛出的所有异常。其中@ExceptionHandler用来指定具体的异常类型。使用示例如下:

java 复制代码
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView customException(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", e.getMessage());
        mv.setViewName("myerror");
        return mv;
    }
}

参考

https://docs.spring.io/spring-framework/docs/4.2.4.RELEASE/spring-framework-reference/html/mvc.html Spring Web MVC framework
https://www.w3schools.cn/springmvc/index.html Spring MVC 教程
https://docs.spring.io/spring-framework/reference/web/webmvc.html Spring Web MVC
https://blog.csdn.net/thinkwon/article/details/104397427 Spring MVC面试题

https://www.w3cschool.cn/servlet/servlet-intro.html Servlet学习网站
https://blog.csdn.net/weixin_65950231/article/details/130499706 深入了解SpringMVC框架,探究其优缺点、作用以及使用方法
https://blog.csdn.net/weixin_43888891/article/details/108479214 什么是SpringMVC,SpringMVC有什么优缺点
https://blog.csdn.net/fuzhongmin05/article/details/81585672 从MVC到前后端分离
https://www.jianshu.com/p/8a20c547e245 SpringMVC执行流程及工作原理
https://www.cnblogs.com/lifullmoon/p/14137467.html Spring MVC 源码分析 - HandlerAdapter 组件(一)之 HandlerAdapter
https://www.cnblogs.com/shuaifing/p/8119664.html @Controller和@RestController的区别?
https://zhuanlan.zhihu.com/p/168017369 说说Spring中的 @RestController 和 @Controller
https://blog.csdn.net/demo_yo/article/details/123608034 @RequestMapping 注解使用技巧(完整详解)
https://www.cnblogs.com/FFFFF/p/4624140.html SpringMVC(三)@PathVariable
https://www.cnblogs.com/tomingto/p/11377138.html @RequestParam注解的详细介绍
https://blog.csdn.net/qq_44543508/article/details/101026720 @RequestParam注解详细使用
https://www.jianshu.com/p/2dbb585ffb1c Spring Boot使用过滤器Filter
https://www.jdon.com/springboot/spring-filter.html
https://www.cnblogs.com/jobbible/p/17546547.html SpringBoot 如何处理 CORS 跨域?
https://www.jianshu.com/p/2dbb585ffb1c Spring Boot使用过滤器Filter
https://blog.csdn.net/heweimingming/article/details/79993591 spring boot 过滤器、拦截器的区别与使用
https://blog.csdn.net/cold___play/article/details/103295685 SpringMVC--拦截器的两种实现方式(HandlerInterceptor、WebRequestInterceptor)及拦截器的执行流程(单个、多个)
https://my.oschina.net/centychen/blog/3018007 SpringBoot 入坑指南之六:使用过滤器或拦截器
http://www.51gjie.com/javaweb/872.html Servlet Listener监听器详解(原理)
https://www.jianshu.com/p/5f57f2aa5e2c Springboot事件监听
https://blog.csdn.net/m0_38075425/article/details/81164501 springboot的监听器Listener
https://www.jianshu.com/p/5f57f2aa5e2c Springboot事件监听
https://blog.csdn.net/weixin_41490593/article/details/97132317 springboot中监听器使用
https://www.jianshu.com/p/dcd956169910 Spring事件监听
https://blog.csdn.net/qq_30211955/article/details/86709873 Spring Boot监听事件同步和异步使用
https://my.oschina.net/u/3245438/blog/2961234 SpringBoot > 启动异步事件监听机制

相关推荐
IT毕设梦工厂8 分钟前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius43 分钟前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
七夜zippoe1 小时前
分布式系统实战经验
java·分布式
是梦终空1 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
落落落sss1 小时前
sharding-jdbc分库分表
android·java·开发语言·数据库·servlet·oracle
码爸1 小时前
flink doris批量sink
java·前端·flink
Monodye2 小时前
【Java】网络编程:TCP_IP协议详解(IP协议数据报文及如何解决IPv4不够的状况)
java·网络·数据结构·算法·系统架构
一丝晨光2 小时前
逻辑运算符
java·c++·python·kotlin·c#·c·逻辑运算符
无名指的等待7123 小时前
SpringBoot中使用ElasticSearch
java·spring boot·后端
Tatakai253 小时前
Mybatis Plus分页查询返回total为0问题
java·spring·bug·mybatis