1 / 59

Spring Web MVC

Spring Web MVC. Ievads. Web aplikācijas ir iespējams programmēt pa tiešo izmantojot Java Servlet un JSP tehnoloģijas Eksistē vairāki Web aplikāciju ietvari (web application frameworks), kuri atbalsta dinamisko Web aplikāciju izstrādi

hazel
Download Presentation

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 • Web aplikācijas ir iespējams programmēt pa tiešo izmantojot Java Servlet un JSP tehnoloģijas • Eksistē vairāki Web aplikāciju ietvari (web application frameworks), kuri atbalsta dinamisko Web aplikāciju izstrādi • Piemēri: Struts, Tapestry, Cocoon, Spring, Web Work un daudz citi

  3. Spring • Spring iratklāta koda Java/JavaEE aplikāciju ietvars • Viens no interesantākiem komponentiem ir Spring Web MVC

  4. Web aplikāciju uzdevumi • Svarīgie uzdevumi, kuri ir jāatrisina izstrādājot Web aplikāciju: • 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 2.5): <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.5</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</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 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. DispatcherServletconfig Jākonfigurē Web aplikācijas/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>

  20. 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

  21. 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-2.5.xsd"> <!-- the application context definition for the DispatcherServlet --> </beans> • Šīs fails satur bean definitions, kurus izmantoDispatcherServlet

  22. 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

  23. Kontroliera izveidošana 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

  24. Kontroliera konfigurēšana • Kontrolieri ir jāieraksta DispatcherServlet konteksta konfigurācijas failā (training-servlet.xml) : <bean name="/home.htm" 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.htm”, DispatcherServlet will dispatch the request to HomeController

  25. 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

  26. 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ānoliek /WEB-INF/jsp/ direktorijā

  27. 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>

  28. Rezultāta apskatīšana • Palika izveidot Web aplikācijas WAR failu (mvn package) un palaist aplikāciju uz servera • Pārlūkprogrammā uzrakstīt URL: http://localhost:8080/my_app/training/home.htm

  29. Kopsavilkums

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

  31. 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>

  32. 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>

  33. CommonsPathMapHandlerMapping • Considers source-level metadata placed in a controller’s source code to determine the URL mapping • Need to set up build to include the Commons Attributes compiler so that the attributes will be compiled into application code <bean id="urlMapping" class="org.springframework.web. servlet.handler.metadata.CommonsPathMapHandlerMapping"/> Deprecated as of Spring 2.5! /** @@org.springframework.web.servlet. handler.commonsattributes.PathMap( "/displayCourse.htm") */ public class DisplayCourseController extends AbstractCommandController { … }

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

  35. 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>

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

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

  38. 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!"); } }

  39. 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)

  40. 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; }

  41. 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ā???

  42. 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!

  43. 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)

  44. 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); }

  45. 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

  46. Pārskats

  47. Formu apstrāde • Tipiska Web aplikācija satur vismaz vienu formu • Lietotājs aizpilda formu un aizsūta to • Dati tiek nosūtīti serverim • Kad datu apstrāde ir pabeigta, lietotājs saņem vienu no variantiem: • Lapa ar veiksmīgas izpildes paziņojumu • Formas lapa ar kļūdu paziņojumiem Kādā veidā varētu to realizēt???

  48. Risinājums • IzmantotAbstractControllerformas attēlošanai • Izmantot AbstractCommandControllerformas apstrādei • Trūkums: vajag uzturēt divus dažādus kontrolierus, kuri kopā nodarbojas ar viena uzdevuma risināšanu

  49. SimpleFormController Formu kontroliera funkcionalitāte: • Attēlo formu uz HTTP GET pieprasījuma • Apstrādā formu uz HTTP POST pieprasījuma • Ja notiek kļūda, tad atkārtoti parāda formu publicclass PersonFormController extends SimpleFormController { public PersonFormController() { setCommandClass(Person.class); } publicvoiddoSubmitAction(Object command){ Person person = (Person)object; personService.save(person); } . . . }

  50. Formas JSP Spring piedāvā speciālu formas tagu bibliotēku <%@ page session="false"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html><body> <h1>Add new Person</h1> <form:form commandName="person"> <label for=“name">Name</label> <form:input path="name"/> <label for="surname">Surname</label> <form:input path="surname"/> <input type="submit" value="Save"/> </form:form> </body></html> http://static.springframework.org/spring/docs/2.5.x/reference/spring-form.tld.html

More Related