Learning springboot notes (three) configuration springmvc

springboot default is configured SpringMVC, so if you have previous experience using SpringMVC, you can use it directly here, but the default configuration is often difficult to meet the needs of use So how do you implement SpringMVC with personalized configuration in springboot? First, the configuration view resolver Sometimes we need to specify which URL corresponds to which page to jump to, this time you need a view resolver, the configuration code is as follows

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

@Configuration The role of this annotation is to declare this class is a configuration class, and add this bean to In the container WebMvcConfigurer this interface, springboot automatically configures the SpringMVC interface, we need to implement this interface when writing our own SpringMVC configuration class (not to implement this interface before springboot2.0, but to inherit the WebMvcConfigurerAdapter class, but in springboot2 After .0 this class is marked as not recommended, because the Java version after springboot2.0 started as Java8, and a very important feature of Java8 is that the interface can have its own default method, so the WebMvcConfigurerAdapter class is no longer needed. ) The method addViewControllers, this method is to add the corresponding relationship between the URL and the view to the view resolver. The parameters of the registry.addViewController are the URL, the registry.addViewController("url").setViewName("index") parameter is the view name, springboot The default view suffix name is html. You can configure the suffix name of the view by configuring the "spring.mvc.view.suffix" attribute in the application.properties file.

二. Configure the interceptor. When configuring the interceptor, we also need to write an interceptor, and then register the interceptor in a configuration class. The interceptor implements the HandleInterceptor interface. For example, if we want to intercept the URL and determine whether it is currently logged in, then we can implement the preHandle method. The code of the interceptor is as follows:

public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if( user == null){
            request.setAttribute("msg","Please login first");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }
        return true;
    }
}

Then write a configuration class registration interceptor

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/","/index.html","/login","/asserts/**","/webjars/**");
    }
}

addPathPatterns parameter is the URL to be intercepted, /** means to intercept all URLs, excludePathPatterns parameters are not intercepted URLs Third, configure the filter Filter code

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("FilterProcessing...");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

then register filter

@Configuration
public class MyServletConfig {
    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new MyFilter());
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return filterRegistrationBean;
    }
}

四, configure listener The listener code

public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("contextInitialized...web starts ");
    }@Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("contextDestroyed...web destroy ");
    }
}

Register listener

@Configuration
public class MyServletConfig {
    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean<MyListener> myListenerServletListenerRegistrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return myListenerServletListenerRegistrationBean;
    }

}