Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (및 공유 보안)
두 가지 컨텍스트를 올바르게 사용하는 방법은 무엇입니까?dispatcher-servlet.xml
그리고.applicationContext.xml
무엇이 어디로 갑니까?
저는 서블릿 컨테이너에 배포된 상당히 일반적인 앱을 작성하고 싶습니다.JSP 보기가 있는 일부 컨트롤러가 있습니다.그것은 또한 백엔드에 사소하지 않은 논리가 있습니다.정말로 두 가지 상황이 모두 필요합니까?그들은 서로 어떻게 관련이 있습니까?어떤 것을 넣어야 할지 어떻게 결정할 수 있습니까?
또한 Spring-security를 응용 프로그램에 사용하고 싶습니다.주석이 있는 선언적 보안과 같은 기능을 더 깊은 계층뿐만 아니라 웹 컨트롤러에서도 사용하고 싶을 수 있습니다.이 경우 작동하도록 보안을 어떻게 구성해야 합니까?해당 파일 중 하나(어느 파일)에 있어야 합니까? 아니면 둘 다에 있어야 합니까?
그dispatcher-servlet.xml
파일에는 에 대한 모든 구성이 포함되어 있습니다.Spring MVC
그래서 당신은 그 안에서 다음과 같은 콩을 발견할 것입니다.ViewHandlerResolvers
,ConverterFactories
,Interceptors
등등.이 콩들은 모두의 일부입니다.Spring MVC
웹 요청을 처리하는 방법을 구조화하는 프레임워크로, 데이터 바인딩, 보기 해상도 및 요청 매핑과 같은 유용한 기능을 제공합니다.
그application-context.xml
선택적으로 사용할 때 포함할 수 있습니다.Spring MVC
또는 그 문제에 대한 다른 프레임워크.이렇게 하면 데이터 지속성과 같은 지원을 제공하는 다른 유형의 스프링 원두를 구성하는 데 사용할 수 있는 컨테이너가 제공됩니다.기본적으로 이 구성 파일에서는 스프링이 제공하는 다른 모든 상품을 끌어오는 위치입니다.
이러한 구성 파일은 web.xml 파일에서 다음과 같이 구성됩니다.
디스패처 구성
<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>
응용 프로그램 구성
<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>
컨트롤러를 구성하려면 컨트롤러에 다음과 같이 주석을 달아야 합니다.@Controller
그런 다음 다음을 포함합니다.dispatcher-context.xml
파일:
<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />
Kevin의 답변을 덧붙이자면, 실제로는 거의 모든 사소한 Spring MVC 애플리케이션에 애플리케이션 컨텍스트가 필요합니다(Spring MVC 디스패처 서블릿 컨텍스트만 필요함).응용프로그램 컨텍스트에서는 다음과 같은 웹과 관련되지 않은 모든 문제를 구성해야 합니다.
- 보안.
- 고집
- 예약된 작업
- 다른 사람들은?
이를 좀 더 구체적으로 설명하기 위해 최신(Spring 버전 4.1.2) Spring MVC 애플리케이션을 설정할 때 사용한 Spring 구성의 예를 다음에 제시하겠습니다.개인적으로, 저는 여전히 사용하는 것을 선호합니다.WEB-INF/web.xml
파일은 있지만 실제로 확인할 수 있는 유일한 xml 구성입니다.
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("/**/images/**").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;
}
}
지속성Config.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();
}
}
보시다시피 웹 구성은 전체 스프링 웹 응용 프로그램 구성의 일부에 불과합니다.의 웹 프로그램은 를 안고 , 이 을 통해 전체 응용 프로그램 합니다. 이러한 우려 사항은 다음을 통해 전체 애플리케이션 컨텍스트 부트스트랩이 필요합니다.org.springframework.web.context.ContextLoaderListener
에 시대에web.xml
.
<?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>
<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>
<?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>
언급URL : https://stackoverflow.com/questions/16458754/spring-web-mvc-dispatcher-servlet-xml-vs-applicationcontext-xml-plus-shared
'programing' 카테고리의 다른 글
오라클 11g에 무제한 문자를 저장하는 방법은 무엇입니까? (0) | 2023.07.26 |
---|---|
ES6/Node 4에서 인터페이스를 생성할 수 있는 방법이 있습니까? (0) | 2023.07.26 |
최대 절전 모드가 필드에 잘못된 유형을 설정하려고 합니다(Spring Data JPA). (0) | 2023.07.26 |
lazy-init에 대한 스프링 기본 동작 (0) | 2023.07.26 |
서비스 계층 및 컨트롤러: 무엇을 담당합니까? (0) | 2023.07.26 |