記錄

Spring) Spring Framework MVC Basic Flow 상세 (+예제코드) 본문

Web/Spring framework

Spring) Spring Framework MVC Basic Flow 상세 (+예제코드)

surhommejk 2018. 4. 30. 00:23




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_3_1.xsd"
        id="WebApp_ID" version="3.1">
<display-name>SpringMVC_Basic01_Controller</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<!--
DispatcherServlet를 xml 설정해줄 때에는
반드시 Handler Mapping인 "#-servlet.xml"에서 사용될 것을 고려해야 한다.


Spring Framework에서는 DispatcherServlet이 request를 보낼 Handler Mapping의 파일명을
"#-servlet.xml"로 이미 설정해 두었기 때문이다.
-->
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

<!--
servlet-mapping은 name에 해당하는 servlet이 url-pattern에서 설정된 접근을
모두 처리하도록 하는 설정이다!!

즉, 여기서는 *.htm에 해당하는 모든 처리를 spring이라는 servlet이 담당하도록
설정되어 있다.

(그리고 이 spring은 위에서 DispatcherServlet으로 설정하고 있음)
-->

</web-app>



Class DispatcherServlet

public class DispatcherServlet

extends FrameworkServlet


Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers or HTTP-based remote service exporters. Dispatches to registered handlers for processing a web request, providing convenient mapping and exception handling facilities.




index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Spring MVC</h3>
<a href="hello.htm">hello.htm 요청하기</a>
<hr>
<a href="intro.htm">intro.htm 요청하기</a>
</body>
</html>





spring-servlet.xml (<--  web.xml에 의해 Dispatcher로 설정되었다)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="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.xsd">



<bean id="/hello.htm" class="kr.or.bit.HelloController"></bean>
<bean id="/intro.htm" class="kr.or.bit.IntroController"></bean>

<!-- hello.htm과 intro.htm은 존재하지도 않는 파일이지만 index.html에서 링크가 걸려있다.
     따라서 거기서 링크를 거는 것은 저 bean id에 걸리는 것과 동일하다고 보면 된다.
     결과적으로 해당 bean의 id에 맞는 class로 경로가 설정되는 것이고 링크 클릭 시
     설정된 class로 이동하게 된다.
-->

<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.
view.InternalResourceViewResolver">
   <property name="prefix">
       <value>/WEB-INF/views/</value>
   </property>
   <property name="suffix">
       <value>.jsp</value>
   </property>
</bean>
<!--
ModelAndView mav = new ModelAndView();
    mav.addObject("name", "hong");
    mav.setViewName("Hello");
    
    Hello
    /WEB-INF/views/ + Hello + .jsp
    
    view 주소 : /WEB-INF/views/Hello.jsp
-->
</beans>





HelloController.java

//기존 servlet 과 동일한 역활 >> 요청이 오면 실행 > doGET , doPOST >>> handleRequest
public class HelloController implements Controller {

    public HelloController() {
        System.out.println("HelloController 객체 생성");
    }
    
    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
        System.out.println("HelloController 요청 실행 :handleRequest ");
        //ModelAndView > 데이터를 담을것을 만들고 , view 지정 처리
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "hong"); //request.setAttribute("name","hong")
        mav.setViewName("Hello");
        
        return mav;
    }
}



Class ModelAndView


public class ModelAndView

extends java.lang.Object


Holder for both Model and View in the web MVC framework. Note that these are entirely distinct. This class merely holds both to make it possible for a controller to return both model and view in a single return value.


Represents a model and view returned by a handler, to be resolved by a DispatcherServlet. The view can take the form of a String view name which will need to be resolved by a ViewResolver object; alternatively a View object can be specified directly. The model is a Map, allowing the use of multiple objects keyed by name.



addObject()

public ModelAndView addObject(java.lang.Object attributeValue)

Add an attribute to the model using parameter name generation.


Parameters:

attributeValue - the object to add to the model (never null)

See Also:

ModelMap.addAttribute(Object), getModelMap()


----------------------------------------------------------------------------------------------------------


setViewName()

public void setViewName(@Nullable

java.lang.String viewName)

Set a view name for this ModelAndView, to be resolved by the DispatcherServlet via a ViewResolver. Will override any pre-existing view name or View.


return mav에서 mav를 받는 대상은

Dispatcher로 설정된 spring-servlet.xml 이다!






IntroController.java

public class IntroController implements Controller{

    public IntroController() {
        System.out.println("IntroController 객체 생성 ^^");
    }
    
    
    //handleRequest > servlet (doGET , doPOST) 역할
    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)
throws Exception {
        System.out.println("IntroController 요청 실행 :handleRequest ");
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "bituser");//request.setAttribute()
        mav.setViewName("intro"); // WEB-INF/views/board/intro.jsp
        return mav;
    }
}


return mav에서 mav를 받는 대상은

Dispatcher로 설정된 spring-servlet.xml 이다!






Hello.jsp , intro.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Intro </title>
</head>
<body>
<h3>Intro</h3>
VIEW : ${name}
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello JSP</title>
</head>
<body>
    <h3>HELLO</h3>
    VIEW : ${name}
</body>
</html>


Comments