ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Servlet & 스프링 web.xml 설정 (쉽게 따라하는 자바 웹개발 (백기선))
    BackEnd/스프링 2021. 1. 14. 21:04

     

     

    https://coding-factory.tistory.com/742

     

    [Web] 서블릿(Servlet)이란 무엇인가? 서블릿 총정리

     서블릿(Servlet)이란? 서블릿이란 Dynamic Web Page를 만들 때 사용되는 자바 기반의 웹 애플리케이션 프로그래밍 기술입니다. 웹을 만들때는 다양한 요청(Request)과 응답(Response)이 있기 마련이고 이

    coding-factory.tistory.com

    JSP 프로그래밍 방식

    요청받은 파일을 그대로 반환한다.

    web.xml
    
    <welcome-file-list> 
      <welcome-file>index.html</welcome-file> 
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file> 
      <welcome-file>default.html</welcome-file> 
      <welcome-file>default.htm</welcome-file> 
      <welcome-file>default.jsp</welcome-file> 
    </welcome-file-list>
    

     


    서블릿 & JSP 프로그래밍 방식

    서블릿 클래스를 등록하고 관련 매핑 정보를 기재한다.

    다른 기능을 추가하기 위해서는 서블릿을 추가하고, web.xml 에 서블릿 mapping 을 등록해야한다.

    web.xml에 매핑 정보는 점점 늘어나고, 서블릿, JSP 모두 변경, 관리해야된다는 단점이 있다.

    web.xml
    
    <servlet> 
    	<servlet-name>hello</servlet-name> 
    	<servlet-class>whiteship.HelloServlet</servlet-class> 
    </servlet>
    <servlet-mapping> 
      <servlet-name>hello</servlet-name> 
      <url-pattern>/hello</url-pattern> 
    </servlet-mapping>
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class HelloServlet extends HttpServlet{
    	
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		String name = req.getParameter("name");
    		
    		String hello = "hello" + name;
    		
    		req.setAttribute("hello", hello);
    		RequestDispatcher dispatcher = req.getRequestDispatcher("WEB-INF/views/hello.jsp");
    		
    		dispatcher.forward(req, resp);
    	}
    
    }
    

     


    스프링

    스프링 MVC의 핵심 요소인 DispacherServlet 맵핑을 추가한다.

    스프링에서 서블릿 name 을 spring 으로 하는 DispatcherServlet를 제공하는데, 

    이를 등록하고 /app으로 시작하는 모든 요청을 처리하도록 설정하면 위의 서블릿&JSP 보다 매핑을 손쉽게 관리할 수 있다.

    web.xml
    
    <servlet> 
      <servlet-name>spring</servlet-name> 
      <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> 
    </servlet>
     
    <servlet-mapping> 
      <servlet-name>spring</servlet-name> 
      <url-pattern>/app/*</url-pattern> 
    </servlet-mapping>
    
    spring-servlet.xml
    
    <beans>
    	<context:component-scan base-package="whiteship"/>
    </beans>
    
    import org.springframework.stereotype.Controller; 
    import org.springframework.ui.Model; 
    import org.springframework.web.bind.annotation.RequestMapping; 
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller public class HelloController {
     
     @RequestMapping("/hello") 
     public String hello(@RequestParam String name, Model model) {   
     	model.addAttribute("hello", "hello " + name);   
     	return "/WEB-INF/views/hello.jsp"; 
        }
    }

    스프링 전체 설정 구조 

    - ContextLoaderListener웹 애플리케이션이 서블릿 컨테이너에 로딩될 때 실행되는 리스너로,

    서블릿에서 제공하는 Servlet ContextListener를 확장하여 만든 것이다.
    - <context-param> 에 ContextLoaderListener에서 사용할 스프링 설정 파일을 지정한다.
    - ContextLoaderListener 는 웹 애플리케이션이 로딩될 때 Web ApplicationContext 를 만든다.
    - 생성된 WebApplicationContext 는 contextConfigLocation에 설정한 빈 설정 파일을 사용해서 
      웹 애플리케이션 에서 사용할 객체를 관리해주는 역할을 한다.

    web.xml
    
    <listener> 
      <listener-class>
      	org.springframework.web.context.ContextLoaderListener  
      </listener-class> 
    </listener>
    
    <context-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>
      	classpath:applicationContext*.xml
      </param-value> 
    </context-param>
    
    

    <servlet>  
        <servlet-name>spring</servlet-name>  
        <servlet-class>
        	org.springframework.web.servlet.DispatcherServlet  
        </servlet-class>  
    
        <init-param>    
        	<param-name>contextConfigLocation</param-name>    
        	<param-value>/WEB-INF/spring/webmvc-config.xml</param-value>  
        </init-param> 
    </servlet>
    
    <servlet-mapping>  
        <servlet-name>spring</servlet-name>  
        <url-pattern>/app/*</url-pattern> 
    </servlet-mapping>
    

    DispatcherServlet은 자바 Servlet 을 확장한 클래스로 특정 URL 패턴을 DispatcherServlet으로 맵핑하여 스프링 MVC를 사용할 수 있도록 해주는 일종의 대문 역할을 하는데 , DispatcherServlet(DS)도 ContextLoaderListener(CLL)처럼 WebApplication Context(WAC)를 생성한다. 

    하지만 CLL과는 WAC를 만드는 방법이 다르다.

    1. ContextLoaderListener(CLL)에서 만든 WAC가 있다면, 그것을 상속 받는 WAC를 만든다. 

    2. ContextLoaderListener(CLL)애플리케이션당 WAC 한 개,

      DispatcherServlet(DS)는 서블릿 설정당  WAC를 한 개씩 만 든다.
    즉 ContextLoaderListner는 애플리케이션 전체에서 사용할 WAC를 만들고,

     DispatcherServlet은 해당 서블릿에서만 사용할 WAC를 만든다.

     

    이런 식으로 WebApplicationContext는 상속 구조를 가지며, 상속의 특징을 동일하게 갖는다.
     · 자식 WAC에서 부모 WAC의 빈을 참조할 수 있다. 

    · 부모 WAC에서는 자식 WAC의 빈을 참조할 수 없다. 

    · 자식 WAC에서 어떤 빈을 참조할 때, 먼저 자기 자신 내부에 있는 빈을 참조한다. 

    만약 자기 자신 내부에 없다면 부모 쪽에서 찾아보고, 부모 쪽에도 원하는 빈이 없다면 예외를 발생시킨다.
    그래서 보통 WAC(CLL)과 WAC(DS)로 다음과 같이 빈을 나눠서 관리한다.

     

    · WAC(CLL): 웹에 종속적이지 않은 빈. 예) 서비스, DAO 

    · WAC(DS): 웹에 종속적인 빈. 예) 컨트롤러, 스프링 MVC 관련 빈

     

     

    web.xml 설정을 보면 

    <init-param>  contextConfigLocation  은 web-inf 아래 있는 xml 을, 

    <context-param> contextConfigLocation  src 아래 xml 파일을 사용하고 있다.

     

    init-param은 ContextLoaderListener(CCL) 에서 관리하는 Web Application Context(WAC) 이고

    ( service,repository -> src/applicationContext.xml ) ,

     

    context-param은 DispatcherServlet(DS) 에서 관리하는 Web Application Context(WAC) 이다.

    (  controller -> web/WEB-INF/spring/webmvc-config.xml)

     

    반응형

    'BackEnd > 스프링' 카테고리의 다른 글

    필터와 인터셉터  (0) 2021.07.27
    WebFlux  (0) 2021.05.25
    restcontroller  (0) 2021.05.14
    트랜젝션  (0) 2020.12.06
    messageConverter  (0) 2020.11.22
Designed by Tistory.