AbstractController을 이용한 스프링 컨트롤러 작성
web.xml
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 | <! --?xml version="1.0" encoding="UTF-8"?--> <web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "WebApp_ID" version= "2.5" > <display- name >spring3</display- name > <welcome-file-list> <welcome-file> index .html</welcome-file> <welcome-file> index .htm</welcome-file> <welcome-file> index .jsp</welcome-file> <welcome-file> default .html</welcome-file> <welcome-file> default .htm</welcome-file> <welcome-file> default .jsp</welcome-file> </welcome-file-list> <! -- 스프링 환경 설정 시작 --> <! -- ContextLoaderListener : 서로 다른 DispatcherServlet이 공통으로 사용될 빈 설정 --> <! -- context-param 태그로 설정파일을 지정하지 않으면 applicationContext.xml이 설정 파일이 된다. --> <! -- <context-param> <param- name >contextConfigLocation</param- name > <param-value>/WEB-INF/service.xml, /WEB-INF/common.xml</param-value> </context-param> --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! -- 스프링 컨트롤러 --> <servlet> <servlet- name >dispatcher</servlet- name > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! -- <init-param> <param- name >contextConfigLocation</param- name > <param-value> /WEB-INF/dispatcher-servlet.xml, /WEB-INF/front.xml </param-value> </init-param> --> < load - on -startup>1</ load - on -startup> </servlet> <servlet-mapping> <servlet- name >dispatcher</servlet- name > <url-pattern>*. action </url-pattern> </servlet-mapping> <! -- 인코딩 필터 --> <filter> <filter- name >encodingFilter</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 >encodingFilter</filter- name > <url-pattern>/*</url-pattern> </filter-mapping> </web-app> |
com.hello.HelloService
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.hello; public class HelloService { public String getMessage() { String msg = null ; int h = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); if(h>=6 && h<9) msg = "좋은 아침" ; else if(h>=9 && h<13) msg = "오전 수업 시간" ; else if(h>=13 && h<14) msg = "점심" ; else if(h>=14 && h<18) msg = "오후수업시간" ; else msg = "자유시간" ; return msg; } } |
dispatcher-servlet.xml
com.hello.HelloController
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 | package com.hello; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloController extends AbstractController { private HelloService helloService; public void setHelloService(HelloService helloService) { this.helloService = helloService; } @Override protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName( "hello/result" ); mav.addObject( "msg" , helloService.getMessage()); return mav; //혹은 req.setAttribute( "msg" , helloService); return new ModelAndView( "hello/result" ); } } |
WEB-INF/hello/result.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <%@ page contentType= "text/html; charset=UTF-8" %> <%@ page trimDirectiveWhitespaces= "true" %> <% String cp = request.getContextPath(); request.setCharacterEncoding( "utf-8" ); %> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title> Insert title here</title> 스프링을 이용한 첫번째 MVC2 패턴 프로그래밍<br> ${msg} |
설명
1. 클라이언트가 hello.action 요청
2. xml → dispatcher 호출
1 2 3 4 5 6 7 8 | <servlet> <servlet- name >dispatcher</servlet- name > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet- name >dispatcher</servlet- name > <url-pattern>*. action </url-pattern> </servlet-mapping> |
3. dispatcher → beanNameUrlHandlerMapping
1 2 3 | <bean id= "beanNameUrlHandlerMapping" class= "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" > <property name = "order" value= "1" > // order : 실행되는 매핑의 순서를 결정 </property></bean> |
beanNameUrlHandlerMapping은 클라이언트가 요청한 uri를 전달받는다.
전달받은 uri로 해당작업을 수행할 컨트롤러를 검색
* 매핑은 생성된 컨트롤러의 이름을 검색함.
1 2 3 4 | <bean name = "/hello.action" class= "com.hello.HelloController" > <span> .... </span></bean><span> </span> |
4. 매핑은 컨트롤러 객체를 리턴하고 dispatcher는 다시 해당 컨트롤러의 handleRequestInternal 메서드 호출
5. 호출된 컨트롤러는 프로그램된 구문을 실행하고 ModelAndView객체를 리턴한다.
1 2 3 4 5 | <bean id= "helloService" class= "com.hello.HelloService" > <bean name = "/hello.action" class= "com.hello.HelloController" > <property name = "helloService" ref= "helloService" > </property></bean> </bean> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class HelloController extends AbstractController { private HelloService helloService; public void setHelloService(HelloService helloService) { this.helloService = helloService; } @Override protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception { /*ModelAndView mav = new ModelAndView(); mav.setViewName( "hello/result" ); mav.addObject( "msg" , helloService.getMessage()); return mav;*/ req.setAttribute( "msg" , helloService.getMessage()); return new ModelAndView( "hello/result" ); } } |
1 2 3 4 5 | AbstractController ac = new HelloController(); ac.handleRequestInternal() // User user = new UserImpl() // user .result(); |
6. ModelAndView를 리턴받은 dispatcher는 resolver를 호출한다. (인자값으로 컨트롤러의 리턴값)
1 2 3 4 | <bean id= "viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name = "prefix" value= "/WEB-INF/views/" > <property name = "suffix" value= ".jsp" > </property></property></bean> |
1 2 3 4 | <bean id= "viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name = "prefix" value= "/WEB-INF/views/" > <property name = "suffix" value= ".jsp" > </property></property></bean> |
7. resolver는 prefix + "viewName" + suffix를 리턴
8. 최종적으로 dispatcher가 해당 view로 포워딩
MultiActionController을 이용한 스프링 컨트롤러 작성
예제
web.xml
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 | <! --?xml version="1.0" encoding="UTF-8"?--> <web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "WebApp_ID" version= "2.5" > <display- name >spring3</display- name > <welcome-file-list> <welcome-file> index .html</welcome-file> <welcome-file> index .htm</welcome-file> <welcome-file> index .jsp</welcome-file> <welcome-file> default .html</welcome-file> <welcome-file> default .htm</welcome-file> <welcome-file> default .jsp</welcome-file> </welcome-file-list> <! -- 스프링 환경 설정 시작 --> <! -- ContextLoaderListener : 서로 다른 DispatcherServlet이 공통으로 사용될 빈 설정 --> <! -- context-param 태그로 설정파일을 지정하지 않으면 applicationContext.xml이 설정 파일이 된다. --> <! -- <context-param> <param- name >contextConfigLocation</param- name > <param-value> /WEB-INF/service.xml, /WEB-INF/common.xml </param-value> </context-param> --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! -- 스프링 컨트롤러 --> <servlet> <servlet- name >dispatcher</servlet- name > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! -- <init-param> <param- name >contextConfigLocation</param- name > <param-value> /WEB-INF/dispatcher-servlet.xml, /WEB-INF/front.xml </param-value> </init-param> --> < load - on -startup>1</ load - on -startup> </servlet> <servlet-mapping> <servlet- name >dispatcher</servlet- name > <url-pattern>*. action </url-pattern> </servlet-mapping> <! -- 인코딩 필터 --> <filter> <filter- name >encodingFilter</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 >encodingFilter</filter- name > <url-pattern>/*</url-pattern> </filter-mapping> </web-app> |
com.bbs.Board
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 | package com.bbs; public class Board { private int num; private String name , subject, content, created; public int getNum() { return num; } public void setNum( int num) { this.num = num; } public String getName() { return name ; } public void setName(String name ) { this. name = name ; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } } |
dispatcher-servlet.xml
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 | <! --?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" xmlns:util= "http://www.springframework.org/schema/util" xmlns:task= "http://www.springframework.org/schema/task" xsi:schemalocation= " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd" > <bean id= "handlerMapping" class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name = "alwaysUseFullPath" value= "true" > <property name = "order" value= "1" > <property name = "mappings" > //property : private String name , 즉 인스턴스변수 <props> //props : properties <prop key = "/bbs/*.action" >bbs.boardController</prop> //여기서 bbs.boardController는 value //아래에 bean으로 생성할 객체 bbs.boardController를 찾아간다. </props> </property> </property></property></bean> <bean id= "bbs.boardController" class= "com.bbs.BoardController" > <property name = "methodNameResolver" ref= "propsResolver" > </property></bean> <bean id= "propsResolver" class= "org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver" > <property name = "mappings" > <props> //props : properties <prop key = "/bbs/list.action" >list</prop> <prop key = "/bbs/created.action" >createdForm</prop> <prop key = "/bbs/created_ok.action" >createdSubmit</prop> </props> //propsResolver의 인스턴스변수 mappings에 각 key 에 해당된 value 할당 </property> </bean> <bean id= "viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name = "prefix" value= "/WEB-INF/views/" > <property name = "suffix" value= ".jsp" > </property></property></bean> </beans> |
com.bbs.BoardController
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 | package com.bbs; 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 BoardController extends MultiActionController { public ModelAndView list(HttpServletRequest req, HttpServletResponse resp) throws Exception { return new ModelAndView( "bbs/list" ); } public ModelAndView createdForm(HttpServletRequest req, HttpServletResponse resp) throws Exception { return new ModelAndView( "bbs/write" ); } public ModelAndView createdSubmit(HttpServletRequest req, HttpServletResponse resp) throws Exception { return new ModelAndView( "bbs/write_ok" ); } } |
view
1 2 3 4 5 6 7 | list.jsp 게시판 리스트<br> <a href= "<%=cp%>/bbs/created.action" >글쓰기</a> |
1 2 3 4 5 6 7 8 9 10 11 | write.jsp <form action = "<%=cp%>/bbs/created_ok.action" method= "post" > 이름 : <input type= "text" name = "name" ><br> 제목 : <input type= "text" name = "subject" ><br> 내용 : <textarea rows = "5" cols= "60" name = "content" ></textarea><br> <input type= "submit" value= "등록" > </form> |
1 2 3 4 5 6 7 8 9 10 11 | write_ok.jsp 입력한 내용 <br> 이름 : ${dto. name } <br> 제목 : ${dto.subject} <br> 내용 : ${dto.content}<br> <a href= "<%=cp%>/bbs/list.action" >뒤로가기</a> |
설명
1. WEB-INF/web.xml
1 2 3 4 5 6 7 8 9 | <servlet> <servlet- name >dispatcher</servlet- name > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet- name >dispatcher</servlet- name > <url-pattern>*. action </url-pattern> </servlet-mapping> |
1) 기본적으로 스프링환경설정파일은 서블릿이름-servlet.xml 이다.
→ dispatcher-servlet.xml
2) 클라이언트가 *.action 으로 요청하면 DispatcherServlet이 처리를 담당한다.
2. MultiActionController을 이용한 스프링 컨트롤러 작성
- MultiActionController는 하나의 컨트롤러를 이용하여 여러 요청을 처리할수 있다. 예를 들어 게시판에서 글리스트, 글쓰기폼, 글저장, 글보기, 글수정폼, 글수정완료, 글삭제등의 여러 요청을 하나의 컨트롤러로 처리할수 있다.
- 클라이언트가 *.action 으로 요청할 경우 흐름
1) DispatcherServlet이 클라이언트의 요청을 받는다.
2) HandlerMapping이 클라이언트의 요청 URL을 어떤 Controller가 처리할지를 결정한다.
3) 결정된 컨트롤러는 클라이언트의 요청을 처리한 뒤, 그 결과를 DispatcherServlet에 알려준다.
4) ViewResolver는 처리 결과를 보여줄 View를 결정한다.
5) View는 처리 결과를 보여줄 응답을 생성한다.
- 프로그램 작성
1) service 클래스를 작성한다.(비지니즈 로직을 처리)
2) MultiActionController를 상속받은 controller를 작성 한다.
요청을 받아 처리할 메소드명은 프로그래머가 임의로 지정하며 다음의 형식을 따른다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public [ModelAndView|Map|void] 메서드이름 (HttpServletRequest req, HttpServletResponse resp, [HttpSession|Command]) [throws Exception] { ... ... } (1) return type : ModelAndView, Map, void 중 하나 (2) argument : 1- HttpServletRequest 2- HttpServletResponse 3- 선택적이며 HttpSession 또는 Command 4- Command (3) ModelAndView는 컨트롤러의 처리 결과를 보여줄 뷰와 뷰에 전달할 값을 저장할 용도로 사용된다. |
- dispatcher-servlet.xml 에서 환경 설정
1) HandlerMapping 설정
1 2 3 4 5 6 7 8 9 | <bean id= "handlerMapping" class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name = "alwaysUseFullPath" value= "true" > <property name = "order" value= "1" > <property name = "mappings" > <props> <prop key = "/bbs/*.action" >bbs.boardController</prop> </props> </property> </property></property></bean> |
클라이언트가 /bbs/*.action 형식으로 요청하면 bbs.boardController 라는 id를 가진 컨트롤러가 요청을 처리한다.
2) ViewResolver 설정
1 2 3 4 | <bean id= "viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name = "prefix" value= "/WEB-INF/views/" > <property name = "suffix" value= ".jsp" > </property></property></bean> |
3) MethodNameResolver 등록
어떤 메소드가 클라이언트의 요청을 처리할 것인지 결정한다.
MultiActionController에서는 반드시 필요 하다.
1 2 3 4 5 6 7 8 9 10 | <bean id= "propsResolver" class= "org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver" > <property name = "mappings" > <props> <prop key = "/bbs/list.action" >list</prop> <prop key = "/bbs/created.action" >createdForm</prop> <prop key = "/bbs/created_ok.action" >createdSubmit</prop> </props> </property> </bean> |
4) 컨트롤러 및 서비스 객체 생성
1 2 3 | <bean id= "bbs.boardController" class= "com.bbs.BoardController" > <property name = "methodNameResolver" ref= "propsResolver" > </property></bean> |
'JSP > JspServlet' 카테고리의 다른 글
tag : core (0) | 2013.08.16 |
---|---|
서버 도메인 확인 (0) | 2013.08.16 |
MVC 관련 핸들러 매핑 및 컨트롤러 (0) | 2013.07.29 |
액션 태그와 커스텀 태그 (0) | 2013.07.29 |
파입업로드/다운로드 (0) | 2013.07.29 |