서블릿 3.0에서 웹 프로젝트를 시작하는 데는 web.xml 구성 파일이 전혀 필요하지 않으므로 이 글의 구성은 서블릿 3.0 이상을 지원하는 웹 컨테이너에서만 유효합니다.
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 인터페이스의 메소드입니다. 사용자는 구성 클래스를 가져오기 위해
getRootConfigClasses()를 구성합니다. 제가 이해하는 것은 applicationContext에 의해 생성된 컨텍스트와 동일합니다. .xml
getServletConfigClasses( ) mvc-servlet.xml에서 생성된 컨텍스트와 동일한 구성 클래스를 가져옵니다.
이 클래스에는 주석이 필요하지 않습니다.
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}; } /** * 配置DispatcherServlet 匹配的路径 * @return */ @Override protected String[] getServletMappings() { return new String[]{"/"}; } /** * 配置其他的 servlet 和 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, "/*"); } }
는 RootConfig 클래스
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") // 导入属性文件 @EnableAspectJAutoProxy // 相当于 xml 中的 <aop:aspectj-autoproxy/> @EnableTransactionManagement // 开启注解事务 @ComponentScan(basePackages = {"com.liulu.lit", "com.liulu.bank"}, excludeFilters = @ComponentScan.Filter(classes = Controller.class )) public class RootConfig { // 上面导入的属性文件中的属性会 注入到 Environment 中 @Resource private Environment env; /** * 配置数据库连接池 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; } /** * 配置事物管理器 * @param dataSource * @return */ @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean public JdbcTemplate jdbcTemplate (DataSource dataSource) { return new JdbcTemplate(dataSource); } }
에 의해 구현되는 applicationContext.xml을 구성합니다. config.properties 파일은 리소스 디렉토리
#数据库配置 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 템플릿 구성도
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 // 启用 SpringMVC ,相当于 xml中的 <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 { /** * 设置由 web容器处理静态资源 ,相当于 xml中的<mvc:default-servlet-handler/> */ @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } /** * 下面三个bean 配置 Thymeleaf 模板 * @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; } }