O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.
Spring Framework - MVC                SPRING FRAMEWORK 3.0Dmitry Noskov   Spring MVC
The Spring WEB stack              Spring Framework - MVC   Dmitry Noskov
MVC      Spring Framework - MVC   Dmitry Noskov
Web frameworks   request-based       Struts, Spring MVC   component-based       JSF, GWT, Wicket   RIA       Flex   ...
What is Spring MVC?   web component of Spring Framework   request based web framework                      Spring Framew...
Request processing workflow                 Spring Framework - MVC   Dmitry Noskov
Front controller<servlet>  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>  <servlet-class>org.springframework....
Application context<web-app version="2.5">  <context-param>   <param-name>contextConfigLocation</param-name>   <param-valu...
Context          Spring Framework - MVC   Dmitry Noskov
UrlRewritehttp://www.tuckey.org/urlrewrite/<filter>  <filter-name>UrlRewriteFilter</filter-name>  <filter-class>org.tuckey...
Mapping<urlrewrite default-match-type="wildcard"> <rule>   <from>/</from>   <to>/app/welcome</to> </rule> <rule>   <from>/...
WebApplicationContextUtils(1)public class ExchangerServlet extends HttpServlet {    private AccountService accountService;...
WebApplicationContextUtils(2)public class ExchangerFilter implements Filter {    private AccountService accountService;   ...
Controller@Controller@RequestMapping@RequestParam@PathVariable              Spring Framework - MVC   Dmitry Noskov
Mapping requests   by path@RequestMapping("/welcome")   by HTTP method@RequestMapping(value = "/welcome", method=Request...
Simple Controller@Controllerpublic class WelcomeController {    @RequestMapping("/welcome")    public void welcome() {    ...
Use case controller@Controllerpublic class CarController {    @RequestMapping("/showcar.do")    public String show(@Reques...
Unfriendly URLs                            direct commandURL: http://localhost:8080/carbase/showcar.do?id=77              ...
REST   Representation State Transfer   style of software architecture   RPC is antipode   http://en.wikipedia.org/wiki...
Http methods   get   post       when the resource URL is unknown (create item)   put       when the resource URL is k...
RESTful mappingResource                        GET                       PUT       POST       DELETEhttp://domain.com/cars...
RESTful URLsURL: http://localhost:8080/carbase/cars/11                        Spring Framework - MVC   Dmitry Noskov
Typical actions   simple list page   filtered list page   CRUD:     create     read (retrieve)     update     delet...
List pageURL: http://localhost:8080/carbase/cars@Controller@RequestMapping("/cars")public class CarController {    @Reques...
Detailed pageURL: http://localhost:8080/carbase/cars/11@Controller@RequestMapping("/cars")public class CarController {    ...
CreateURL: http://localhost:8080/carbase/cars@Controller@RequestMapping("/cars")public class CarController {    @RequestMa...
UpdateURL: http://localhost:8080/carbase/cars/@Controller@RequestMapping("/cars")public class CarController {    @RequestM...
DeleteURL: http://localhost:8080/carbase/cars/11@Controller@RequestMapping("/cars")public class CarController {    @Reques...
Filtered pageURL: http://localhost:8080/carbase/cars@Controller@RequestMapping("/cars")public class CarController {    @Re...
Delete and put through post   Spring tag    <form:form action="/carbase/cars" method="PUT">   html    <form id="car" act...
Handler arguments   HttpSession / HttpServletRequest / etc.   Spring’s WebRequest / NativeWebRequest   path variable  ...
Return types   ModelAndView   Model / Map / ModelMap   View   String / void   @ResponseBody / @ModelAttribute   http...
Additional annotations@ModelAttribute@SessionAttributes@RequestHeader@CookieValue@RequestBody / @ResponseBody            S...
ModelAttribute   maps a model attribute to the specific parameter@RequestMapping(method = RequestMethod.POST)public Strin...
SessionAttributes   list the names or types of model attributes which should    be stored in the session@Controller@Sessi...
RequestHeader   typical request headerhost = localhost:8080user-agent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; r...
CookieValue   get the JSESSIONID of the cookie    @RequestMapping(value = "/welcome")    public void welcome(@CookieValue...
Data Representation           Spring Framework - MVC   Dmitry Noskov
Approach   template view     ViewResolver, View     HTML, Excel, PDF, etc.   data view     HttpMessageConverter     ...
View resolver   XmlViewResolver   ResourceBundleViewResolver   UrlBasedViewResolver   InternalResourceViewResolver   ...
View   JSP & JSTL   Tiles   Velocity   FreeMarker   etc.   prefix     redirect:     forward:                  Spri...
ResourceBundleViewResolver   configuration<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> ...
UrlBasedViewResolver<bean id="viewResolver"       class="org.springframework.web.servlet.view.UrlBasedViewResolver">    <p...
Tiles(1)   configuration<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">  <property name="viewCla...
Tiles(2)<bean id="tilesConfigurer"      class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">  <property na...
HttpMessageConverter   reads the request body and writes the response   converters mapped to content types   http://sta...
ContentNegotiatingViewResolver           Spring Framework - MVC   Dmitry Noskov
Strategies   URI     www.domain.com/cars.html     www.domain.com/cars.json   content negotiation     Accept: text/htm...
Example(1)<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> ...
Example(2)<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value=...
Additional featuresLocalesThemesFile uploadHandling mappings / exceptions                 Spring Framework - MVC   Dmitry ...
Locales   LocaleResolver       AcceptHeaderLocaleResolver       CookieLocaleResolver       SessionLocaleResolver   Lo...
Themes   ThemeSource       ResourceBundleThemeSource   ThemeResolver     FixedThemeResolver     SessionThemeResolver ...
File upload   MultipartResolver<bean id="multipartResolver"       class="org.springframework.web.multipart.commons.Common...
Handling mappings   interceptors   default handler   order   lazy init handlers<bean id="handlerMapping"class="org.spr...
Handler interceptorspublic interface HandlerInterceptor {    /** Called before HandlerAdapter invokes the handler.    * @r...
Handling Exceptions   application       HandlingExeptionResolver   controller       @ExceptionHandler(Exception.class)...
Magic tags<mvc:annotation-driven><mvc:interceptors><mvc:view-controller><mvc:resources><mvc:default-servlet-handler>      ...
mvc:annotation-driven   registers necessary beans   support formatting     Number fields using the @NumberFormat     D...
mvc:interceptors<!-- register "global" interceptor beans to apply to allregistered HandlerMappings --><mvc:interceptors> <...
mvc:view-controller   immediately forwards to a view when invoked    <mvc:view-controller path="/" view-name="index"/>   ...
mvc:resources<!-- Handles HTTP GET requests for /resources/** by efficientlyserving up static resources --><mvc:resources ...
mvc:default-servlet-handler<!-- Allows for mapping the DispatcherServlet to "/" byforwarding static resource requests to t...
Ajax       Spring Framework - MVC   Dmitry Noskov
Getting JSON   server@RequestMapping(value="/availability", method=RequestMethod.GET)public @ResponseBody AvailabilitySta...
Post JSON   client$("#account").submit(function() {    var account = $(this).serializeObject();    $.postJSON("account", ...
Spring Framework - MVC   Dmitry Noskov
Features   clear separation of roles   reusable business code   flexible model transfer   customizable binding and val...
Spring MVC   lightweight web framework   controller is a Spring bean                         Spring Framework - MVC   Dm...
Information   reference       http://www.springsource.org/documentation   samples       https://src.springsource.org/s...
Questions            Spring Framework - MVC   Dmitry Noskov
The end             http://www.linkedin.com/in/noskovd      http://www.slideshare.net/analizator/presentations
Próximos SlideShares
Carregando em…5
×

Spring Framework - MVC

12.388 visualizações

Publicada em

Introduction to Spring MVC.

Publicada em: Tecnologia, Educação
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui

Spring Framework - MVC

  1. 1. Spring Framework - MVC SPRING FRAMEWORK 3.0Dmitry Noskov Spring MVC
  2. 2. The Spring WEB stack Spring Framework - MVC Dmitry Noskov
  3. 3. MVC Spring Framework - MVC Dmitry Noskov
  4. 4. Web frameworks request-based  Struts, Spring MVC component-based  JSF, GWT, Wicket RIA  Flex Spring Framework - MVC Dmitry Noskov
  5. 5. What is Spring MVC? web component of Spring Framework request based web framework Spring Framework - MVC Dmitry Noskov
  6. 6. Request processing workflow Spring Framework - MVC Dmitry Noskov
  7. 7. Front controller<servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/web-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <url-pattern>/app/*</url-pattern></servlet-mapping> Spring Framework - MVC Dmitry Noskov
  8. 8. Application context<web-app version="2.5"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/root-context.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener></web-app> Spring Framework - MVC Dmitry Noskov
  9. 9. Context Spring Framework - MVC Dmitry Noskov
  10. 10. UrlRewritehttp://www.tuckey.org/urlrewrite/<filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class></filter><filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping> Spring Framework - MVC Dmitry Noskov
  11. 11. Mapping<urlrewrite default-match-type="wildcard"> <rule> <from>/</from> <to>/app/welcome</to> </rule> <rule> <from>/**</from> <to>/app/$1</to> </rule> <outbound-rule> <from>/app/**</from> <to>/$1</to> </outbound-rule></urlrewrite> Spring Framework - MVC Dmitry Noskov
  12. 12. WebApplicationContextUtils(1)public class ExchangerServlet extends HttpServlet { private AccountService accountService; @Override public void init() throws ServletException { ServletContext sc = super.getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc); accountService = context.getBean(AccountService.class); }} Spring Framework - MVC Dmitry Noskov
  13. 13. WebApplicationContextUtils(2)public class ExchangerFilter implements Filter { private AccountService accountService; @Override public void init(FilterConfig config) throws ServletException { ServletContext sc = config.getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc); accountService = context.getBean(AccountService.class); }} Spring Framework - MVC Dmitry Noskov
  14. 14. Controller@Controller@RequestMapping@RequestParam@PathVariable Spring Framework - MVC Dmitry Noskov
  15. 15. Mapping requests by path@RequestMapping("/welcome") by HTTP method@RequestMapping(value = "/welcome", method=RequestMethod.GET) by presence / value of query parameter@RequestMapping(params = {"find=ByMake", "form" }) by presence / value of request header@RequestMapping(value = "/welcome", headers="accept=text/*") Spring Framework - MVC Dmitry Noskov
  16. 16. Simple Controller@Controllerpublic class WelcomeController { @RequestMapping("/welcome") public void welcome() { }} Spring Framework - MVC Dmitry Noskov
  17. 17. Use case controller@Controllerpublic class CarController { @RequestMapping("/showcar.do") public String show(@RequestParam("id") id, Model model) { model.addAttribute("car", Car.findCar(id)); return "jsp/cars/car.jsp"; } @RequestMapping("/carlist.do") public String list(Model model) { /** such business logic*/} /** such method handlers*/} Spring Framework - MVC Dmitry Noskov
  18. 18. Unfriendly URLs direct commandURL: http://localhost:8080/carbase/showcar.do?id=77 for each item not very cacheable and search engine friendly Spring Framework - MVC Dmitry Noskov
  19. 19. REST Representation State Transfer style of software architecture RPC is antipode http://en.wikipedia.org/wiki/Representational_State_Transfer Spring Framework - MVC Dmitry Noskov
  20. 20. Http methods get post  when the resource URL is unknown (create item) put  when the resource URL is known (update item) delete post vs put  http://stackoverflow.com/questions/630453/put-vs-post-in-rest Spring Framework - MVC Dmitry Noskov
  21. 21. RESTful mappingResource GET PUT POST DELETEhttp://domain.com/cars obtain list of item update create Xhttp://domain.com/cars/7 obtain item X X deletehttp://domain.com/cars?form create empty form X X Xhttp://domain.com/cars/7?form pre-populated form X X X Spring Framework - MVC Dmitry Noskov
  22. 22. RESTful URLsURL: http://localhost:8080/carbase/cars/11 Spring Framework - MVC Dmitry Noskov
  23. 23. Typical actions simple list page filtered list page CRUD:  create  read (retrieve)  update  delete workflow  submit / approve / etc. Spring Framework - MVC Dmitry Noskov
  24. 24. List pageURL: http://localhost:8080/carbase/cars@Controller@RequestMapping("/cars")public class CarController { @RequestMapping(method = RequestMethod.GET) public String list(Model model) { model.addAttribute("cars", Car.findAllCars()); return "cars/list"; }} Spring Framework - MVC Dmitry Noskov
  25. 25. Detailed pageURL: http://localhost:8080/carbase/cars/11@Controller@RequestMapping("/cars")public class CarController { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public String show(@PathVariable("id") Long id, Model model) { model.addAttribute("car", Car.findCar(id)); return "cars/show"; }} Spring Framework - MVC Dmitry Noskov
  26. 26. CreateURL: http://localhost:8080/carbase/cars@Controller@RequestMapping("/cars")public class CarController { @RequestMapping(method = RequestMethod.POST) public String create(Car car) { car.persist(); return "redirect:/cars/" + car.getId(); }} Spring Framework - MVC Dmitry Noskov
  27. 27. UpdateURL: http://localhost:8080/carbase/cars/@Controller@RequestMapping("/cars")public class CarController { @RequestMapping(method = RequestMethod.PUT) public String update(@Valid Car car, BindingResult result) { /** Spring Validator*/ //result.hasErrors(); car.merge(); return "redirect:/cars/" + car.getId(); }} Spring Framework - MVC Dmitry Noskov
  28. 28. DeleteURL: http://localhost:8080/carbase/cars/11@Controller@RequestMapping("/cars")public class CarController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String delete(@PathVariable("id") Long id) { Car.findCar(id).remove(); return "redirect:/cars; }} Spring Framework - MVC Dmitry Noskov
  29. 29. Filtered pageURL: http://localhost:8080/carbase/cars@Controller@RequestMapping("/cars")public class CarController { @RequestMapping(params="find=ByMake", method=RequestMethod.GET) public String findByMake(@RequestParam("make")Make make, Model m) { m.addAttribute("cars", Car.findCarsByMake(make).getResultList()); return "cars/list"; }} Spring Framework - MVC Dmitry Noskov
  30. 30. Delete and put through post Spring tag <form:form action="/carbase/cars" method="PUT"> html <form id="car" action="/carbase/cars" method="post"> <input type="hidden" name="_method" value="PUT"/> server side <filter> <filter-name>HttpMethodFilter</filter-name> <filter-class> org.springframework.web.filter.HiddenHttpMethodFilter </filter-class> </filter> Spring Framework - MVC Dmitry Noskov
  31. 31. Handler arguments HttpSession / HttpServletRequest / etc. Spring’s WebRequest / NativeWebRequest path variable java.io.InputStream / java.io.OutputStream request’s param / header / body / cookies command objects http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-ann-requestmapping-arguments Spring Framework - MVC Dmitry Noskov
  32. 32. Return types ModelAndView Model / Map / ModelMap View String / void @ResponseBody / @ModelAttribute http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-ann-requestmapping-arguments Spring Framework - MVC Dmitry Noskov
  33. 33. Additional annotations@ModelAttribute@SessionAttributes@RequestHeader@CookieValue@RequestBody / @ResponseBody Spring Framework - MVC Dmitry Noskov
  34. 34. ModelAttribute maps a model attribute to the specific parameter@RequestMapping(method = RequestMethod.POST)public String create(@ModelAttribute("car") Car car) {} provide reference data for the model @ModelAttribute("makes") public Collection<Make> populateMakes() { return Make.findAllMakes(); } Spring Framework - MVC Dmitry Noskov
  35. 35. SessionAttributes list the names or types of model attributes which should be stored in the session@Controller@SessionAttributes("car")//@SessionAttributes(value={}, types={})public class CarController { public String updateForm(@PathVariable("id") Long id, Model model) { m.addAttribute("car", Car.findCar(id)); } public String update(Car request, SessionStatus status) { status.setComplete(); }} Spring Framework - MVC Dmitry Noskov
  36. 36. RequestHeader typical request headerhost = localhost:8080user-agent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203Firefox/3.6.13 ( .NET CLR 3.5.30729; .NET4.0E)accept = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8accept-language = en-us,en;q=0.5 obtain request header@RequestMapping("/welcome")public void welcome(@RequestHeader("user-agent") String agent) {} narrow mappings@RequestMapping(value = "/welcome", headers="accept=text/*")public void welcome() {} Spring Framework - MVC Dmitry Noskov
  37. 37. CookieValue get the JSESSIONID of the cookie @RequestMapping(value = "/welcome") public void welcome(@CookieValue("JSESSIONID") String session){ } Spring Framework - MVC Dmitry Noskov
  38. 38. Data Representation Spring Framework - MVC Dmitry Noskov
  39. 39. Approach template view  ViewResolver, View  HTML, Excel, PDF, etc. data view  HttpMessageConverter  XML, JSON, etc. Spring Framework - MVC Dmitry Noskov
  40. 40. View resolver XmlViewResolver ResourceBundleViewResolver UrlBasedViewResolver InternalResourceViewResolver BeanNameViewResolver ContentNegotiatingViewResolver http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-viewresolver-resolver Spring Framework - MVC Dmitry Noskov
  41. 41. View JSP & JSTL Tiles Velocity FreeMarker etc. prefix  redirect:  forward: Spring Framework - MVC Dmitry Noskov
  42. 42. ResourceBundleViewResolver configuration<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="view"/></bean> view.propertieswelcome.(class)=org.springframework.web.servlet.view.JstlViewwelcome.url=/WEB-INF/jsp/welcome.jspcars.(class)=org.springframework.web.servlet.view.JstlViewcars.url=/WEB-INF/jsp/cars.jsp controller@Controller return "cars" Spring Framework - MVC Dmitry Noskov
  43. 43. UrlBasedViewResolver<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/></bean> use caseIf @Controller return "cars/show"view class will process "/WEB-INF/jsp/cars/show.jsp" Spring Framework - MVC Dmitry Noskov
  44. 44. Tiles(1) configuration<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/></bean><bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/layouts/layouts.xml</value> <value>/WEB-INF/**/views.xml</value> </list> </property></bean> views.xml<definition extends="default" name="cars/show"></definition> Spring Framework - MVC Dmitry Noskov
  45. 45. Tiles(2)<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/layouts/layouts.xml</value> <value>/WEB-INF/**/views.xml</value> </list> </property> <property name="preparerFactoryClass"> <value> org.springframework.web.servlet.view.tiles2. SpringBeanPreparerFactory </value> </property></bean> Spring Framework - MVC Dmitry Noskov
  46. 46. HttpMessageConverter reads the request body and writes the response converters mapped to content types http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/remoting.html#rest-message-conversion registered by default if jar present in classpath  Jackson, JAXB, Atom, RSS Spring Framework - MVC Dmitry Noskov
  47. 47. ContentNegotiatingViewResolver Spring Framework - MVC Dmitry Noskov
  48. 48. Strategies URI  www.domain.com/cars.html  www.domain.com/cars.json content negotiation  Accept: text/html…  Accept: text/xml…  Accept: application/pdf… Spring Framework - MVC Dmitry Noskov
  49. 49. Example(1)<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="atom" value="application/atom+xml"/> <entry key="html" value="text/html"/> <entry key="json" value="application/json"/> </map> </property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/> </list> </property> <property name="defaultViews"> <list><bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/></list> </property></bean> Spring Framework - MVC Dmitry Noskov
  50. 50. Example(2)<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml" /> </map> </property> <property name="defaultViews"> <list><bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/></list> </property></bean><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="order" value="2" /> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/></bean> Spring Framework - MVC Dmitry Noskov
  51. 51. Additional featuresLocalesThemesFile uploadHandling mappings / exceptions Spring Framework - MVC Dmitry Noskov
  52. 52. Locales LocaleResolver  AcceptHeaderLocaleResolver  CookieLocaleResolver  SessionLocaleResolver LocaleChangeInterceptor<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang"/></bean>http://localhost:8080/carbase/?lang=ru Spring Framework - MVC Dmitry Noskov
  53. 53. Themes ThemeSource  ResourceBundleThemeSource ThemeResolver  FixedThemeResolver  SessionThemeResolver  CookieThemeResolver Spring Framework - MVC Dmitry Noskov
  54. 54. File upload MultipartResolver<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties; the maximum file size in bytes --> <property name="maxUploadSize" value="100000"/></bean> MultipartFile@RequestMapping(method = RequestMethod.POST)public String upload (@RequestParam("file") MultipartFile file) {} Spring Framework - MVC Dmitry Noskov
  55. 55. Handling mappings interceptors default handler order lazy init handlers<bean id="handlerMapping"class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <bean class="myInterceptor"/> </property></bean> Spring Framework - MVC Dmitry Noskov
  56. 56. Handler interceptorspublic interface HandlerInterceptor { /** Called before HandlerAdapter invokes the handler. * @return true if the execution chain should proceed */ boolean preHandle(Request, Response, Handler) {} /** Called after HandlerAdapter actually invoked the handler, * but before the DispatcherServlet renders the view.*/ void postHandle(Request, Response, Handler, ModelAndView) {} /** Callback after rendering the view. */ void afterCompletion(Request, Response, Handler, Exception) {}} Spring Framework - MVC Dmitry Noskov
  57. 57. Handling Exceptions application  HandlingExeptionResolver controller  @ExceptionHandler(Exception.class) public String handleException(Exception e) { return ClassUtils.getShortName(e.getClass()); } method  try {} catch (Exception e) {} Spring Framework - MVC Dmitry Noskov
  58. 58. Magic tags<mvc:annotation-driven><mvc:interceptors><mvc:view-controller><mvc:resources><mvc:default-servlet-handler> Spring Framework - MVC Dmitry Noskov
  59. 59. mvc:annotation-driven registers necessary beans support formatting  Number fields using the @NumberFormat  Date, Calendar, Long fields using the @DateTimeFormat support for reading and writing  XML, if JAXB is present in classpath  JSON, if Jackson is present in classpath support validating with @Valid Spring Framework - MVC Dmitry Noskov
  60. 60. mvc:interceptors<!-- register "global" interceptor beans to apply to allregistered HandlerMappings --><mvc:interceptors> <!–- applied to all URL paths --> <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/> <!–- applied to a specific URL path --> <mvc:interceptor> <mvc:mapping path="/secure/*"/> <bean class="org.example.MyInterceptor" /> </mvc:interceptor></mvc:interceptors> Spring Framework - MVC Dmitry Noskov
  61. 61. mvc:view-controller immediately forwards to a view when invoked <mvc:view-controller path="/" view-name="index"/> <mvc:view-controller path="/resourceNotFound"/> Spring Framework - MVC Dmitry Noskov
  62. 62. mvc:resources<!-- Handles HTTP GET requests for /resources/** by efficientlyserving up static resources --><mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/> http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-static-resources Spring Framework - MVC Dmitry Noskov
  63. 63. mvc:default-servlet-handler<!-- Allows for mapping the DispatcherServlet to "/" byforwarding static resource requests to the containers defaultServlet --><mvc:default-servlet-handler/> Spring Framework - MVC Dmitry Noskov
  64. 64. Ajax Spring Framework - MVC Dmitry Noskov
  65. 65. Getting JSON server@RequestMapping(value="/availability", method=RequestMethod.GET)public @ResponseBody AvailabilityStatus getAvailability(@RequestParam String name) { return AvailabilityStatus.AVAILABLE;} clientfunction checkAvailability() { $.getJSON("account/availability", {name: $(#name).val()}, function(availability) {} );} Spring Framework - MVC Dmitry Noskov
  66. 66. Post JSON client$("#account").submit(function() { var account = $(this).serializeObject(); $.postJSON("account", account, function(data) { $("#assignedId").val(data.id); }); return false;}); server@RequestMapping(method=RequestMethod.POST)public @ResponseBody Map<String, ? extends Object> create(@RequestBody Account account) { return Collections.singletonMap("id", account.getId());} Spring Framework - MVC Dmitry Noskov
  67. 67. Spring Framework - MVC Dmitry Noskov
  68. 68. Features clear separation of roles reusable business code flexible model transfer customizable binding and validation customizable handler mapping and view resolution pluggability Spring Framework - MVC Dmitry Noskov
  69. 69. Spring MVC lightweight web framework controller is a Spring bean Spring Framework - MVC Dmitry Noskov
  70. 70. Information reference  http://www.springsource.org/documentation samples  https://src.springsource.org/svn/spring-samples/ blog  http://blog.springsource.com/category/web/ forum  http://forum.springsource.org/forumdisplay.php?f=25 Spring Framework - MVC Dmitry Noskov
  71. 71. Questions Spring Framework - MVC Dmitry Noskov
  72. 72. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations

×