SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
Spring framework
                     Motto: Musíte rozbít vejce když chcete udělat omeletu




                Spring framework training materials by Roman Pichlík is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Sunday 13 May 2012                                                                                                                                       1
Spring MVC




Sunday 13 May 2012                2
Jak jsme se tam dostali




Sunday 13 May 2012                             3
Špagetový kód
                     • JSP 1.0, skriplety
                           <%
                            Connection con = null;
                            String sql = "select name from users";
                            PreparedStatement ps = con.prepareStatement(sql);
                            ResultSet rs = ps.executeQuery();
                            out.println("<table>");
                            while(rs.next()) {
                                out.println("<tr>");
                                  out.println("<td>");
                                    out.println(rs.getString(1));
                                  out.println("</td>");
                                out.println("</tr>");
                            }
                            out.println("<table>");
                           %>




Sunday 13 May 2012                                                              4
Nevýhody
                     • Znovupoužitelnost
                     • Míchání odpovědností
                      • prezentační a aplikační logika
                        dohromady
                        • nemožnost alternativní
                          reprezentace
                     • Špatná testovatelnost
Sunday 13 May 2012                                       5
MVC
                     • Oddělení odpovědností
                      • Aplikační chování
                      • Data a jejich reprezentaci
                     • Obecný návrhový vzor
                      • Desktop, klientské frameworky
                       • JavaScript - SproutCore
                       • Swing
Sunday 13 May 2012                                      6
MVC
                     • Model

                       • Date

                     • Controller

                       • Aplikační
                         chování

                     • View

                       • Prezentace
                         Modelu
Sunday 13 May 2012                          7
MVC v prostředí web framew.




Sunday 13 May 2012                  8
Web frameworky




Sunday 13 May 2012                    9
Spring MVC


                     • XML, Anotace
                     • Dependency Injection
                     • SPEL, Validace
                     • Koncepty zůstavají zachované


Sunday 13 May 2012                                    10
Odbavení požadavku




Sunday 13 May 2012                        11
Aplikační context




Sunday 13 May 2012                       12
Základní anotace


                     • @Controller
                     • @RequestMapping
                     • @PathVariable
                     • @RequestParam


Sunday 13 May 2012                          13
Controller
                     • @Controller
                     • Vstupní bod
                     • Mapování na konkretní URL path
                     • Bridge HTTP/Aplikační logika
                     • Měl by být jednotkově
                       testovatelný

Sunday 13 May 2012                                      14
Controller ukázka

                     @Controller
                     public class UserController {

                         @Autowired
                         private UserStorageDao userStorageDao;

                         @RequestMapping("/users.htm")
                         public ModelMap usersHandler() {
                             return new ModelMap("users", userStorageDao.getAll());
                         }

                     }




Sunday 13 May 2012                                                                    15
@RequestMapping

                     • Používá se pro třídy i metody
                     • Lze vhodně kombinovat
                     • Může definovat path, HTTP
                       metodu případně další podmínky,
                       za kterých dojde k match


Sunday 13 May 2012                                       16
@Controller
               @RequestMapping("/appointments")
               public class AppointmentsController {

                     private final AppointmentBook appointmentBook;

                     @Autowired
                     public AppointmentsController(AppointmentBook appointmentBook) {
                         this.appointmentBook = appointmentBook;
                     }

                     @RequestMapping(method = RequestMethod.GET)
                     public Map<String, Appointment> get() {
                         return appointmentBook.getAppointmentsForToday();
                     }

                     @RequestMapping(value="/{day}", method = RequestMethod.GET)
                     public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) {
                         return appointmentBook.getAppointmentsForDay(day);
                     }

                     @RequestMapping(value="/new", method = RequestMethod.GET)
                     public AppointmentForm getNewForm() {
                         return new AppointmentForm();
                     }

                     @RequestMapping(method = RequestMethod.POST)
                     public String add(@Valid AppointmentForm appointment, BindingResult result) {
                         if (result.hasErrors()) {
                             return "appointments/new";
                         }
                         appointmentBook.addAppointment(appointment);
                         return "redirect:/appointments";
                     }
               }




