springboot实现自定义mvc组件
如果你想实现一些定制化功能,只需要写这个组件,然后将它交给springboot管理,springboot会给我们自动装配
以下是spring官方文档解释
由官方文档可知,想要自定义组件,需要实现以下步骤
- 写一个配置类,加上@Configuration注解
- 实现WebMvcConfigurer接口
- 不添加@EnableWebMvc注解
示例:自定义拦截器和视图解析器
-
自定义拦截器
package com.yl.handler; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyHandler implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getParameter("username").equals("yl")){ return true; }else { return false; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
-
注册拦截器和视图解析器
package com.yl.configration; import com.yl.handler.MyHandler; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { /** * 添加拦截器,springboot已经做好了静态资源映射 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyHandler()).addPathPatterns("/**").excludePathPatterns("/register"); } /** * 添加视图解析器 * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index.html").setViewName("index"); } }