✅ Controller의 분리와 POJO 컨트롤러 (*POJO class)

기존의 컨트롤러: 사용자 입출력을 처리함 (출력은 jsp에게 전달하긴함!)

이런 서블릿 컨트롤러가 많아지고, 각각 입력받는 방법이 다르고 forwarding하는 방법이 반복적임.

프론트 컨트롤러를 추가해서 단순화함

👉 프론트 컨트롤러의 형태가 비슷해서 라이브러리가 제공됨 == 스프링mvc

 

 

JSP  MVC model 1
JSP  MVC model 2
모든 서블릿이 mapping되어있는 구조
디스패처 서블릿이 중간에서 포워딩의 역할을 한다

 

디스패처 서블릿 (프론트컨트롤러)를 쓰는 이유

  • 파라미터 쉽게 사용
  • 포워딩이 쉬워짐

컨트롤러를 어떤 라이브러리를 쓰냐에 따라서 난이도가 쉬워짐.

(* 프론트컨트롤러가 일을 많이할수록 POJO의 일은 줄어드므로 프론트 컨트롤러의 역할이 중요하다)

 

어노테이션 설정과 어노테이션 속성을 어떻게 인식하지? ▶ 스프링을사용하며 살펴봐야 할 부분

 


 

✅ 스프링 MVC

https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-servlet.html

 

DispatcherServlet :: Spring Framework

Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components

docs.spring.io

web.xml에 스프링 라이브러리 설정값 (메모리에 올리는 설정)

 

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
  version="6.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

	<servlet>
		<servlet-name>app</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

<!-- 모든 URL을 처리하도록 맵핑한다 -->
	<servlet-mapping>
		<servlet-name>app</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

</web-app>

 

 

#️⃣ web.xml설정

 

Container Overview :: Spring Framework

As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata. This configuration metadata represents how you, as an application developer, tell the Spring container to instantiate, configure, and assemble the objects i

docs.spring.io

 

👉 이렇게 실행시키면 아직 예외가 뜬다 (500번 에러)

 

👉 근본원인에 보면 [/WEB-INF/app-servlet.xml]이 없다고 나온다.

즉 dispatcher servlet이 찾아갈 pojo servlet에 대한 mapping자료인 app-servlet.xml이 없다는 것. 경로를 만들어주자!

 

WEB-INF아래에 xml파일 추가
web.xml 설정값에 맞춰서 app-setlvet.xml을 찾아가도록 하기

 

 

#️⃣ POJO Controller 만들기

(*아직 예전방식의 컨트롤러 코드 - 서블릿에서 완전히 벗어나진 못했음)

//@WebServlet("/menu/list")  -- app-servlet.xml로부터 연결되므로 url맵핑이 필요가없어진다

//서블릿은 없어지고 부모가 스프링으로 바뀐다
public class ListController implements Controller {
	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ServletContext application =request.getServletContext();
		
		SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) application.getAttribute("sqlSessionFactory");
		SqlSession sqlSession = sqlSessionFactory.openSession();
		MenuRepository repository = sqlSession.getMapper(MenuRepository.class);
		List<Menu> list = repository.findAll();

		//request.setAttribute("list", list); -- 기존포워딩방법
		mv.setViewName("/WEB-INF/view/menu/list.jsp");
		mv.addObject("list", list);
		
		//forwarding
		return mv;
	}
	
//	@Override
//	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		
//		ServletContext application =req.getServletContext();
//		
//		SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) application.getAttribute("sqlSessionFactory");
//		SqlSession sqlSession = sqlSessionFactory.openSession();
//		MenuRepository repository = sqlSession.getMapper(MenuRepository.class);
//		List<Menu> list = repository.findAll();
//
//		req.setAttribute("list", list); //값을 받았으니 jsp로 포워딩해줘야함
//		
//		//dispatcher로 연결해주기 (절대경로로 설정)
//		req.getRequestDispatcher("/WEB-INF/view/menu/list.jsp").forward(req, resp);
//	}
}

 

 

https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-config/enable.html

 

Enable MVC Configuration :: Spring Framework

In Java configuration, you can use the @EnableWebMvc annotation to enable MVC configuration, as the following example shows: In XML configuration, you can use the element to enable MVC configuration, as the following example shows: The preceding example re

docs.spring.io

 

+ Recent posts