Sunday 13 May 2012                                                                                      17
Path mapping
               @Controller                                        třída definuje první část cesty
               @RequestMapping("/appointments")
               public class AppointmentsController {

                     private final AppointmentBook appointmentBook;

                     @Autowired
                     public AppointmentsController(AppointmentBook appointmentBook) {
                         this.appointmentBook = appointmentBook;
                     }
                                                                         metody definují zbytek
                     @RequestMapping(method = RequestMethod.GET)
                     public Map<String, Appointment> get() {
                         return appointmentBook.getAppointmentsForToday();
                     }

                     @RequestMapping(value="/{day}", method = RequestMethod.GET)
                     public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) {
                         return appointmentBook.getAppointmentsForDay(day);
                     }

                     @RequestMapping(value="/new", method = RequestMethod.GET)
                     public AppointmentForm getNewForm() {
                         return new AppointmentForm();
                     }
                     ...




Sunday 13 May 2012                                                                                      18
Path mapping
            http://myapp/appointments/2011-01-01

                                       http://myapp/appointments/new

         @Controller
         @RequestMapping("/appointments")
         public class AppointmentsController {

               private final AppointmentBook appointmentBook;

               ...

               @RequestMapping(value="/{day}", method = RequestMethod.GET)
               public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) {
                   return appointmentBook.getAppointmentsForDay(day);
               }

               @RequestMapping(value="/new", method = RequestMethod.GET)
               public AppointmentForm getNewForm() {
                   return new AppointmentForm();
               }
               ...




Sunday 13 May 2012                                                                                19
HTTP method mapping
                                            mapping na konkrétní HTTP metodu
           @Controller
           @RequestMapping("/appointments")
           public class AppointmentsController {

                 @RequestMapping(method = RequestMethod.GET)
                 public Map<String, Appointment> get() {
                     return appointmentBook.getAppointmentsForToday();
                 }

                 @RequestMapping(value="/{day}", method = RequestMethod.GET)
                 public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) {
                     return appointmentBook.getAppointmentsForDay(day);
                 }

                 @RequestMapping(method = RequestMethod.POST)
                 public String add(@Valid AppointmentForm appointment, BindingResult result) {
                     if (result.hasErrors()) {
                         return "appointments/new";
                     }
                     appointmentBook.addAppointment(appointment);
                     return "redirect:/appointments";
                 }
           }




Sunday 13 May 2012                                                                                  20
Podmínečný mapping
                                                                                       HTTP hlavičkou
         @Controller
         @RequestMapping("/owners/{ownerId}")
         public class RelativePathUriTemplateController {

         @RequestMapping(value = "/pets", method = RequestMethod.POST, headers="content-type=text/*")
           public void addPet(Pet pet, @PathVariable String ownerId) {
             // implementation omitted
           }
         }


                                                                           Query parametrem
          @Controller
          @RequestMapping("/owners/{ownerId}")
          public class RelativePathUriTemplateController {

              @RequestMapping(value = "/pets/{petId}", params="myParam=myValue")
              public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
                // implementation omitted
              }
          }




Sunday 13 May 2012                                                                                           21
Handler method argumenty
  •ServletRequest or HttpServletRequest, HttpSession.
  •org.springframework.web.context.request.WebRequest,
  org.springframework.web.context.request.NativeWebRequest.
  •java.util.Locale
  •java.io.InputStream / java.io.Reader
  •java.io.OutputStream / java.io.Writer
  •java.security.Principal
  •@PathVariable
  •@RequestParam
  •@RequestHeader
  •@RequestBody
  •HttpEntity<?>
  •java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap
  •org.springframework.validation.Errors / org.springframework.validation.BindingResult
  •org.springframework.web.bind.support.SessionStatus


Sunday 13 May 2012                                                                        22
@PathVariable


         @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
         public String findOwner(@PathVariable String ownerId, Model model) {
           Owner owner = ownerService.findOwner(ownerId);
           model.addAttribute("owner", owner);
           return "displayOwner";
         }




Sunday 13 May 2012                                                              23
@PathVariable
           http://myapp/owners/1



         @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
         public String findOwner(@PathVariable String ownerId, Model model) {
           Owner owner = ownerService.findOwner(ownerId);
           model.addAttribute("owner", owner);
           return "displayOwner";
         }




Sunday 13 May 2012                                                              24
@PathVariable
                     • @PathVariable typ může být pouze
                       základní typ (long, String)
                     • Pro další typy =>PropertyEditor

   @Controller
   public class MyFormController {

          @InitBinder
          public void initBinder(WebDataBinder binder) {
              SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
              dateFormat.setLenient(false);
              binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
          }
   }



