728x90
Spring MVC 웹서비스
- MVC - Model, View, Controller
설계 모델 Model2
- 개발자가 설정하는 부분
MVC 프레임워크 동작구조
- spring이 동작하는 구조
- 클라이언트의 요청이 들어오면 front controller라고 하는 DispatcherServlet으로 가져옴
- 여기서 HandlerMapping 클래스에 던져주면 url을 분석하고 다시 DispatcherServlet으로 던짐
- 이번에는 받아온 url을 HandlerAdapter에 던져주면 적합한 컨트롤러를 찾아서 연결을 붙여줌
- Controller에서는 크게 Model(데이터)과 View(화면정보) 2개를 DispatcherServlet으로 던짐
- 처리결과를 출력할 view를 선택하는데 view에 대한 정보를 받고, 완성시키기 위해서
view 경로를 완전히 합성해서 완성된 view 정보를 DispatcherServlet으로 던짐 - view에서 응답 생성
- JSP 내장객체로 응답
▶ 결론적으로 DispatcherServlet이 forward 방식으로 화면으로 넘겨줌
2022.12.01 - [Server/JSP] - [JSP] 예외처리 - 예외페이지, forward, JAVA Bean
[JSP] 예외처리 - 예외페이지, forward, JAVA Bean
예외 처리 예외 상황이 발생했을 경우 웹 컨테이너에서 제공되는 기본적인 예외페이지가 보여짐 개발 과정에서는 문제없지만 배포시에는 따로 만들어 둔 에러 페이지로 유도하여 사용자에게
j-won950101.tistory.com
프로젝트 전체 구조 - 디렉토리
1. web.xml - 초기 설정 파일
- 서블릿을 맵핑
- 전역에서 사용할 초기설정 파일
- 모든 서블릿에서 공통으로 참조할 파일은 전역으로 선언 가능
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>SpringMake</display-name>
<!-- 전역으로 사용할 초기설정 파일 -->
<!-- 모든 서블릿에서 공통으로 참조할 파일은 전역으로 선언할 수 있습니다. -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 디스패쳐 서블릿이 생성될 때 스프링 설정파일로 사용할 파일의 경로를 매개변수로 받습니다. -->
<!-- 이 파일이 혹 여러개라면, 줄바꿈으로 표현해주면 됩니다. -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/spring-servlet.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2. DispatcherServlet
3. servlet-context.xml - 서블릿
<init-param> 부분 ▷ web.xml
- 디스패쳐 서블릿이 생성될 때 스프링 설정파일로 사용할 파일의 경로를 매개변수로 받음
- 이 파일이 여러개라면, 줄바꿈으로 표현해주면 됨
- 스프링 설정 파일을 여러 개 생성하고 싶으면 위처럼 파일 경로를 여러개 적어주면 됨
- 새롭게 생성한 스프링 설정파일을 가장 mvc설정 파일로 지정하는 방법은 기존 servlet-context.xml 의 스키마 설정을 복사해서 넣어주면 됨
<annotation-driven />
- handlermapping, handleradapter 을 객체로 생성
<resources ~ />
- 정적 자원의 맵핑
<bean ~ /> + <property ~/> : view 리졸버
<context:component-scan ~/>
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- 메인컨트롤러를 빈으로 등록 -->
<!-- <bean id="xxx" class="com.simple.controller.MainController"></bean> -->
<!-- 핸들러맵핑 등록 -->
<!-- /test/aaa 요청이 들어오면 xxx빈으로 핸들러맴핑 -->
<!-- <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/test/aaa">xxx</prop>
<prop key="/test/bbb">xxx</prop>
</props>
</property>
</bean> -->
<!-- 스프링 내부에 있는 어노테이션방법으로 핸들러맵핑과 핸들러어댑터기능을 제공함 -->
<mvc:annotation-driven />
<!-- 해당 패키지를 읽어서 @Controller가 있는 클래스를 자동으로 bean으로 등록시킴 include, exclude를 확장시켜 사용가능함 -->
<context:component-scan base-package="com.simple.**"><!-- 컨트롤러어노테이션이 붙어있는 애들을 지정한 패키지의 빈으로 만들어줌 -->
<context:include-filter type="annotation" expression="com.simple.controller.HomeController"/>
</context:component-scan> <!-- include-특정경로는 포함 -->
<!-- css, js 정적자원들은 폴더경로로 바로 연결 -->
<!-- resource 경로로 들어오면 /resource폴더 연결 -->
<mvc:resources mapping="/resource/**" location="/resource/" />
<!-- 뷰 합성기(뷰리졸버) -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
4. Controller (컨트롤러)
- 핸들러 클래스로 등록이 되려면 특정 기능을 가지고 있어야 함
- MultiActionController 스프링 3ver에서 컨트롤러의 역할을 할 수 있도록 제공되는 클래스 중 1개
- 상속받고 handleRequestInternal 오버라이딩 하면 동작
package com.simple.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
//핸들러 클래스로 등록이 되려면 특정 기능을 가지고 있어야 합니다.
//MultiActionController 스프링 3ver에서 컨트롤러의 역할을 할 수 있도록 제공되는 클래스 중 1개
//상속받고 handleRequestInternal 오버라이딩 하면 동작합니다.
public class MainController extends MultiActionController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String path = request.getContextPath();
String uri = request.getRequestURI();
String command = uri.substring(path.length());
if(command.equals("/test/aaa")) {
System.out.println("aaa실행됨");
//확장
//model과 view 정보를 담는 객체
ModelAndView mv = new ModelAndView();
// mv.setViewName("/WEB-INF/views/home.jsp"); //뷰의 정보
mv.setViewName("home"); //앞뒤로 prefix, suffix 들어감
mv.addObject("data", "hello world"); //데이터정보
return mv;
} else if(command.equals("/test/bbb")) {
System.out.println("bbb실행됨");
}
return super.handleRequestInternal(request, response);
}
}
5. View (뷰)
- 뷰리졸버가 jsp파일을 조립해서 실행
6. home.xml 구동과정
오늘 하루
더보기
기억에 남는 부분
-
-
어려운 부분
-
-
문제 해결 부분
-
-
728x90