본문 바로가기
Programming/Spring

Spring MVC (XML 설정 기반)

by TinKerBellBass 2017. 8. 8.
728x90
반응형
참고 도서
스프링 퀵 스타트
국내도서
저자 : 채규태
출판 : 루비페이퍼 2016.06.30
상세보기



1. Spring MVC 전체 구조

1. 클라이언트로부터의 요청을 DispatcherServlet 이 받는다.

2. DispatcherServlet 은 HandlerMapping 을 통해 요청을 처리할 Controller 를 검색.

3. DispatcherServlet 은 검색된 Controller 를 실행하여 클라이언트의 요청을 처리.

4. Controller 는 비지니스 로직의 수행 결과로 얻어낸 Model 정보와 Model 을 보여줄 View 정보를 ModelAndView 객체에    저장하여 리턴

5. DispatcherServlet 은 ModelAndView 객체에서 View 정보를 추출하고, ViewResolver 에서 응답할 View 를 얻어낸다.

    (Model 은 Controller 에서 비지니스 로직이 처리된 후 응답에 필요한 데이터, View 는 응답에 필요한 뷰 정보)

6. DispatcherSerlvet 은 ViewResolver 를 통해 찾아낸 View 를 실행하여 응답을 전송


2. DispatcherServlet

(1) 등록

1
2
3
4
5
6
7
8
9
<!-- WEB-INF/web.xml -->
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
cs

스프링에서 제공하는 DispatcherServlet 을 등록
서블릿 컨테이너는 .do 요청이 들어오면 action 이름으로 등록된 DispatcherServlet 클래스의 객체를 생성
(2)

(2) 스프링 컨테이너 구동
Dispatcher 객체가 생성되면 Dispatcher 클래스에 재정의된 init( ) 메소드가 자동으로 실행되어,
ApplicationContext 인터페이스를 구현한 XmlWebApplicationContext 스프링 컨테이너가 구동.
DispatcherServlet 은 스프링 컨테이너를 구동할 때, WEB-INF/(servlet-name 으로 등록한 이름)-servlet.xml 을 로딩,
위의 코드라면 WEB-INF/action-servlet.xml

XmlWebApplicationContext 컨테이너는 action-servlet.xml 에
<bean> 으로 등록한 HandlerMapping, Controller, ViewResolver 객체들을 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- HandlerMapping 등록 -->
<bean class="org.springframework.webg.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
<!-- /login.do 요청이 키로 들어오면 login 값 반환 -->
            <prop key="/login.do">login</prop>
            <prop key="/getBoardList.do">getBoardList</prop>
            <prop key="/getBoard.do">getBoard</prop>            
        <props>
    </property>
</bean>
 
 
<!-- Controller 등록 -->
<!-- login 값이 반환되면 com.neverland.view.user.LoginController 클래스 객체 생성, 요청 처리 -->
<bean id="login" class="com.neverland.view.user.LoginController" />
<bean id="getBoardList" class="com.neverland.view.board.GetBoardListController" />
<bean id="getBoard" class="com.neverland.view.board.GetBoardController" />
 
 
<!-- ViewResolver 등록 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 응답할 View에 prefix(접두사), suffix(접미사)를 붙여 반환 -->
    <property name="prefix" value="/WEB/INF/board/" />
    <property name="suffix" value=".jsp" />
</bean>
cs

(3) HandlerMapping, Controller, ViewResolver 객체들을 생성하는 스프링 설정 파일 변경


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- WEB-INF/web.xml -->
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!-- HandlerMapping, Controller, ViewResolver 객체가 생성되는 설정 파일 변경 ->
        <param-value>/WEB/INF/congif/presentation-layer.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
 
<!-- 실제 DispatcherServlet.java 파일 
public class DispatcherServlet extends HttpServlet {
    private String contextConfigLocation;
    