Sunday 13 May 2012                                                                                25
@ModelAttribute


                     • Přednahrání dat do formuláře
                     • Propojení modelu do
                       konverzačního schématu
                      • obsluha formuláře



Sunday 13 May 2012                                    26
Přednahrání modelu
  •metoda se volá ještě před vlastní handler metodou
  •model atributy lze namapovat do handler metody

          public class EditPetForm {

                 // ...

                 @ModelAttribute("types")
                 public Collection<PetType> populatePetTypes() {
                     return this.clinic.getPetTypes();
                 }

                 @RequestMapping
                 public void handle(@ModelAttribute Collection<PetType> types)




Sunday 13 May 2012                                                               27
Konverzační použití
               @Controller
               @RequestMapping("/editUser.htm")
               @SessionAttributes("user")
               public class UserEditFormController {

               	      @Autowired
               	      private UserStorageDao userStorageDao;

               	       @RequestMapping(method = RequestMethod.GET)
                     public String setupForm(ModelMap model) {
                          model.addAttribute("user", new User());
                          return "editUser"; //viewname
                     }

                     @RequestMapping(method = RequestMethod.POST)
                     public String processSubmit( @ModelAttribute("user") User user, BindingResult result, SessionStatus status) {
                         userStorageDao.save(user);
                         status.setComplete();
                         return "redirect:users.htm";
                     }
               }




Sunday 13 May 2012                                                                                                                   28
Návratové typy
                                         návratový typ



                     @RequestMapping(method = RequestMethod.POST)
                     public XXX processSubmit(@ModelAttribute("pet") Pet pet,
                         BindingResult result, Model model) {
                       …
                     }




Sunday 13 May 2012                                                              29
Možné návratové typy

 •org.springframework.web.servlet.ModelAndView
 •org.springframework.ui.Model
 •java.util.Map
 •org.springframework.ui.View
 •java.lang.String
 •void
 •@ResponseBody
 •A HttpEntity<?> or ResponseEntity<?>
 •Jiný typ




Sunday 13 May 2012                               30
Automatická validace
                     • integrace JSR-303
                     • BindingResult objekt s výsledkem
                       validace

  @RequestMapping(method = RequestMethod.POST)
  public String processSubmit( @ModelAttribute("user") @Valid User user, BindingResult result, SessionStatus status) {
      if (result.hasErrors()) {
          return "editUser";
      }

       userStorageDao.save(user);
       status.setComplete();
       return "redirect:users.htm";
  }




Sunday 13 May 2012                                                                                                       31
Exception handling
                     • Vytvoření beany implementující
                      • HandlerExceptionResolver
                      • Vrací ModelAndView
                     • Ošetření všech výjímek
                      • Zobrazení error stránky
                      • Zalogovaní kontextu
                      • REST (správný HTTP status)
Sunday 13 May 2012                                      32
Interceptors

                     • Možnost reagovat před a po
                       zpracování HTTP požadavku
                      • pre, post, after
                     • Vytvoření beany implementující
                     • HandlerInterceptor
                     • HandlerInterceptorAdapter

Sunday 13 May 2012                                      33
Spring MVC zavedení


    <?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 classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
                                   http://www.springframework.org/schema/mvc classpath:/org/springframework/web/servlet/config/spring-mvc-3.0.xsd">
        <mvc:annotation-driven/>
    </beans>




Sunday 13 May 2012                                                                                                                                     34
Spring MVC zavedení s view r.

    <?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 classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
                                   http://www.springframework.org/schema/mvc classpath:/org/springframework/web/servlet/config/spring-mvc-3.0.xsd">

        <mvc:annotation-driven/>

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

    </beans>




Sunday 13 May 2012                                                                                                                                     35
Praktické cvičení




Sunday 13 May 2012                       36
•   Vytvořte beany pro

                         •   ReservationServiceImp

                         •   InMemoryBookStoreDao

                             •   inicializujte s několika knihami viz setter pro bookHolder

                     •   Vytvořte controller

                         •   vrátí seznam rezervací

                             •   použijte @RequestParam pro její vyfiltrování

                         •   vrátí konkrétní rezervaci

                         •   umožní vytvořit novou rezervaci (inspiraci hledejte v již naimplementovaných
                             uživatelích)

                         •   použijte @PathVariable

                         •   validace vstupu

                         •   přidejte interceptor, ktery vypíše čas obsluhy

                         •   přidejte ErrorHandler, ktery bude logovat vyjímky

Sunday 13 May 2012                                                                                          37

Weitere ähnliche Inhalte

Andere mochten auch

Modular Java - OSGi
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGi
Craig Walls
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 

Andere mochten auch (17)

That old Spring magic has me in its SpEL
That old Spring magic has me in its SpELThat old Spring magic has me in its SpEL
That old Spring magic has me in its SpEL
 
Modular Java - OSGi
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGi
 
Spring boot
Spring bootSpring boot
Spring boot
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
Boot It Up
Boot It UpBoot It Up
Boot It Up
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring Mvc Rest
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest
 
Get ready for spring 4
Get ready for spring 4Get ready for spring 4
Get ready for spring 4
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 

Ähnlich wie Spring MVC

3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)
drupalconf
 
mDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOmDevCamp - The Best from Google IO
mDevCamp - The Best from Google IO
ondraz
 

Ähnlich wie Spring MVC (20)

What's New in Spring 3.1
What's New in Spring 3.1What's New in Spring 3.1
What's New in Spring 3.1
 
Spring integration
Spring integrationSpring integration
Spring integration
 
Getting started with Windows Phone 7 and unit test
Getting started with Windows Phone 7 and unit testGetting started with Windows Phone 7 and unit test
Getting started with Windows Phone 7 and unit test
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven Development
 
REST based web applications with Spring 3
REST based web applications with Spring 3REST based web applications with Spring 3
REST based web applications with Spring 3
 
GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0GIDS 2012: Java Message Service 2.0
GIDS 2012: Java Message Service 2.0
 
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
 
AngularJS On-Ramp
AngularJS On-RampAngularJS On-Ramp
AngularJS On-Ramp
 
3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
Backbone
BackboneBackbone
Backbone
 
Dynamic Groovy Edges
Dynamic Groovy EdgesDynamic Groovy Edges
Dynamic Groovy Edges
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJS
 
mDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOmDevCamp - The Best from Google IO
mDevCamp - The Best from Google IO
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Introduction to Angular
Introduction to AngularIntroduction to Angular
Introduction to Angular
 
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 

Mehr von Roman Pichlík (9)

Spring Testing
Spring TestingSpring Testing
Spring Testing
 
Spring ioc-advanced
Spring ioc-advancedSpring ioc-advanced
Spring ioc-advanced
 
Spring dao
Spring daoSpring dao
Spring dao
 
Spring aop
Spring aopSpring aop
Spring aop
 
Spring Web Services
Spring Web ServicesSpring Web Services
Spring Web Services
 
MongoDB for Java Developers
MongoDB for Java DevelopersMongoDB for Java Developers
MongoDB for Java Developers
 
Nosql from java developer pov
Nosql from java developer povNosql from java developer pov
Nosql from java developer pov
 
Spring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariSpring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou Tvari
 
Dependency Injection Frameworky
Dependency Injection FrameworkyDependency Injection Frameworky
Dependency Injection Frameworky
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Spring MVC

  • 1. Spring framework Motto: Musíte rozbít vejce když chcete udělat omeletu Spring framework training materials by Roman Pichlík is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Sunday 13 May 2012 1
  • 2. Spring MVC Sunday 13 May 2012 2
  • 3. Jak jsme se tam dostali Sunday 13 May 2012 3
  • 4. Špagetový kód • JSP 1.0, skriplety <% Connection con = null; String sql = "select name from users"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); out.println("<table>"); while(rs.next()) { out.println("<tr>"); out.println("<td>"); out.println(rs.getString(1)); out.println("</td>"); out.println("</tr>"); } out.println("<table>"); %> Sunday 13 May 2012 4
  • 5. Nevýhody • Znovupoužitelnost • Míchání odpovědností • prezentační a aplikační logika dohromady • nemožnost alternativní reprezentace • Špatná testovatelnost Sunday 13 May 2012 5
  • 6. MVC • Oddělení odpovědností • Aplikační chování • Data a jejich reprezentaci • Obecný návrhový vzor • Desktop, klientské frameworky • JavaScript - SproutCore • Swing Sunday 13 May 2012 6
  • 7. MVC • Model • Date • Controller • Aplikační chování • View • Prezentace Modelu Sunday 13 May 2012 7
  • 8. MVC v prostředí web framew. Sunday 13 May 2012 8
  • 10. Spring MVC • XML, Anotace • Dependency Injection • SPEL, Validace • Koncepty zůstavají zachované Sunday 13 May 2012 10
  • 13. Základní anotace • @Controller • @RequestMapping • @PathVariable • @RequestParam Sunday 13 May 2012 13
  • 14. Controller • @Controller • Vstupní bod • Mapování na konkretní URL path • Bridge HTTP/Aplikační logika • Měl by být jednotkově testovatelný Sunday 13 May 2012 14
  • 15. Controller ukázka @Controller public class UserController { @Autowired private UserStorageDao userStorageDao; @RequestMapping("/users.htm") public ModelMap usersHandler() { return new ModelMap("users", userStorageDao.getAll()); } } Sunday 13 May 2012 15
  • 16. @RequestMapping • Používá se pro třídy i metody • Lze vhodně kombinovat • Může definovat path, HTTP metodu případně další podmínky, za kterých dojde k match Sunday 13 May 2012 16
  • 17. @Controller @RequestMapping("/appointments") public class AppointmentsController { private final AppointmentBook appointmentBook; @Autowired public AppointmentsController(AppointmentBook appointmentBook) { this.appointmentBook = appointmentBook; } @RequestMapping(method = RequestMethod.GET) public Map<String, Appointment> get() { return appointmentBook.getAppointmentsForToday(); } @RequestMapping(value="/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(value="/new", method = RequestMethod.GET) public AppointmentForm getNewForm() { return new AppointmentForm(); } @RequestMapping(method = RequestMethod.POST) public String add(@Valid AppointmentForm appointment, BindingResult result) { if (result.hasErrors()) { return "appointments/new"; } appointmentBook.addAppointment(appointment); return "redirect:/appointments"; } } Sunday 13 May 2012 17
  • 18. Path mapping @Controller třída definuje první část cesty @RequestMapping("/appointments") public class AppointmentsController { private final AppointmentBook appointmentBook; @Autowired public AppointmentsController(AppointmentBook appointmentBook) { this.appointmentBook = appointmentBook; } metody definují zbytek @RequestMapping(method = RequestMethod.GET) public Map<String, Appointment> get() { return appointmentBook.getAppointmentsForToday(); } @RequestMapping(value="/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(value="/new", method = RequestMethod.GET) public AppointmentForm getNewForm() { return new AppointmentForm(); } ... Sunday 13 May 2012 18
  • 19. Path mapping http://myapp/appointments/2011-01-01 http://myapp/appointments/new @Controller @RequestMapping("/appointments") public class AppointmentsController { private final AppointmentBook appointmentBook; ... @RequestMapping(value="/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(value="/new", method = RequestMethod.GET) public AppointmentForm getNewForm() { return new AppointmentForm(); } ... Sunday 13 May 2012 19
  • 20. HTTP method mapping mapping na konkrétní HTTP metodu @Controller @RequestMapping("/appointments") public class AppointmentsController { @RequestMapping(method = RequestMethod.GET) public Map<String, Appointment> get() { return appointmentBook.getAppointmentsForToday(); } @RequestMapping(value="/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(method = RequestMethod.POST) public String add(@Valid AppointmentForm appointment, BindingResult result) { if (result.hasErrors()) { return "appointments/new"; } appointmentBook.addAppointment(appointment); return "redirect:/appointments"; } } Sunday 13 May 2012 20
  • 21. Podmínečný mapping HTTP hlavičkou @Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping(value = "/pets", method = RequestMethod.POST, headers="content-type=text/*") public void addPet(Pet pet, @PathVariable String ownerId) { // implementation omitted } } Query parametrem @Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping(value = "/pets/{petId}", params="myParam=myValue") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } } Sunday 13 May 2012 21
  • 22. Handler method argumenty •ServletRequest or HttpServletRequest, HttpSession. •org.springframework.web.context.request.WebRequest, org.springframework.web.context.request.NativeWebRequest. •java.util.Locale •java.io.InputStream / java.io.Reader •java.io.OutputStream / java.io.Writer •java.security.Principal •@PathVariable •@RequestParam •@RequestHeader •@RequestBody •HttpEntity<?> •java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap •org.springframework.validation.Errors / org.springframework.validation.BindingResult •org.springframework.web.bind.support.SessionStatus Sunday 13 May 2012 22
  • 23. @PathVariable @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable String ownerId, Model model) { Owner owner = ownerService.findOwner(ownerId); model.addAttribute("owner", owner); return "displayOwner"; } Sunday 13 May 2012 23
  • 24. @PathVariable http://myapp/owners/1 @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable String ownerId, Model model) { Owner owner = ownerService.findOwner(ownerId); model.addAttribute("owner", owner); return "displayOwner"; } Sunday 13 May 2012 24
  • 25. @PathVariable • @PathVariable typ může být pouze základní typ (long, String) • Pro další typy =>PropertyEditor @Controller public class MyFormController { @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } } Sunday 13 May 2012 25
  • 26. @ModelAttribute • Přednahrání dat do formuláře • Propojení modelu do konverzačního schématu • obsluha formuláře Sunday 13 May 2012 26
  • 27. Přednahrání modelu •metoda se volá ještě před vlastní handler metodou •model atributy lze namapovat do handler metody public class EditPetForm { // ... @ModelAttribute("types") public Collection<PetType> populatePetTypes() { return this.clinic.getPetTypes(); } @RequestMapping public void handle(@ModelAttribute Collection<PetType> types) Sunday 13 May 2012 27
  • 28. Konverzační použití @Controller @RequestMapping("/editUser.htm") @SessionAttributes("user") public class UserEditFormController { @Autowired private UserStorageDao userStorageDao; @RequestMapping(method = RequestMethod.GET) public String setupForm(ModelMap model) { model.addAttribute("user", new User()); return "editUser"; //viewname } @RequestMapping(method = RequestMethod.POST) public String processSubmit( @ModelAttribute("user") User user, BindingResult result, SessionStatus status) { userStorageDao.save(user); status.setComplete(); return "redirect:users.htm"; } } Sunday 13 May 2012 28
  • 29. Návratové typy návratový typ @RequestMapping(method = RequestMethod.POST) public XXX processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { … } Sunday 13 May 2012 29
  • 30. Možné návratové typy •org.springframework.web.servlet.ModelAndView •org.springframework.ui.Model •java.util.Map •org.springframework.ui.View •java.lang.String •void •@ResponseBody •A HttpEntity<?> or ResponseEntity<?> •Jiný typ Sunday 13 May 2012 30
  • 31. Automatická validace • integrace JSR-303 • BindingResult objekt s výsledkem validace @RequestMapping(method = RequestMethod.POST) public String processSubmit( @ModelAttribute("user") @Valid User user, BindingResult result, SessionStatus status) { if (result.hasErrors()) { return "editUser"; } userStorageDao.save(user); status.setComplete(); return "redirect:users.htm"; } Sunday 13 May 2012 31
  • 32. Exception handling • Vytvoření beany implementující • HandlerExceptionResolver • Vrací ModelAndView • Ošetření všech výjímek • Zobrazení error stránky • Zalogovaní kontextu • REST (správný HTTP status) Sunday 13 May 2012 32
  • 33. Interceptors • Možnost reagovat před a po zpracování HTTP požadavku • pre, post, after • Vytvoření beany implementující • HandlerInterceptor • HandlerInterceptorAdapter Sunday 13 May 2012 33
  • 34. Spring MVC zavedení <?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 classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc classpath:/org/springframework/web/servlet/config/spring-mvc-3.0.xsd"> <mvc:annotation-driven/> </beans> Sunday 13 May 2012 34
  • 35. Spring MVC zavedení s view r. <?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 classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc classpath:/org/springframework/web/servlet/config/spring-mvc-3.0.xsd"> <mvc:annotation-driven/> <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> </beans> Sunday 13 May 2012 35
  • 37. Vytvořte beany pro • ReservationServiceImp • InMemoryBookStoreDao • inicializujte s několika knihami viz setter pro bookHolder • Vytvořte controller • vrátí seznam rezervací • použijte @RequestParam pro její vyfiltrování • vrátí konkrétní rezervaci • umožní vytvořit novou rezervaci (inspiraci hledejte v již naimplementovaných uživatelích) • použijte @PathVariable • validace vstupu • přidejte interceptor, ktery vypíše čas obsluhy • přidejte ErrorHandler, ktery bude logovat vyjímky Sunday 13 May 2012 37