Spring MVC is fully annotated to configure the web project

  • 2020-05-10 18:08:39
  • OfStack

Starting the web project on servlet 3.0 will eliminate the need for the web.xml configuration file altogether, so the configuration in this article will only work in web containers that support servlet 3.0 and above

Use spring mvc (4.3.2. RELEASE) + thymeleaf (3.0.2. RELEASE), persistence layer using spring JdbcTemplate, PS: recommend a useful framework for JdbcTemplate encapsulation: https: / / github com/selfly/dexcoder - assistant  . Let's start with the specific configuration:

Configure spring mvc DispatcherServlet
DispatcherServlet is the core of spring mvc. Spring provides a class AbstractAnnotationConfigDispatcherServletInitializer for the quick configuration of DispatcherServlet. The specific code is as follows:

Where onStartup()   is a method in the WebApplicationInitializer interface, the user concatenates other filter and listener

getRootConfigClasses() gets the configuration class, which I understand is equivalent to the context created by applicationContext.xml

getServletConfigClasses() gets the configuration class, equivalent to the context created by mvc-servlet.xml

No comments are required on this class


package com.liulu.bank.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.nio.charset.StandardCharsets;

/**
 * User : liulu
 * Date : 2016-10-7 15:12
 */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class<?>[]{RootConfig.class};
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class<?>[]{WebConfig.class};
 }

 /**
  *  configuration DispatcherServlet  Matched path 
  * @return
  */
 @Override
 protected String[] getServletMappings() {
  return new String[]{"/"};
 }

 /**
  *  Configure others  servlet  and  filter
  *
  * @param servletContext
  * @throws ServletException
  */
 @Override
 public void onStartup(ServletContext servletContext) throws ServletException {
  FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
  encodingFilter.setInitParameter("encoding", String.valueOf(StandardCharsets.UTF_8));
  encodingFilter.setInitParameter("forceEncoding", "true");
  encodingFilter.addMappingForUrlPatterns(null, false, "/*");
 }
}

Configure applicationContext.xml, implemented by the RootConfig class


package com.liulu.bank.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * User : liulu
 * Date : 2016-10-7 15:36
 */
@Configuration
@PropertySource("classpath:config.properties") //  Import properties file 
@EnableAspectJAutoProxy //  The equivalent of  xml  In the  <aop:aspectj-autoproxy/>
@EnableTransactionManagement //  Open annotation transaction 
@ComponentScan(basePackages = {"com.liulu.lit", "com.liulu.bank"}, excludeFilters = @ComponentScan.Filter(classes = Controller.class ))
public class RootConfig {

 //  The properties in the properties file imported above will   Injected into the  Environment  In the 
 @Resource
 private Environment env;

 /**
  *  Configure the database connection pool  c3p0 . 
  * @return
  * @throws PropertyVetoException
  */
 @Bean
 public DataSource dataSource() throws PropertyVetoException {
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  dataSource.setJdbcUrl(env.getProperty("db.url"));
  dataSource.setDriverClass(env.getProperty("db.driver"));
  dataSource.setUser(env.getProperty("db.user"));
  dataSource.setPassword(env.getProperty("db.password"));
  dataSource.setMinPoolSize(Integer.valueOf(env.getProperty("pool.minPoolSize")));
  dataSource.setMaxPoolSize(Integer.valueOf(env.getProperty("pool.maxPoolSize")));
  dataSource.setAutoCommitOnClose(false);
  dataSource.setCheckoutTimeout(Integer.valueOf(env.getProperty("pool.checkoutTimeout")));
  dataSource.setAcquireRetryAttempts(2);
  return dataSource;
 }

 /**
  *  Configure the thing manager 
  * @param dataSource
  * @return
  */
 @Bean
 public PlatformTransactionManager transactionManager(DataSource dataSource) {
  return new DataSourceTransactionManager(dataSource);
 }

 @Bean
 public JdbcTemplate jdbcTemplate (DataSource dataSource) {
  return new JdbcTemplate(dataSource);
 }


}

The config.properties file is in the resources directory


# Database configuration 
db.url=jdbc:mysql://192.168.182.135:3306/bank
db.driver=com.mysql.jdbc.Driver
db.user=root
db.password=123456

# Database connection pool configuration 
# The minimum number of connections retained in the connection pool 
pool.minPoolSize=5
# The maximum number of connections left in the connection pool 
pool.maxPoolSize=30
# Gets the connection timeout 
pool.checkoutTimeout=1000


Configure servlet.xml, implemented by the WebConfig class
The Thymeleaf   template configuration is also below


package com.liulu.bank.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

import java.nio.charset.StandardCharsets;

/**
 * User : liulu
 * Date : 2016-10-7 15:16
 */
@Configuration
@EnableWebMvc //  To enable the  SpringMVC  , which is equivalent to  xml In the  <mvc:annotation-driven/>
@ComponentScan(basePackages = {"com.liulu.bank.controller", "com.liulu.lit"},
  includeFilters = @ComponentScan.Filter(classes = Controller.class),
  useDefaultFilters = false)
public class WebConfig extends WebMvcConfigurerAdapter {

 /**
  *  Set up by the  web The container handles static resources   , which is equivalent to  xml In the <mvc:default-servlet-handler/>
  */
 @Override
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }

 /**
  *  The following 3 a bean  configuration  Thymeleaf  The template 
  * @return
  */
 @Bean
 public SpringResourceTemplateResolver templateResolver() {
  SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
  templateResolver.setPrefix("/WEB-INF/templates/");
  templateResolver.setSuffix(".html");
  templateResolver.setTemplateMode(TemplateMode.HTML);
  templateResolver.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
  return templateResolver;
 }

 @Bean
 public TemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver) {
  SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  templateEngine.setTemplateResolver(templateResolver);
  return templateEngine;
 }

 @Bean
 public ViewResolver viewResolver(TemplateEngine templateEngine) {
  ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
  viewResolver.setTemplateEngine(templateEngine);
  viewResolver.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
  return viewResolver;
 }

}

Related articles: