SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
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

Mais conteúdo relacionado

Destaque

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 SpELCraig Walls
 
Modular Java - OSGi
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGiCraig Walls
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
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.1Sam Brannen
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC frameworkMohit Gupta
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 

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

Semelhante a Spring MVC

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.1Matt Raible
 
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 testMichele Capra
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven DevelopmentAugusto Pascutti
 
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 3Oliver Gierke
 
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.0Arun Gupta
 
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 7Max Andersen
 
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
 
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 applicationsDivyanshGupta922023
 
Dynamic Groovy Edges
Dynamic Groovy EdgesDynamic Groovy Edges
Dynamic Groovy EdgesJimmy Ray
 
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 AngularJSPablo Godel
 
mDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOmDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOondraz
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVCAcquisio
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSJumping Bean
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 

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

Mais de Roman Pichlík

MongoDB for Java Developers
MongoDB for Java DevelopersMongoDB for Java Developers
MongoDB for Java DevelopersRoman Pichlík
 
Nosql from java developer pov
Nosql from java developer povNosql from java developer pov
Nosql from java developer povRoman Pichlík
 
Spring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariSpring framework - J2EE S Lidskou Tvari
Spring framework - J2EE S Lidskou TvariRoman Pichlík
 
Dependency Injection Frameworky
Dependency Injection FrameworkyDependency Injection Frameworky
Dependency Injection FrameworkyRoman Pichlík
 

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

Último

UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 

Último (20)

UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 

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