1 / 104

Spring Web MVC

Spring Web MVC. Ievads. T īmekļa lietojumprogrammas ir iespējams programmēt pa tiešo izmantojot Java Servlet un JSP tehnoloģijas Eksistē vairāki tīmekļa lietojumprogrammu izstrādes ietvari (web application frameworks), kuri atbalsta dinamisko tīmekļa lietojumprogrammu izstrādi

claire-odom
Télécharger la présentation

Spring Web 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 Web MVC

  2. Ievads • Tīmekļa lietojumprogrammas ir iespējams programmēt pa tiešo izmantojot Java Servlet un JSP tehnoloģijas • Eksistē vairāki tīmekļa lietojumprogrammu izstrādes ietvari (web application frameworks), kuri atbalsta dinamisko tīmekļa lietojumprogrammu izstrādi • Piemēri: Spring MVC , Play!, JSF, Struts, Tapestry, Stripes, Wicket un daudzi citi

  3. Spring • Spring iratklāta koda Java/JavaEE lietojumprogrammu izstrādes ietvars • Viens no interesantākiem komponentiem ir Spring Web MVC http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/overview.html

  4. Tīmekļa lietojumprogrammu uzdevumi • Tipiskie un svarīgie uzdevumi, kuri ir jāatrisina izstrādājot tīmekļa lietojumprogrammu : • Stāvokļu pārvaldība (state management) • Darba plūsma (workflow) • Validācija • Spring MVC ietvars ir uzprojektēts, lai palīdzēt izstrādātājiem risināt šīs problēmas

  5. Model-View-Controller Pattern • Model-View-Controller (MVC) ir arhitektūras paraugs (aprakstīts 1979. gadā, Smalltalk valodā) • Pamata mērķis: atdalīt datus (Model) no lietotāja interfeisa (View) • MVC atrisina problēmu ieviešot starpnieka komponenti - kontrolieri (Controller)

  6. Model-View-Controller Pattern • Model - Represents enterprise data and the business rules. • View - Renders the contents of a model. Accesses enterprise data through the model and specifies how that data should be presented. • Controller - Translates interactions with the view (button clicks, menu selections) into actions to be performed by the model (activating processes, changing the state of the model). http://ash-mvc.org/

  7. Spring MVC application architecture • Spring MVC applications are broken down into a series of layers • A layer is a discrete, orthogonal area of concern within an application General, high-level layers in a web application

  8. Spring MVC application layers • Typical Spring MVC applications have at least five layers of abstraction • Isolating problem domains into separate layers creates a flexible and testable application • The interface is a contract for a layer, making it easy to keep implementations and their details hiddenwhile enforcing correct layer usage

  9. Spring MVC application layers • The user interface layer (also known as the view) is responsible for rendering output for the client • The web layer manages the user’s navigation through the site • The service layer provides a stateless, coarse-grained interface for clients to use for system interaction • The domain model is the collection of nouns in the system, it also contains the business logic of the system • The data access layer is responsible for interfacing with the persistence mechanism to store and retrieve instances of the object model

  10. Required JAR dependencies Maven dependency configuration (for Spring 3.1.3): <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.1.3.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency>

  11. Spring MVC komponenti Spring MVC sastāv no vairākiem komponentiem, starp kuriem notiek sadarbība apstrādājot klienta pieprasījumu

  12. Pieprasījuma dzīves cikls (1) • Klients sūta pieprasījumu, kurš tiek nodots DispatcherServlet komponentam • Visi pieprasījumi vienmēr tiek nodoti vienam servletam, kuru sauc par priekšējo kontrolieri (front controller)

  13. Pieprasījuma dzīves cikls (2) • Komponents, kurš atbild par pieprasījuma apstrādi ir Controller • Lai nolemt kuram kontrolierim atdot pieprasījumu, DispatcherController izmanto HandlerMapping komponentus • HandlerMapping: URL piesaistīšana kontrolieriem

  14. Pieprasījuma dzīves cikls (3-4) • Kad DispatcherServlet ir izvēlējies kontroliera objektu, tad parsūta tam pieprasījumu, lai kontrolieris izpilda biznesa loģiku • Pēc darba pabeigšanas Controller atgriež ModelAndView objektu • ModelAndView satur View objektu vai skata loģisko vārdu un modeli

  15. Pieprasījuma dzīves cikls (5) • Ja ModelAndView objekts satur skata loģisko vārdu, tad DispatcherServlet izmanto ViewResolver komponenti • ViewResolver atrod atbilstošu View objektu, lai attēlot atbildi klientam

  16. Pieprasījuma dzīves cikls (6) • Visbeidzot, DispatcherServlet atdod pieprasījumu tam View objektam, uz kuru norāda ModelAndView • Viewobjekts ir atbildīgs par pieprasījuma atbildes atgriešanu un parādīšanu klientam

  17. Spring MVC sequence diagram

  18. Front Controller • At the heart of Spring MVC is DispatcherServlet, a servlet that functions as a front controller • A front controller is a common web-application pattern where a single servlet delegates responsibility for a request to other components of an application to perform the actual processing

  19. Processing workflow http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html

  20. DispatcherServletconfig Jākonfigurē programmas/WEB-INF/web.xmlfailā: <servlet> <servlet-name>training</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> Nākamais solis ir nodefinēt servlet mapping: <servlet-mapping> <servlet-name>training</servlet-name> <url-pattern>/training/*</url-pattern> </servlet-mapping>

  21. DispatcherServletcontext • WebApplicationContext tiek ielādēts no faila: • training-servlet.xml • kurš atrodas direktorijā WEB-INF (blakus web.xml failam) • Ir iespējams arī sadalīt • konfigurāciju starp • vairākiem failiem

  22. Context hierarchy in Spring Web MVC http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

  23. Konfigurācijas faila piemērs • DispatcherServletkonfigurācijas faila piemērs: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- the application context definition for the DispatcherServlet --> </beans> • Šīs fails satur bean definitions, kurus izmantoDispatcherServlet

  24. Vienkāršas Web lapas izveidošana Nepieciešamie soļi, lai izveidot Web lapu ar Spring MVC: • Uzrakstīt kontroliera klasi, kas izpildīs biznesa loģiku • Iekonfigurēt kontrolieri DispatcherServlet konteksta konfigurācijas failā (training-servlet.xml) • Iekonfigurēt view resolver, kurš piesaistīs kontrolieri pie JSP • Uzrakstīt JSP, kas attēlos lapu klientam

  25. Kontrolieru izveidošanas veidi Ir divi pamata kontrolieru izveidošanas veidi: • [pirms 2.5] Paplašināt klases no piedāvātas kontrolieru hierarhijas • [sākot no 2.5] Izmantot anotācijas

  26. Kontroliera izveidošana(< 2.5 stils) import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.ModelAndView; public class HomeController implements Controller { public ModelAndViewhandleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("home", "message", greeting); } private String greeting; public void setGreeting(String greeting) { this.greeting = greeting; } } • Nodarbojas ar pieprasījuma apstrādāšanu • Pamata metodes signatūra ir līdzīga servleta service() metodei • Atgriež ModelAndView objektu

  27. Kontroliera konfigurēšana • Kontrolieri ir jāieraksta DispatcherServlet konteksta konfigurācijas failā (training-servlet.xml) : <bean name="/home" class="com.springinaction.training.mvc.HomeController"> <property name="greeting"> <value>Welcome to Spring Training!</value> </property> </bean> • The default handler mapping is BeanNameUrlHandlerMapping, which uses the base name as the URL pattern • When a request comes with a URL that ends with “/home”, DispatcherServlet will dispatch the request to HomeController

  28. Kontroliera izveidošana(>= 2.5 stils) @Controller public class HomeController { @RequestMapping("/home") public ModelAndView helloWorld() { ModelAndView mav = new ModelAndView(); mav.setViewName("home"); mav.addObject("message", greeting); return mav; } private String greeting; public void setGreeting(String greeting) { this.greeting = greeting; } } Lai izmantot anotācijas ir nepieciešama papildus konfigurācija!

  29. Enable annotation support <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Enable autodetection of annotated controllers --> <context:component-scan base-package="com.web.music.portal.mvc"/> <bean class="org.springframework.web.servlet.mvc .annotation.DefaultAnnotationHandlerMapping"/> . . . </beans>

  30. View Resolver deklarēšana • View resolver darbs ir pēc skata loģiska vārda (kurš ir atgriezts ModelAndView objektā) atrast pašu skatu • Viens no variantiem ir izmantot skata vārdu kā JSP faila vārdu (jāieraksta training-servlet.xml): <bean id="viewResolver" class="org.springframework.web. servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> “home”  /WEB-INF/jsp/home.jsp

  31. JSP izveidošana • Pēdējais kas palika – izveidot pašu JSP <%@ page session="false"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html> <head><title>Spring Training, Inc.</title></head> <body> <h2><c:out value="${message}"/></h2> </body> </html> • Failu ir jānosauc par “home.jsp” un ir jāieliek /WEB-INF/jsp/ direktorijā

  32. JSTL konfigurēšana Lai izmantot JSTL (c:out tagu) JSP lapā, ir nepieciešamas papildus bibliotēkas • Step1: download standard.jarand jstl.jar • Step2: ensure that both files arepackaged in /WEB-INF/lib directory of WAR file • Step3: Write JSP file that can use core tags <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency>

  33. Rezultāta apskatīšana • Palika izveidot tīmekļa lietojumprogrammas WAR failu (mvn package) un palaist to uz servera • Pārlūkprogrammā uzrakstīt URL: http://localhost:8080/my_app/training/home.htm

  34. Kopsavilkums

  35. HandlerMapping • Tipiski piesaista specifisku kontrolieri pie URL adreses parauga • Spring piedāvā sekojošas noderīgas HandlerMapping implementācijas • DefaultAnnotationHandlerMapping • BeanNameUrlHandlerMapping • SimpleUrlHandlerMapping

  36. DefaultAnnotationHandlerMapping • Introduced in Spring 2.5 - maps handlers based on HTTP paths expressed through the @RequestMappingannotation inside controller classes annotated with @Controller • Registered by default in DispatcherServleton Java 5+

  37. BeanNameUrlHandlerMapping • Piesaista URL adresi pie kontroliera, kurš ir reģistrēts konfigurācijas failā ar tādu pašu vārdu • e.g. /simple.htm maps to a bean named “/simple.htm” • Ir jāizmanto name atribūtu, jo “/” nav atļauts XML atribūtā id <bean class="org.springframework.web.servlet. handler.BeanNameUrlHandlerMapping"/> <bean name="/simple.htm" class="com.mvc.web.SimpleController"> . . . </bean>

  38. SimpleUrlHandlerMapping • Pats vispārīgs veids kā piesaistītpieprasījuma URLus kontrolieriem • Tiek konfigurēts kāsaraksts no name/value pāriem (URL/kontrolieru vārds) <bean id="simpleUrlMapping" class="org.springframework.web .servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/listCourses.htm">listCoursesController</prop> <prop key="/register.htm">registerStudentController</prop> <prop key="/displayCourse.htm">displayCourseController</prop> </props> </property> </bean>

  39. Multiple handler mappings • Ir iespējams deklarēt vairākus handler mappings vienā lietojumprogrammā • Handler mapping klases implementē Spring Ordered interfeisu • Var uzstādīt order īpašību, lai norādīt izpildes kārtību attiecībā uz citiem handler mapping komponentiem

  40. Multiple handler mappings <bean id="beanNameUrlMapping"class="org.springframework.web. servlet.handler.BeanNameUrlHandlerMapping"> <property name="order"><value>1</value></property> </bean> <bean id="simpleUrlMapping" class="org.springframework.web. servlet.handler.SimpleUrlHandlerMapping"> <property name="order"><value>0</value></property> <property name="mappings"> … </property> </bean>

  41. Kontrolieri JaDispatcherServletir Spring MVC sirds, tad kontrolieri ir smadzenes

  42. Kontrolieru hierarhija ( < 2.5) • Spring piedāvā bagātu kontrolieru hierarhiju • Hierarhijas virsotnē atrodas Controller interfeiss • Parasti ir jāizmanto kādu no implementācijas apakšklasēm

  43. AbstractController Pats vienkāršākais kontrolieris public class SampleController extends AbstractController { public ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView( "hello", "message", "Hello World!"); } }

  44. ModelAndViewobjekts • Iekapsulē skatu un modeļa datus, kurus skats attēlos • Modelis ir realizēts kā java.util.Map • Ērts konstruktors viena modeļa objekta gadījumam: ModelAndView( String viewName, String modelName, Object modelObject)

  45. ModelAndViewobjekts Ir iespējams arī pievienot modelim vairākus objektus: public ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("welcome"); mav.addObject("message1", "Welcome!"); mav.addObject("message2", "Nice to see you!"); return mav; }

  46. Parametru apstrāde Web pieprasījums bieži satur vienu vai vairākus parametrus <form action="/login" method="POST"> Login: <input id=“login" name="login"/> Password: <input id="password" name="password" type="password"/> <input type="submit" value="Login"/> </form> Kādā veidā varētu piekļūt parametriem kontroliera kodā???

  47. Risinājums Varētu izmantot AbstractControllerun nolasīt parametrus no HttpServletRequest public ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { String login = request.getParameter("login"); String pass = request.getParameter("password"); . . . } Spring piedāvā ērtāku iespēju!

  48. AbstractCommandController • Automātiski ieraksta parametrus speciālajā komandas objektā (command object) • Ir iespēja pievienot validatoru, lai nodrošināt to, ka parametri ir pareizi • Galvenā izpildes metode: handle( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)

  49. AbstractCommandController public class DisplayCourseController extends AbstractCommandController { public DisplayCourseController() { setCommandClass(DisplayCourseCommand.class); } protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { DisplayCourseCommand displayCommand = (DisplayCourseCommand) command; Course course = courseService.getCourse(displayCommand.getId()); return new ModelAndView("courseDetail", "course", course); }

  50. Command Object • A command object is a bean that is meant to hold request parameters for easyaccess public class DisplayCourseCommand { private Integer id; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } } • Spring will attempt to match any parameters passed in the request to properties in the command object

More Related