ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 6. Spring MVC
    개발자 수업/Spring 2021. 12. 30. 16:24

    1. MVC(Model-View-Controller) 패턴
        1) 아키텍쳐 패턴
        2) 주목적 : Business logic과 Presentation logic을 분리하기 위함
        3) 사용자 인터페이스로부터 비즈니스 로직을 분리
            -> 시각적 요소와 그 이면에서 실행되는 비즈니스 로직이 서로 영향 없이 쉽게 고칠 수 있는 애플리케이션을 만들 수 있음
        4) Model : 애플리케이션의 정보(데이터, Business Logic 포함)
           View : 사용자에게 제공할 화면(Presentation Logic)
           Controller : Model과 View 사이 상호 작용을 관리

    2. MVC 컴포넌트 역할
        1) 모델(Model) 컴포넌트
            - 데이터 저장소(DB)와 연동
            - 사용자가 입력한 데이터나 사용자에게 출력할 데이터를 다루는 일을 함
            - 여러 개의 데이터 변경 작업을 하나의 작업으로 묶는 트랜잭션을 다루는 일도 함
            - DAO, VO, Service 클래스에 해당
        2) 뷰(View) 컴포넌트
            - 화면을 만드는 일을 함
            - HTML, JSP, JS, CSS
        3) 컨트롤러 (Controller) 컴포넌트
            - 클라이언트 요청에 대해 모델과 뷰를 결정하여 전달
            - Servlet, JSP

    3. 모델2 아키텍처 개념
        1) 모델1 : Controller 역할을 JSP가 담당함
           모델2 : Controller 역할을 Servlet이 담당함

    4. Spring MVC
        1) DI와 AOP 기능과 더불어 서블릿 기반의 웹 개발을 위한 MVC 프레임워크를 제공
        2) 모델2 아키텍처와 Front Controller 패턴을 프레임워크 차원에서 제공
        3) DispatcherServlet 클래스를 맨 앞단에 놓고, 서버로 들어오는 모든 요청을 받아 처리하는 구성

    5. Spring MVC 주요 구성 요소
        1) DispatcherServlet
        2) HandlerMapping
        3) Controller
        4) ModelAndView
        5) View
        6) ViewResolver

    6. SimplerUrlController

    actionbk-servlet-bk.xml

    <?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:aop="http://www.springframework.org/schema/aop"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:p="http://www.springframework.org/schema/p"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
    	<!-- id가 simpleUrlController인 빈 생성 -->
    	<bean id="simpleUrlController" class="kr.co.ezenac.simpleurl.SimpleUrlController"/>
    	
    	<!-- simpleUrlHandlerMapping 클래스를 이용해 /url/index.do로 요청시 simpleUrlController를 호출하도록 매핑함 -->
    	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    		<property name="mappings">
    			<props>
    				<prop key="/url/index.do">simpleUrlController</prop>
    			</props>
    		</property>
    	</bean> 
    	
    </beans>

     

    SimpleUrlController.java

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    /*
     * 1) 브라우저에 http://localhost:8080/ezen03_SpringMVC/url/index.do로 요청함
     * 2) DispatcherServlet은 요청에 대해 미리 action-servlet.xml에 매핑된 SimpleUrlController를 요청함
     * 3) 컨트롤러는 요청에 대해 url 폴더에 있는 index.jsp를 브라우저로 전송함 
     */
    public class SimpleUrlController implements Controller {
    
    	@Override
    	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		
    		return new ModelAndView("index.jsp");	//작업이 되고 나서 뷰이름을 ModelAndView에 설정해서 반환함
    	}
    
    }

     

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Spring 테스트</title>
    </head>
    <body>
    	<h1>Index.jsp 파일입니다!</h1>
    	<p>welcome to 2022!</p>
    </body>
    </html>



    7. MultiActionController
        - 여러 요청명에 대해 한 개의 컨트롤러에 구현된 각 메서드로 처리할 수 있음
        - InternalResourceViewResolver
            - 뷰 생성하는 기능 제공
            - prefix, suffix 프로퍼티를 이용해 경로를 지정
        - PropertiesMethodNameResolver
            - URL 요청명으로 컨트롤러의 설정 파일에서 미리 설정된 메서드를 바로 호출해서 사용할 수 있음

     

     

    action.xml

    <?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:aop="http://www.springframework.org/schema/aop"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:p="http://www.springframework.org/schema/p"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
    	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    		<property name="prefix" value="/multi/"/>
    		<property name="suffix" value=".jsp"/>
    	</bean>
    	
    	<bean id="userUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    		<property name="mappings">
    			<props>
    				<prop key="/multi/*.do">userController</prop>	<!-- URL 요청명 /multi/*.do로 되면 userController를 요청함 -->
    			</props>
    		</property>
    	</bean>
    	
    	<bean id="userController" class="kr.co.ezenac.multiaction.UserController">
    		<property name="methodNameResolver">
    			<ref local="userMethodNameResolver"/>	<!-- 지정한 요청명에 대해 직접 메서드를 호출 -->
    		</property>
    	</bean>
    	
    	<bean id="userMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
    		<property name="mappings">
    			<props>
    				<prop key="/multi/login.do">login</prop>
    				<prop key="/multi/memberInfo.do">memberInfo</prop>	<!-- URL 요청명과 메서드명을 동일하게하여 회원정보 요청함 -->
    			</props>
    		</property>
    	</bean>	<!-- PropertiesMethodNameResolver를 이용해 /multi/login.do로 요청하면 userController의 login 메서드를 호출 -->
    </beans>

     

    UserController.java

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
    
    public class UserController extends MultiActionController {
    	
    	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		String userId = "";
    		String passwd = "";
    		ModelAndView mav = new ModelAndView();
    		
    		request.setCharacterEncoding("utf-8");
    		
    		userId = request.getParameter("userId");
    		passwd = request.getParameter("passwd");
    		mav.addObject("userId", userId);	//ModelAndView에 로그인 정보를 바인딩함
    		mav.addObject("passwd", passwd);
    		mav.setViewName("result"); 			//ModelAndView 객체에 포워딩할 JSP 이름 설정함
    		return mav;
    	}
    	
    	public ModelAndView memberInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		request.setCharacterEncoding("utf-8");
    		ModelAndView mav = new ModelAndView();
    		
    		String id = request.getParameter("id");
    		String pwd = request.getParameter("pwd");
    		String name = request.getParameter("name");
    		String email = request.getParameter("email");
    		
    		
    		mav.addObject("id", id);		//회원 가입창에서 전송된 회원정보를 addObject()로 ModelAndView 객체에 바인딩함
    		mav.addObject("pwd", pwd);
    		mav.addObject("name", name);
    		mav.addObject("email", email);
    		mav.setViewName("memberInfo");	//memberInfo.jsp로 포워딩함
    		return mav;
    	}
    }

     

    loginForm.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <c:set var="contextPath" value="${pageContext.request.servletContext.contextPath }"/>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>로그인 창</title>
    </head>
    <body>
    	<form name="frmLogin" method="post" action="${contextPath }/multi/login.do">
    		<table border="1" width="80%" align="center">
    			<tr align="center">
    				<td>아이디</td>
    				<td>비밀번호</td>
    			</tr>
    			<tr align="center">
    				<td><input type="text" name="userId" value="" size="20"></td>
    				<td><input type="password" name="passwd" value="" size="20"></td>
    			</tr>
    			<tr align="center">
    				<td colspan="2">
    					<input type="submit" value="로그인">
    					<input type="reset" value="다시입력">
    				</td>
    			</tr>
    		</table>
    	</form>
    </body>
    </html>

     

     

    result.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%
    	request.setCharacterEncoding("utf-8");
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>결과페이지</title>
    </head>
    <body>
    	<table border="1" width=50 align="center">
    		<tr align="center">
    			<td>아이디</td>
    			<td>비밀번호</td>
    		</tr>
    		<tr align="center">
    			<td>${userId }</td>	<!-- 컨트롤러에서 바인딩해 넘어온 회원정보 -->
    			<td>${passwd }</td>
    		</tr>
    	</table>
    </body>
    </html>


    전에 썼던 코드 추가

    memberForm.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:set var="contextPath" value="${pageContext.request.contextPath }"/>
    
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="UTF-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>회원 가입창</title>
    </head>
    <body>
    	<form action="${contextPath }/memberInfo.do" method="post">
    		<h1 style="text-align: center;">회원 가입창</h1>
    		<table align="center">
    			<tr>
    				<td width="200">
    					<p align="right">아이디</p>
    				</td>
    				<td width="400">
    					<input type="text" name="id">
    				</td>
    			</tr>
    			<tr>
    				<td width="200">
    					<p align="right">비밀번호</p>
    				</td>
    				<td width="400">
    					<input type="password" name="pwd">
    				</td>
    			</tr>
    			<tr>
    				<td width="200">
    					<p align="right">이름</p>
    				</td>
    				<td width="400">
    					<input type="text" name="name">
    				</td>
    			</tr>
    			<tr>
    				<td width="200">
    					<p align="right">이메일</p>
    				</td>
    				<td width="400">
    					<input type="text" name="email">
    				</td>
    			</tr>
    			<tr>
    				<td width="200">
    					<p align="right">&nbsp;</p>
    				</td>
    				<td width="400">
    					<input type="submit" value="가입하기">
    					<input type="reset" value="다시입력">
    				</td>
    			</tr>
    		</table>
    	</form>
    </body>
    </html>

     

     

    memberInfo.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>회원 정보 출력</title>
    </head>
    <body>
    	<table border="1" align="center" width=100%>
    		<tr align="center" bgcolor="lightblue">
    			<td><b>아이디</b></td>
    			<td><b>비밀번호</b></td>
    			<td><b>이름</b></td>
    			<td><b>이메일</b></td>
    		</tr>
    		<tr>
    			<td>${id }</td>
    			<td>${pwd }</td>
    			<td>${name }</td>
    			<td>${email }</td>
    		</tr>
    	</table>
    </body>
    </html>

     

    '개발자 수업 > Spring' 카테고리의 다른 글

    8. 스프링 트랜잭션  (0) 2022.01.04
    7. MyBatis Framework 사용 (수정중)  (0) 2021.12.31
    5. AOP  (0) 2021.12.29
    4. IoC와 DI  (0) 2021.12.29
    3. 스프링 의존성 주입  (0) 2021.12.29

    댓글