SpringMvc - full annotation development

SpringMvc - full annotation development

Use configuration classes instead of web.xml, SpringMvc.xml, Spring.xml.

first

Create a new module, introduce dependency, specify the packaging method war, create webapp directory and WEB-INF directory.

then

Create a WebConfig class, inherit the AbstractAnnotationConfigDispatcherServletInitializer class, and implement the methods inside

In WebConfig

//This class is used to replace web.xml and inherit AbstractAnnotationConfigDispatcherServletInitializer.
//All the work done in the web.xml file is done in this class. Configure the character encoding filter, request converter, dispatcher servlet, and declare the SpringMvc configuration class
public class TestWebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
​
​
    /**
     * This method is used to return an array of class types of Spring's configuration classes. Multiple can be configured
     * @return This method is used to return an array of class types of Spring's configuration classes. Multiple can be configured
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{
                TestSpringConfig.class
        };
    }
​
    /**
     * This method returns an array of class types of the configuration class of SpringMvc
     * @return This method returns an array of class types of the configuration class of SpringMvc
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{
                TestSpringMvcConfig.class
        };
    }
​
​
    /**
     *
     * @return The returned path is the path of the DispatchServlet, which is the path of the management request
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

In SpringMvcConfig

Use annotation @ configuration to declare a class as a configuration class, start annotation scanning, set the scanning range, and establish controller, Interceptor and view

You have a lot of work to do in the configuration class. Therefore, after being declared as a configuration class, implement the interface WebMvcConfigurer. Many methods are provided in the interface to realize the corresponding functions.

Using @ EnableWebMvc annotation is to turn on mvc annotation driver

View Parser - first create a method whose return value is ITemplateResolver. In it, set values for view prefix, suffix, encoding format and text format attributes through ServletContextTemplateResolver. If you find that you want a WebApplicationContext, create a new one. Then set the value and return the object. Use the @ bean tag to identify and put the returned object into the IOC container. Referring to the configuration cluster in the configuration file, you need a method to return the value of SpringTemplateEngine. Create this method and use the @ bean ID to inject the bean object just returned as a formal parameter. SpringMvc will automatically assemble according to the type. If the type is different from the bean object of the object just returned, it will say that AutoWire has not found the corresponding type. According to the code configuring the view parser in the configuration file, you know that you need to assign a value to the TemplateResolve property, create a SpringTemplateEngine object, and call the set method. Take the formal parameter bean as the value of TemplateResolve. Finally, create a method with ViewResolver as the return value and identify @ bean. Take the return bean object of the method with SpringTemplateEngine as the formal parameter, create a ThymeleafViewResolver object with reference to the configuration file code in the method, call the set method to set the value and return the ThymeleafViewResolver object.

Other functions can be realized through the methods provided by the interface, as shown below.

/**
 * SpringMvc Configure the work to be done in the class
 * Start component scanning, set view parser, set view controller, start mvc annotation driver, register bean s required for file upload service
 * Set the format and character code of the response message, set the interceptor, register the bean for exception handling, and enable static resource access
 */
@Configuration
@ComponentScan("xlw.com.last")
//This annotation can open the annotation driver of Mvc
@EnableWebMvc
public class TestSpringMvcConfig implements WebMvcConfigurer {
​
​
    /**
     * Configure the format and character coding of response message
     * @param converters Put the return result of the method whose return type is StringHttpMessageConverter [return result of processing response output] into the
     *                   List<HttpMessageConverter<?>>In the collection.
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter = new StringHttpMessageConverter();
        converters.add(converter());
    }
​
    /**
     * Process the returned results using the @ ResponseBody annotation
     * @return Response processing results
     */
    @Bean
    public StringHttpMessageConverter converter() {
//         First, create the object of StringHttpMessageConverter to arrange the format and coding of response message
        StringHttpMessageConverter converter = new StringHttpMessageConverter();
//         When calling the set method, it is found that a non empty parameter of list < mediatype > type is required. Create it
//         When adding content to the list set, enter the MediaType source code. There are parameter construction methods and constants specified in the static code block. Specify the response format and coding format through parameter prompts
        List<MediaType> mediaTypeList = new ArrayList<MediaType>();
        MediaType mediaType = new MediaType(new MediaType(TEXT_HTML,Charset.forName("UTF-8")));
        mediaTypeList.add(mediaType);
        converter.setSupportedMediaTypes(mediaTypeList);
//         Set the default encoding format here.
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        return converter;
    }
​
    /**
     * Enable static resource access
     *
     * @param configurer Set the default servlet to handle static resources
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
​
    /**
     * Set interceptor
     *
     * @param registry Set interceptor and interception path
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        FirstInterceptor interceptor = new FirstInterceptor();
//         Add the interceptor object written by yourself and set the interception path
        registry.addInterceptor(interceptor).addPathPatterns("/**");
    }
​
    /**
     * Instead of registering the bean of the exception handling class
     *
     * @param resolvers Possible errors during program execution
     */
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
//         First, create the object of SimpleMappingExceptionResolver, and then create the properties object
        SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
        Properties prop = new Properties();
//         In the spring MVC configuration file, attribute injection is performed for possible exceptions through the prop tag in the props tag, and the name of the exception is specified
        prop.setProperty("java.lang.ArithmeticException", "error");
//         Then inject the above prop into the property exception mappings, which is injected with the property tag in the configuration file of spring MVC
        simpleMappingExceptionResolver.setExceptionMappings(prop);
//         Put the error into the request field
        simpleMappingExceptionResolver.setExceptionAttribute("ex");
    }
​
    /**
     * Configure view controller
     *
     * @param registry The request path and view name of the view
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }
​
    /**
     * Configure view parser
     */
​
    //Configure build template parser
    @Bean
    public ITemplateResolver templateResolver() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContextTemplateResolver servletContextTemplateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
        servletContextTemplateResolver.setPrefix("/WEB-INF/templates/");
        servletContextTemplateResolver.setSuffix(".html");
        servletContextTemplateResolver.setTemplateMode("HTML5");
        servletContextTemplateResolver.setCharacterEncoding("UTF-8");
        return servletContextTemplateResolver;
    }
​
    //Generate a template engine and inject a template parser into the template engine
    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }
​
    //The generated view parser is not injected into the template engine
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
​
​
}

Keywords: Java Spring Spring MVC

Added by jiehuang001 on Fri, 26 Nov 2021 01:22:17 +0200