    public void init(ServletConfig config) throws ServletException{
        // web.xml 에서 param-name 으로 설정한 contextConfigLocation 파라미터
        contextConfigLocation = config.getInitParameter("contextConfigLocation");
        new XmlWebApplicationContext(contextConfigLocation);
    }
}
-->
cs


3. 한글 필터 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- web.xml -->
<filter>
    <filter-name>characterEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
 
<filter-mapping>
    <filter-name>characterEncoding</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping>
cs



4. Controller  구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.springbook.view.user;
 
import javax.servlet.http.*;
 
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
 
import com.springbook.biz.user.*;
import com.springbook.biz.user.impl.*;
 
public class LoginController implements Controller {
 
    // 클라이언트에서 요청 발생 -> Dispatcher 서블릿 객체 생성 -> HandlerMapping 가 Controller 호출
    // -> Controller 에 재정의 한 handlerRequest 메소드를 통해 요청 처리 -> ModelAndView 객체 반환
    // -> ViewResolver 에서 View 정보 검색 -> 검색된 View 반환
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("로그인 처리");
 
        // 1.사용자 입력 정보 추출
        String id = request.getParameter("id");
        String password = request.getParameter("password");
 
        // 2.DB 연동 처리
        UserVO vo = new UserVO();
        vo.setId(id);
        vo.setPassword(password);
 
        UserDAO userDAO = new UserDAO();
        UserVO user = userDAO.getUser(vo);
 
        // 3.화면 네비게이션
        ModelAndView mav = new ModelAndView();
        if (user != null) {
            // redirect: 를 붙이면 설정한 ViewResolver 를 무시하고 리다이렉트
            mav.setViewName("redirect:getBoardList.do");
        } else {
            mav.setViewName("redirect:login.jsp");
        }
        return mav;
    }
 
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.springbook.view.board;
 
import java.util.*;
 
import javax.servlet.http.*;
 
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
 
import com.springbook.biz.board.*;
import com.springbook.biz.board.impl.*;
 
public class GetBoardListController implements Controller {
 
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("글 목록 검색 처리");
 
        // 1.사용자 입력 정부 추출(검색 기능은 나중에 구현)
        // 2.DB 연동 처리
        BoardVO vo = new BoardVO();
        BoardDAO boardDAO = new BoardDAO();
        List<BoardVO> boardList = boardDAO.getBoardList(vo);
 
        // 3.검색 결과를 세션에 저장하고 목록 화면을 리턴한다.
        ModelAndView mav = new ModelAndView();
        mav.addObject("boardList", boardList); // Model 정보 저장
// ViewResolver 에 의해 /board/getBoardList.jsp 로 응답
        mav.setViewName("getBoardList"); // View 정보 저장
        return mav;
    }
 
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.springbook.view.board;
 
import javax.servlet.http.*;
 
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
 
import com.springbook.biz.board.*;
import com.springbook.biz.board.impl.*;
 
public class GetBoardController implements Controller {
 
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("글 상세 조회 처리");
 
        // 1.검색할 게시글 번호 추출
        String seq = request.getParameter("seq");
 
        // 2.DB 연동 처리
        BoardVO vo = new BoardVO();
        vo.setSeq(Integer.parseInt(seq));
 
        BoardDAO boardDAO = new BoardDAO();
        BoardVO board = boardDAO.getBoard(vo);
 
        // 3.검색 결과를 저장하고 상세 화면을 리턴
        ModelAndView mav = new ModelAndView();
        mav.addObject("board", board);
        mav.setViewName("getBoard");
        return mav;
    }
 
}
cs

5. View 작성 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!-- WEB-INF/login.jsp -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>로그인</title>
</head>
 
<body>
    <h1 style="text-align: center;">로그인</h1>
    <hr />
    <form action="login.do" method="post">
        <table border="1" style="margin: auto;">
            <tr>
                <td bgcolor="orange">아이디</td>
                <td><input type="text" name="id" /></td>
            </tr>
            <tr>
                <td bgcolor="orange">비밀번호</td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="로그인" /></td>
            </tr>
        </table>
    </form>
    <hr />
