Iniciar um projeto da Web no Servlet 3.0 não pode mais exigir um arquivo de configuração web.xml, portanto, a configuração deste artigo é válida apenas em contêineres da Web que suportam o Servlet 3.0 e acima
Utilizando MVC da mola (4.3.2.Release) + tymeleaf (3.0.2.Release), o JDBCTemplate usado na camada de persistência. PS: Recomende uma estrutura muito útil para o encapsulamento jdbctemplate: https://github.com/selfly/dexcoder-sistant. A seguir, a configuração específica:
Configurar o Spring MVC DispatcheserServlet
DispatcheserServlet é o núcleo do MVC da primavera. A primavera fornece uma classe abstractannotationConfigDispatcherStletinitializer que configura rapidamente o DispatcheserServlet. O código específico é o seguinte:
Onde o OnStartup () é um método na interface WebApplicationInitializer, e o usuário configura outros filtros e ouvintes.
getRootconfigClasses () recebe a classe de configuração, o que eu entendo é equivalente ao contexto criado por appolplecontext.xml
getServletConfigClasses () recebe a classe de configuração, que é equivalente ao contexto criado por mvc-servlet.xml
Nenhum comentário é necessário nesta categoria
pacote com.liu.bank.config; importar org.springframework.web.webApplicationInitializer; importar org.springframework.web.filter.ispatrevErncodingFilter; importação; javax.servlet.filterRegistration; importar javax.servlet.servletContext; importar javax.servlet.servletexception; importar java.nio.charset.standardcharsets;/** * usuário: LIU * Data: 2016-10-7 15:12 */Classe WebApnialLizer WebApplicationInitializer {@Override Protected Class <?> [] GetRootConfigClasses () {return nova classe <?> [] {Rootconfig.class}; } @Override Classe protegida <?> [] GetServletConfigClasses () {retorna nova classe <?> [] {Webconfig.class}; }/*** Configure o caminho para corresponder ao despachoServlet* @return*/@Override Protected String [] getServletMappings () {return string [] {"/"}; } /** * Configure other servlets and filters * * @param servletContext * @throws ServletException */ @Override public void onStartup(ServletContext servletContext) throws ServletException { FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class); codingfilter.setInitParameter ("Encoding", String.ValueOf (StandardCharSets.utf_8)); codingfilter.setInitParameter ("Forcencoding", "True"); codingfilter.addmappingForUlPatterns (nulo, false, "/*"); }} Configurar ApplicationContext.xml, implementado pela classe RootConfig
package com.liu.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; importar org.springframework.tereotype.controller; importar org.springframework.transaction.platmansationmanager; importar.springframework.annotation.notation.notation.notation.PlatformManager; Import.sPringFramework.Antation.annOtation.notation.notation.notation.PLATRANSATIRNAGER; IMPORNATRG.SPRINGFRAMEWORK.TRANSACTION.ANTATION.PLATSATNATRANGER; javax.annotation.resource; importar javax.sql.dataSource; importar java.beans.propertyvetoException;/** * Usuário: Liu * Data: 2016-10-7 15:36 */@configatury@propriedadesource ("classPaTPath: config.Properties "/Imptomerk <aOP: AspectJ-AutoProxy/> @EnableTransactionManagement no xml // Ative a transação de anotação @ComponentsCan (bashEpackages = {"com.liulu.lit", "com.liulu.bank"}, excluiFilters = @componentsCon.filter (Class. O arquivo de atributo importado acima será injetado no ambiente @Resource Ambiente Privado Env; / ** * Configurar pool de conexão com o banco de dados C3P0, * @return * @throws PropertyVeToException */ @Bean public DataSource DataSource () lança PropertyVeToException {CombopooledDataSource DataSource = new CombooCooledDataSource (); 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.SetcheCechoutTimeout (Integer.ValueOf (Env.getProperty ("Pool.CheckoutTimeout"))); DataSource.setAcquireretyAttsepts (2); return DataSource; } / ** * Configure o gerenciador de coisas * @param DataSource * @return * / @Bean Public PlatformTransactionManager TransactionManager (DataSource DataSource) {Return DataSourCetransActionManager (DataSource); } @Bean public JDBCTemplate JDBCTemplate (DataSource DataSource) {Return New JDBCTemplate (DataSource); }}O arquivo config.properties está no diretório de recursos
#Database Configuration db.url = jdbc: mysql: //192.168.182.135: 3306/Bankdb.driver = com.mysql.jdbc.driverdb.user = rootdb.password = 123456#DataBase Pool Pool Número de conexões reservadas no pool de pool de conexão.
Configurar servlet.xml, implementado pela classe WebConfig
A configuração do modelo Thymeleafd também está abaixo
pacote com.liu.bank.config; importar org.springframework.context.annotation.bean; importar org.springframework.context.annotation.comPonentsCan; importação org.springframework.context.annotation.configuration; importação ou importância; org.springframework.web.servlet.viewResolver; importar org.springframework.web.servlet.config.annotation.defaultservletlethandlerconfigurer; importação Org.springframework.web.servlet.config.annotation.enenableBebringBringBringBringMwebwebwebring.vérgets; org.springframework.web.servlet.config.annotation.webmvcConfigureRAdApter; importar org.thymeleaf.templateengine; importação org.TheLySeLeaf.spring4.springtemplate; import.thymeLeaf.empling.Emplates4 org.thymeleaf.spring4.view.thymeleafviewResolver; importar org.thymeleaf.templatemode.templatemode; importar java.nio.charset.StandardCharSets;/** * Usuário: Liu * Data: 2016-10-7 15:16 */@inableTent <mvc: anotation-driven /> @componentsCan (bashEpackages = {"com.liulu.bank.controller", "com.liulu.lit"}, incluirfilters = @componentsCan.Filter (classes = controler.class), usafultfilters = falsesCan) Recursos estáticos tratados pelo contêiner da web, que é equivalente a <mvc: default-servlet-handler/> em xml */ @Override public void ConfiguleFaultServLetHandling (defaultServLetHandlerConfigurer configure) {configurer.enable (); } / *** Os três feijões a seguir são configurados Tommeleaf Modelo* @return* / @Bean Public SpringResourCETEMPLATERESOLVER TemplateResolver () {SpringResourceTemplateResolver templateresolver.setprefix ("/web-inf/modsates/"); templateresolver.SetSuffix (". html"); templateresolver.setTemplatemode (templatemode.html); templateresolver.setcharacterencoding (string.valueof (standardcharsets.utf_8)); retornar o templateresolver; } @Bean Public TemplateEngine modelo (SpringResourceTemplateresolver templateresolver) {springtemplateEngine modelEngine = new springtemplateEngine (); templateEngine.setTemplateresolver (Templateresolver); Return modeloEngine; } @Bean public ViewResolver ViewResolver (METLEMPLEENGINE METLEGINE) {thymEleafViewResolver ViewResolver = new ThymEleafViewResolver (); ViewResolver.SetTemplateEngine (ModelEngine); ViewResolver.SetcharAcTerEncoding (String.valueof (StandardCharsets.utf_8)); retornar viewResolver; }}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.