1 / 35

Spring MVC

Spring MVC. ㅇ 스프링 MVC. Spring MVC. ㅇ 스프링 MVC 흐름. Controller. HandlerMapping. 4. 처리 요청. 2. url 과 매핑되는 Controller 검색. 3. 처리할 Controller 리턴. 5. 처리 결과를 ModelAndView 로 리턴. 1. 처리요청 (url). 클라이언트. DispatcherServlet. 6. 결과를 출력할 View 검색. 7. 결과를 출력할

venus
Télécharger la présentation

Spring MVC

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Spring MVC ㅇ 스프링 MVC

  2. Spring MVC ㅇ 스프링 MVC 흐름 Controller HandlerMapping 4. 처리 요청 2. url과 매핑되는 Controller 검색 3. 처리할 Controller 리턴 5. 처리 결과를 ModelAndView로 리턴 1. 처리요청(url) 클라이언트 DispatcherServlet 6. 결과를 출력할 View 검색 7. 결과를 출력할 View 위치 리턴 8. 결과 출력 View ViewResolver

  3. Spring MVC ㅇ필요 라이브러리 - spring-web.jar - spring-webmvc.jar

  4. Spring MVC web.xml … 생략 … <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>*.do</url-pattern> </servlet-mapping> … 생략 …

  5. Spring MVC dispatcher-servlet.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:context="http://www.springframework.org/schema/context" 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"> <context:component-scan base-package="edu.seowon.mvc"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>

  6. Spring MVC TestController.java @Controller public class TestController { @RequestMapping("/first.do") public ModelAndView first() { ModelAndViewmav = new ModelAndView(); mav.setViewName("first"); mav.addObject("var", "FIRST"); return mav; } @RequestMapping("/second.do") public String second(Model model) { model.addAttribute("var", "SECOND"); return "second"; } }

  7. Spring MVC first.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>First</title> </head> <body> First :: ${var} </body> </html>

  8. Spring MVC second.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Second</title> </head> <body> Second :: ${var} </body> </html>

  9. Spring MVC Service ㅇ 기존 Model2 : Controller  Model(DAO)  DB ㅇ 스프링 : Controller  Service  Model(DAO)  DB 비즈니스 로직 처리 / 트랜잭션 단위 / 여러 개의 DAO를 호출 Client Controller Service Dao (Model) request DB Forward View (JSP) response

  10. Spring MVC 연습 ㅇ 프로젝트 구조

  11. Spring MVC 연습 ㅇ 프로젝트 구성 파일 설명

  12. Spring MVC 연습 web.xml … 생략 … <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>*.do</url-pattern> </servlet-mapping> … 생략 …

  13. Spring MVC 연습 dispatcher-servlet.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:context="http://www.springframework.org/schema/context" 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"> <context:component-scan base-package="mvc.spring" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>

  14. Spring MVC 연습 HelloController.java @Controller public class HelloController { @Autowired private HelloServicehelloService; @RequestMapping("intro/hello") public ModelAndView hello() { ModelAndViewmav = new ModelAndView(); String value = null; value = "Hello " + helloService.getName(); mav.addObject("value", value); mav.setViewName("hello"); return mav; } }

  15. Spring MVC 연습 HelloService.java @Service public class HelloService { @Autowired private HelloDaohelloDao; public String getName() { String name = helloDao.selectMember(); return name; } }

  16. Spring MVC 연습 HelloDao.java @Repository public class HelloDao{ public String selectMember() { return "SPRING"; } }

  17. Spring MVC 한글처리 ㅇweb.xml <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>

  18. 컨트롤러 메소드 파라미터 @RequestMapping

  19. 컨트롤러 메소드 파라미터 @RequestMapping ㅇvalue @RequestMapping(“/hello”) @RequestMapping({“/hello”, “/hello/”, “hello.*”}) @RequestMapping(“main*”) @RequestMapping(“/admin/*/user”) @RequestMapping(“/admin/**/user”) ㅇmethod @RequestMapping(value=“/hello.do”, method=RequestMethod.GET) @RequestMapping(value=“/hello.do”, method=RequestMethod.POST) ㅇparams @RequestMapping(value=“/hello.do”, params=“type”) @RequestMapping(value=“/hello.do”, params=“type=admin”) @RequestMapping(value=“/hello.do”, params=“/user/edit”) @RequestMapping(value=“/hello.do”, params=“!type”) ㅇheaders @RequestMapping(value=“/hello.do”, headers=“Content-Type=text/*”)

  20. 컨트롤러 메소드 파라미터 @RequestMapping ㅇconsumes @RequestMapping(consumes=“application/json”) @RequestMapping(consumes={“application/json”, “multipart/form-data”}) ※@RequestMapping(headers=“Content-Type=application/json”) ㅇproduces @RequestMapping(produces=“text/html”) @RequestMapping(produces={“text/html”, “application/json”}) ※@RequestMapping(headers=“Accept=application/json”)

  21. 컨트롤러 메소드 파라미터 @RequestParam ㅇ 요청주소 http://localhost/list.do?currentPage=1&searchText=abcd @Controller public class ListController { @RequestMapping(“list.do”) public ModelAndView list(@RequestParam(“currentPage”) int currentPage, @RequestParam(“searchText”) String searchText) { ...... } } @RequestParam을 지정하는 경우 반드시 요청 주소에 해당 파라미터가 존재해야 됨 필수 파라미터로 쓰지 않으려면 requeired를 false로 변경 null을 지정 못하는 타입은 defaultValue로 사용 ex) @RequestParam(value=“searchText”, required=false) String searchText @RequestParam(value=“currentPage”, defaultValue=“1”) int currentPage

  22. 컨트롤러 메소드 파라미터 @CookieValue @RequestMapping(“/cookie/view.do”) public String view(@CookieValue(“auth”) String authValue) { ..... } 해당 쿠키가 존재하지 않으면 500 에러 발생 쿠키가 필수가 아닌 경우 required 속성을 false로 지정 defaultValue를 사용하여 기본값 지정 가능

  23. 컨트롤러 메소드 파라미터 @RequestHeader @RequestMapping(“/header/check.do”) public String check(@RequestHeader(“Accept-Language”) String languageHeader) { ..... } 해당 헤더가 존재하지 않으면 500 에러 발생 쿠키가 필수가 아닌 경우 required 속성을 false로 지정 defaultValue를 사용하여 기본값 지정 가능

  24. 컨트롤러 메소드 파라미터 ㅇ 서블릿 API 직접 사용 - javax.servlet.http.HttpServletRequest / javax.servlet.ServletRequest - javax.servlet.http.HttpServletResponse / javax.servlet.ServletResponse - javax.servlet.http.HttpSession @RequestMapping(“/anything.do”) public ModelAndView anything(HttpServletRequest request, HttpServletResponse response, HttpSession session) { ..... }

  25. 컨트롤러 메소드 리턴 타입

  26. 뷰 이름 명시적 지정 ㅇModelAndView @RequestMapping(“/main.do”) public ModelAndView main() { ModelAndView mav = new ModelAndView(); mav.setViewName(“main”); return mav; } ㅇString @RequestMapping(“/main.do”) public String main() { return “admin/main”; }

  27. 뷰 이름 자동 지정 ㅇRequestToViewNameTranslator 를 이용하여 URL로부터 뷰 이름 결정 - 리턴 타입이 Model 또는 Map 인 경우 - 리턴 타입이 void 이면서 ServletResponse 또는 HttpServletResponse 타입의 파라미터가 없는 경우 @RequestMapping(“/search/list.do”) public Map<String, Object> searchList() { Map<String, Object> map = new HashMap<String, Object>(); return map; } /search/list.do  search/list

  28. 리다이렉트 뷰 ㅇredirect:/bbs/list : 현재 서블릿 컨텍스트에 대한 상대적인 경로 ㅇ redirect:http://localhost/bbs/list : 절대 경로 사용 예) ModelAndView mav = new ModelAndView(); mav.setViewName(“redirect:/list.do”); return mav;

  29. 뷰로 전달되는 모델 데이터 ㅇ@RequestMapping이 적용된메소드가 ModelAndView / Model / Map을 리턴하는 경우해당 객체에 담긴 모델 데이터가 뷰로 전달 ㅇ @RequestMapping이 적용된 메소드가 가지는 파라미터(클래스) ㅇ @ModelAttribute가 적용된 메소드가 리턴한 객체 @ModelAttribute(“searchTypeList”) public List<SearchType> searchTypeList() { List<SearchType> options = new ArrayList<SearchType>(); option.add(new SearchType(1, “전체”)); option.add(new SearchType(2, “아이템”)); option.add(new SearchType(3, “캐릭터”)); return options; } @RequestMapping(“/search/game.do”) public ModelAndView search( @ModelAttribute(“command”) SC sc, ModelMap model) { ..... }

  30. ModelAndView 모델 설정 ㅇsetViewName(String viewName)  뷰 이름 지정 ㅇ addObject(String key, Object value)  해당 key로 value 지정 ㅇ addAllObjects(Map<String, ?> map)  Map 타입 객체 지정

  31. @PathVariable – URI 템플릿 ㅇ@RequestMapping 값으로 {템플릿 변수} 사용 ㅇ @PathVariable를 이용해서 {템플릿 변수}와동일한 이름을 갖는 파라미터 추가 @RequestMapping(“/game/users/{userId}/characters/{characterId}”) public String characterInfo(@PathVariable String userId, @PathVariable String characterId, ModelMap model) { model.addAttribute(“userId”, userId); model.addAttribute(“characterId”, characterId); return “game/chracter/{characterId}”; }

  32. @ResponseBody ㅇreturn String @RequestMapping(value=“/ajax/hello.do") @ResponseBody public String ajaxHello () { return “<html><body>Hello</body></html>”; } ㅇMessageConverter <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> </list> </property> </bean>

  33. @ResponseBody ㅇreturn Map @RequestMapping("/ajax/getData.do") @ResponseBody public Map<String, Object> ajaxGetData() { Map<String, Object> map = new HashMap<String, Object>(); map.put("a", 1); map.put(“b", "abcd"); List<String> list = new ArrayList<String>(); list.add("HI"); list.add("HELLO"); map.put("list", list); return map; } ㅇMessageConverter <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json. MappingJacksonHttpMessageConverter" /> </list> </property> </bean>

  34. MessageConverter ㅇByteArrayHttpMessageConverter - Request : HTTP 본문을 byte 배열로 변경 - Response : Content-Type 을 octet-stream 으로 변경 ㅇStringHttpMessageConverter - Request : HTTP 본문을 String 으로 변경 - Response : Content-Type 을 text/plain으로 변경 ㅇFormHttpMessageConverter - application/x-www-form-urlencoded로 정의된 폼 데이터를 주고 받을때 사용 ㅇSourceHttpMessageConverter - application/xml, application*+xml, text/xml 지원 - XML 문서를 DomSource, SAXSource, StreamSource전환시 사용 위 4가지 MessageConverter기본 등록

  35. MessageConverter ㅇJaxb2RootElementHttpMessageConverter - JAXB2의 @XmlRootElement와 @XmlType이 붙은 클래스를 이용해서 XML과 오브젝트 사이의 메시지 변환 지원 - JAXB2의 스키마 컴파일러를 통해 생성된 바인딩용 클래스를 이용하여 XML과 오브젝트 변환 ㅇMarsharllingHttpMessageConverter - Marshaller와 Unmarsharller를 이용해서 XML 문서와 자바 오브젝트 변환 ㅇMappingJacksonHttpMessageConverter - 자바 오브젝트와 JSON 자동 변환 위 3가지 MessageConverter등록 시 기본 컨버터 자동 등록되지 않음

More Related