在 servlet 3.0 開始web項目可以完全不需要web.xml配置文件了,所以本文的配置只在支持servlet 3.0及以上的web容器中有效 使用的是spring mvc (4.3.2.RELEASE) + thymeleaf(3.0.2.RELEASE), 持久層使用的 spring的 ...
在 servlet 3.0 開始web項目可以完全不需要web.xml配置文件了,所以本文的配置只在支持servlet 3.0及以上的web容器中有效
使用的是spring mvc (4.3.2.RELEASE) + thymeleaf(3.0.2.RELEASE), 持久層使用的 spring的 JdbcTemplate, PS:推薦一個很好用的對JdbcTemplate封裝的框架:https://github.com/selfly/dexcoder-assistant 。 下麵開始具體的配置:
配置spring mvc DispatcherServlet
DispatcherServlet 是spring mvc的核心, Spring 提供了一個快速配置DispatcherServlet的類 AbstractAnnotationConfigDispatcherServletInitializer,具體代碼如下:
其中 onStartup() 是 WebApplicationInitializer 介面中的方法,用戶配置其他的 filter 和 listener
getRootConfigClasses() 獲取配置類,我理解的相當於 applicationContext.xml 創建的上下文
getServletConfigClasses()獲取配置類,相當於 mvc-servlet.xml 創建的上下文
此類上不需要任何註解,
1 package com.liulu.bank.config; 2 3 import org.springframework.web.WebApplicationInitializer; 4 import org.springframework.web.filter.CharacterEncodingFilter; 5 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 6 7 import javax.servlet.FilterRegistration; 8 import javax.servlet.ServletContext; 9 import javax.servlet.ServletException; 10 import java.nio.charset.StandardCharsets; 11 12 /** 13 * User : liulu 14 * Date : 2016-10-7 15:12 15 */ 16 public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer { 17 18 @Override 19 protected Class<?>[] getRootConfigClasses() { 20 return new Class<?>[]{RootConfig.class}; 21 } 22 23 @Override 24 protected Class<?>[] getServletConfigClasses() { 25 return new Class<?>[]{WebConfig.class}; 26 } 27 28 /** 29 * 配置DispatcherServlet 匹配的路徑 30 * @return 31 */ 32 @Override 33 protected String[] getServletMappings() { 34 return new String[]{"/"}; 35 } 36 37 /** 38 * 配置其他的 servlet 和 filter 39 * 40 * @param servletContext 41 * @throws ServletException 42 */ 43 @Override 44 public void onStartup(ServletContext servletContext) throws ServletException { 45 FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class); 46 encodingFilter.setInitParameter("encoding", String.valueOf(StandardCharsets.UTF_8)); 47 encodingFilter.setInitParameter("forceEncoding", "true"); 48 encodingFilter.addMappingForUrlPatterns(null, false, "/*"); 49 } 50 }
配置 applicationContext.xml,由RootConfig類實現
1 package com.liulu.bank.config; 2 3 import com.mchange.v2.c3p0.ComboPooledDataSource; 4 import org.springframework.context.annotation.*; 5 import org.springframework.core.env.Environment; 6 import org.springframework.jdbc.core.JdbcTemplate; 7 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.transaction.PlatformTransactionManager; 10 import org.springframework.transaction.annotation.EnableTransactionManagement; 11 12 import javax.annotation.Resource; 13 import javax.sql.DataSource; 14 import java.beans.PropertyVetoException; 15 16 /** 17 * User : liulu 18 * Date : 2016-10-7 15:36 19 */ 20 @Configuration 21 @PropertySource("classpath:config.properties") // 導入屬性文件 22 @EnableAspectJAutoProxy // 相當於 xml 中的 <aop:aspectj-autoproxy/> 23 @EnableTransactionManagement // 開啟註解事務 24 @ComponentScan(basePackages = {"com.liulu.lit", "com.liulu.bank"}, excludeFilters = @ComponentScan.Filter(classes = Controller.class )) 25 public class RootConfig { 26 27 // 上面導入的屬性文件中的屬性會 註入到 Environment 中 28 @Resource 29 private Environment env; 30 31 /** 32 * 配置資料庫連接池 c3p0, 33 * @return 34 * @throws PropertyVetoException 35 */ 36 @Bean 37 public DataSource dataSource() throws PropertyVetoException { 38 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 39 dataSource.setJdbcUrl(env.getProperty("db.url")); 40 dataSource.setDriverClass(env.getProperty("db.driver")); 41 dataSource.setUser(env.getProperty("db.user")); 42 dataSource.setPassword(env.getProperty("db.password")); 43 dataSource.setMinPoolSize(Integer.valueOf(env.getProperty("pool.minPoolSize"))); 44 dataSource.setMaxPoolSize(Integer.valueOf(env.getProperty("pool.maxPoolSize"))); 45 dataSource.setAutoCommitOnClose(false); 46 dataSource.setCheckoutTimeout(Integer.valueOf(env.getProperty("pool.checkoutTimeout"))); 47 dataSource.setAcquireRetryAttempts(2); 48 return dataSource; 49 } 50 51 /** 52 * 配置事物管理器 53 * @param dataSource 54 * @return 55 */ 56 @Bean 57 public PlatformTransactionManager transactionManager(DataSource dataSource) { 58 return new DataSourceTransactionManager(dataSource); 59 } 60 61 @Bean 62 public JdbcTemplate jdbcTemplate (DataSource dataSource) { 63 return new JdbcTemplate(dataSource); 64 } 65 66 67 }
config.properties 文件在 resources 目錄下
#資料庫配置 db.url=jdbc:mysql://192.168.182.135:3306/bank db.driver=com.mysql.jdbc.Driver db.user=root db.password=123456 #資料庫連接池配置 #連接池中保留的最小連接數 pool.minPoolSize=5 #連接池中保留的最大連接數 pool.maxPoolSize=30 #獲取連接超時時間 pool.checkoutTimeout=1000
配置 servlet.xml, 由WebConfig類實現
Thymeleaf 模板配置也在下麵
1 package com.liulu.bank.config; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.ComponentScan; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.servlet.ViewResolver; 8 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 9 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 10 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 11 import org.thymeleaf.TemplateEngine; 12 import org.thymeleaf.spring4.SpringTemplateEngine; 13 import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; 14 import org.thymeleaf.spring4.view.ThymeleafViewResolver; 15 import org.thymeleaf.templatemode.TemplateMode; 16 17 import java.nio.charset.StandardCharsets; 18 19 /** 20 * User : liulu 21 * Date : 2016-10-7 15:16 22 */ 23 @Configuration 24 @EnableWebMvc // 啟用 SpringMVC ,相當於 xml中的 <mvc:annotation-driven/> 25 @ComponentScan(basePackages = {"com.liulu.bank.controller", "com.liulu.lit"}, 26 includeFilters = @ComponentScan.Filter(classes = Controller.class), 27 useDefaultFilters = false) 28 public class WebConfig extends WebMvcConfigurerAdapter { 29 30 /** 31 * 設置由 web容器處理靜態資源 ,相當於 xml中的<mvc:default-servlet-handler/> 32 */ 33 @Override 34 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 35 configurer.enable(); 36 } 37 38 /** 39 * 下麵三個bean 配置 Thymeleaf 模板 40 * @return 41 */ 42 @Bean 43 public SpringResourceTemplateResolver templateResolver() { 44 SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); 45 templateResolver.setPrefix("/WEB-INF/templates/"); 46 templateResolver.setSuffix(".html"); 47 templateResolver.setTemplateMode(TemplateMode.HTML); 48 templateResolver.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8)); 49 return templateResolver; 50 } 51 52 @Bean 53 public TemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver) { 54 SpringTemplateEngine templateEngine = new SpringTemplateEngine(); 55 templateEngine.setTemplateResolver(templateResolver); 56 return templateEngine; 57 } 58 59 @Bean 60 public ViewResolver viewResolver(TemplateEngine templateEngine) { 61 ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); 62 viewResolver.setTemplateEngine(templateEngine); 63 viewResolver.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8)); 64 return viewResolver; 65 } 66 67 }