</body>
</html>
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!-- WEB-INF/board/getBoardList.jsp -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
 
<!DOCTYPE html>
<html>
 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
 
<title>글 목록</title>
</head>
 
<body>
    <h1 style="text-align: center;">글 목록</h1>
    <h3 style="text-align: center;">
        테스트님 환영합니다... <a href="logout.do">Log-out</a>
    </h3>
 
    <!-- 검색 시작 -->
    <form action="getBoardList.jsp" method="post">
        <table border="1" style="margin: auto; width: 700px;">
            <tr>
                <td align="right">
                    <select name="searchCondition">
                        <option value="TITLE">제목</option>
                        <option value="CONTENT">내용</option>
                    </select>
                    <input type="text" name="searchKeyword" />
                    <input type="submit" value="검색" />
                </td>
            </tr>
        </table>
    </form>
    <!-- 검색 종료 -->
 
    <table border="1" style="margin: auto; width: 700px;">
        <tr>
            <th bgcolor="orange" width="100">번호</th>
            <th bgcolor="orange" width="200">제목</th>
            <th bgcolor="orange" width="150">작성자</th>
            <th bgcolor="orange" width="150">등록일</th>
            <th bgcolor="orange" width="100">조회수</th>
        </tr>
 
        <c:forEach items="${boardList }" var="board">
            <tr>
                <td>${board.seq }</td>
                <td align="left">
                    <a href="getBoard.do?seq=${board.seq }">${board.title }</a>
                </td>
                <td>${board.writer }</td>
                <td>${board.regDate }</td>
                <td>${board.cnt }</td>
            </tr>
        </c:forEach>
    </table>
    <p style="text-align: center;">
        <a href="insertBoard.jsp">새글 등록</a>
    </p>
 
</body>
</html>
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!-- WEB-INF/board/getBoard.jsp -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 
<!DOCTYPE html>
<html>
 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>글 상세</title>
</head>
 
<body>
    <div style="text-align: center; margin: auto;">
        <h1>글 상세</h1>
        <a href="logout.do">Log-out</a>
        <hr />
        <form action="updateBoard.do" method="post">
            <input type="hidden" name="seq" value="${board.seq }" />
            <table border="1" style="margin: auto;">
                <tr>
                    <td style="background-color: orange; whdth: 70px;">제목</td>
                    <td align="left">
                        <input type="text" name="title" value="${board.title }" />
                    </td>
                </tr>
                <tr>
                    <td style="background-color: orange; whdth: 70px;">작성자</td>
                    <td align="left">${board.writer }</td>
                </tr>
                <tr>
                    <td style="background-color: orange; whdth: 70px;">내용</td>
                    <td align="left">
                        <textarea name="content" cols="40" rows="10">${board.content }</textarea>
                    </td>
                </tr>
                <tr>
                    <td style="background-color: orange; whdth: 70px;">등록일</td>
                    <td align="left">${board.regDate }</td>
                </tr>
                <tr>
                    <td style="background-color: orange; whdth: 70px;">조회수</td>
                    <td align="left">${board.seq }</td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="글 수정" />
                    </td>
                </tr>
            </table>
        </form>
        <hr />
        <a href="insertBoard.jsp">글등록</a> &nbsp;&nbsp;&nbsp; <a href="deleteBoard.do?seq=${board.seq }">글삭제</a> &nbsp;&nbsp;&nbsp; <a href="getBoardList.do">글목록</a>
    </div>
</body>
</html>
cs


728x90
반응형

'Programming > Spring' 카테고리의 다른 글

Spring Layered Architecture  (0) 2017.08.09
Spring MVC (annotation 기반)  (0) 2017.08.08
Spring JDBC (JdbcTemplate class)  (0) 2017.08.05
AOP(Aspect Oriented Programming)  (0) 2017.08.02
IoC(Inversion of Control) 컨테이너  (0) 2017.08.01

댓글