풀스택 개발자 2020. 5. 1. 22:45

java에서는 xml에서의 요소들을 다르게 구현한다

 

web.xml->AbstractAnnotationConfigDispatherServletInitializer 상속 or WebApplicationInitializer인터페이스 구현

 

root-context.xml->상속 없음

 

servlet-context.xml-> WebMvcConfigurer 인터페이스 구현

 

 

 

 

 

WebApplicationInitializer인터페이스 구현

 

자바에서는 web.xml파일에서 수행하는 것들을 자바 파일을 만든다.

 

package kr.co.softcampus.config;

public class SpringConfigClass implements WebApplicationInitializer{//WebApplicationInitializer을 구현한 클래스가 존재한다면 그 클래스가 가지고있는 onStrartup을 자동으로 호출해준다 web.xml파일을 로딩하는것 대신에 onstartup 메소드를 자동호출 

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		// TODO Auto-generated method stub
		
		
		
	}

}

 

WebApplicationInitializer을 구현한 클래스가 존재한다면 그 클래스가 가지고있는 onStrartup을 자동으로 호출해준다.

즉 web.xml파일을 로딩하는것 대신에 onstartup 메소드를 자동호출해준다.

 

package kr.co.softcampus.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class SpringConfigClass implements WebApplicationInitializer{//WebApplicationInitializer을 구현한 클래스가 존재한다면 그 클래스가 가지고있는 onStrartup을 자동으로 호출해준다 web.xml파일을 로딩하는것 대신에 onstartup 메소드를 자동호출 

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		// TODO Auto-generated method stub
		//spring mvc 설정을 위해 작성하는 클래스의 객체를 생성한다.
		AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
		servletAppContext.register(ServletAppContext.class);
		
		
		//요청발생시 요청을 처리하는 서블릿을 dispathcerservlet을 설정해줌
		DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);
		ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", dispatcherServlet);
		
		//부가설정
		servlet.setLoadOnStartup(1);//모든 요청에 대해 이 servlet이 가장먼저 받아들이겠다.
		servlet.addMapping("/");//
		
		//bean을 정의하는 클래스를 지정한다
		AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
		rootAppContext.register(RootAppContext.class);
		
		ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
		servletContext.addListener(listener);
		
		//파라미터 인코딩 설정
		FilterRegistration.Dynamic filter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
		filter.setInitParameter("encoding", "UTF-8");
		filter.addMappingForServletNames(null, false, "dispatcher");
		
		
	}

}

xml에서의 web.xml과 설정내용은 같지만 xml과 달리 자바는 클래스는 이용하여 설정한다

 

servlet-context 부분

package kr.co.softcampus.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
//Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다.
@EnableWebMvc
//스캔할 패키지를 지정한다.
@ComponentScan("kr.co.softcampus.controller")
public class ServletAppContext implements WebMvcConfigurer{
	// Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다.
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		// TODO Auto-generated method stub
		WebMvcConfigurer.super.configureViewResolvers(registry);
		registry.jsp("/WEB-INF/views/", ".jsp");
	}
	
	// 정적 파일의 경로를 매핑한다.
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// TODO Auto-generated method stub
		WebMvcConfigurer.super.addResourceHandlers(registry);
		registry.addResourceHandler("/**").addResourceLocations("/resources/");
	}
}

 

root-context부분

package kr.co.softcampus.config;

import org.springframework.context.annotation.Configuration;

//프로젝트 작업시 사용할 bean을 정의하는 클래스
@Configuration
public class RootAppContext {

}

 

 

AbstractAnnotationConfigDispatherServletInitializer 상속

 

 

public class SpringConfigClass extends AbstractAnnotationConfigDispatcherServletInitializer{

	//모든 요청에 대해서 dispathcerservlet이 반응을 하겠다.
	@Override
	protected String[] getServletMappings() {
		// TODO Auto-generated method stub
		return new String[] {"/"};
	}
	
	//spring mvc프로젝트 설정을 위한 클래스를 지정한다,servlet-context지정
	@Override
	protected Class<?>[] getServletConfigClasses() {
		// TODO Auto-generated method stub
		return new Class[] {ServletAppContext.class};
	}
	
	//프로젝트에서 사용한 bean들을 정의하기 위한 클래스를 지정 root-context지정
	@Override
	protected Class<?>[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return new Class[] {RootAppContext.class};
	}
	
	//파라미터 인코딩 필터 설정
	@Override
	protected Filter[] getServletFilters() {
		// TODO Auto-generated method stub
		CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
		encodingFilter.setEncoding("UTF-8");
		return new Filter[] {encodingFilter};
	}

}