Spring MVC PA 165, Lecture 8 Martin Kuba Outline architecture of example eShop responsive web design Spring MVC - initialization - controllers - redirects, flash attributes, messages - forms and input data validation PA165 - SpringMVC 2 Example eShop project • Maven multiple module project • project inheritance - child projects inherit settings from specified parent - groupld, project version, deps versions, props, plugins • project aggregation - project specifies its modules - command in parent is done in all modules INFO] Reactor Summary: INFO] INFO] eshop Parent ...................................... SUCCESS [0.133s] INFO] API ............................................... SUCCESS [0.005s] INFO] Persistence Layer and Beans Ualidation ............ SUCCESS [0.007s] INFO] Service Layer ..................................... SUCCESS [0.005s] INFO] Sample Data For eShop ............................. SUCCESS [0.006s] INFO] Ueb Front end implemented in Spring MUC ........... SUCCESS [0.006s] INF01 -------------------------------------------------------------------- eShop module dependencies Module 'eshop-spring-mvc' Module 'eshop-sample-data' ._□ Module 'eshop-service' Module 'eshop-persistence n f7 Co Module'eshop-api' j PA165 - SpringMVC eShop modules eshop-spring-mvc - web user interface implemented in SpringMVC, JSP, JSTL, Bootstrap eshop-sample-data - some sample data (products, categories, users, orders) eshop-api - facade interfaces, DTOs, enums, exceptions eshop-service - facade implementations, service interfaces and implementations eshop-persistence - entities, DAO interfaces and implementations - custom JSR-303 annotations and validators PA165 - SpringMVC eShop layers Presentation Layer new ProductCreateDTO(MPCM,10000,CZK) Facade Layer Service Layer Persistence Layer ©Transactional ProductFacade.createProduct(ProductCreateDTOdto); new Product("PC'\ new DateQ, new Price(10000, CZK)); ProductService.createProduct( Product entity); PriceRepository.save(Price p); ProductDao.create(Product p); PA165 - SpringMVC ▼ Ljeshop-api ▼ EJ src ▼ ED main ▼ EJ java ▼ & cz.fi.muni.pal 65 ▼ §□ dto © fa C ate g o ryC re ate DTO ©fa CategoryDTO ©fa Color ©fa NewPriceDTO ©fa OrderDTO ©fa OrderltemDTO ©fa PriceDTO ©fa ProductChangelmageDTO ©fa ProductCreateDTO ©fa ProductDTO © fa Use rAuth e nti c ate DTO ©fa UserDTO ▼ Eli enums ©fa Currency ©fa OrderState ▼ (ID exceptions @fa EshopServiceException ▼ §□ facade ■ i ■ fa CategoryFacade ■ i ■ fa OrderFacade ©fa ProductFacade ©fa UserFacade ▼ Eg eshop-service ▼ EJ src ▼ ED main ▼ E3 Java ▼ §□ cz.fi.muni.pal 65 ▼ Eli service ▼ §□ config ©fa ServiceConflguration ▼ ED facade ©fa CategoryFacadelrnpl ©fa OrderFacadelmpI ©fa ProductFacadelrnpl ©fa UserFacadelmpI ©fa BeanMappingService ©fa BeanMappingServicelmpI i fa CategoryService CategoryServicelmpI ©fa ExchangeService ©fa ExchangeServicelmpI ® fa OrderService © fa OrderServicelmpI ©fa ProductService © fa ProductServicelmpI ® fa TimeService © fa TimeServicelmpI © fa Transition ® fa UserService © fa UserServicelrnpl Co eshop-persistence ▼ ED src ▼ CD main ▼ CD java ▼ ill cz.fi.tnuni.pa165 ▼ Hj dao I fa CategoryDao 0fa CategoryDaolrnpl 0fa OrderDao 0fa OrderDaolrnpl (Dft OrderlternDao Cq) ft OrderlternDaolmpI © ft PriceRepository ProductDao ©ft ProductDaolmpI 0ft UserDao 0fa UserDaolrnpl ▼ [_-■ entity 0ft Category 0ft Order ■ C - fa Orderltem 0fa Price 0ft Product 0fa User ▼ enurns 0 fa Currency 0ft OrderState ► SD utils ▼ §□ validation @ ft AIIOrNothing ■ c) fa Al10rNothingVaIidator PA165 - SpringMVC ▼ Ea eshop-spring-muc ▼ ED src ▼ ED main ▼ ED java ▼ cz.muni.fi.pa165.rnvc ▼ dD config ©ft MySpringMvcConfig © ft MyStartlnitialiier ▼ EID controllers ©ft Categon/Controller © ft ExarnpleController ©ft OrderController © ft ProductController ©ft ShoppingControler ©ft UserController ▼ (ID forms © ft P ro d u etc re ate DTO Va lidator ▼ dD security © ft ProtectFiIter ▼ Ca resources S logback.xml ► Eft Resource Bundle Texts' ▼ Eowebapp ▼ Ejweb-inf ▼ ED jsp ► ED category ► ED order ► ED product ► ED shopping ► ED user [a) bar.jsp B example.jsp laj home.jsp ► ED tags [i| favicon.ico E no-image.png _ Business logic on service layer • OrderService.shipOrder(Order o) • OrderService.finishOrder(Order o) • OrderService.cancelOrder(Order o) • ProductService.changePrice(Product p, Price r) • UserService.registerUser(User u, String psswd) • UserService.authenticate(User u, String psswd) PA165 - SpringMVC 9 eShop Architecture Summary • separate layers for UI, API, services and persistence • layers implemented in separate Maven modules • Maven project using both project inheritance and aggregation • kept in GitHub https://github.com/fi-muni/PA165 PA165 - SpringMVC 10 The problems of today's web design • wide range of screen sizes from 3" phones to 30" desktop monitors • wide range of pixel densities (80ppi - 560ppi) • touch screens do not have "mouse over" events • devices change orientation (portrait / landscape) PA165 - SpringMVC 11 Responsive web design • web design that adapts to screen size and pixel density • CSS media queries - @media screen and (min-width: 4OOpx){...} • CSS pixels versus hardware pixels - CSS pixels are 96ppi at 28" distance (lpx=0.26mm) - hardware pixels described in CSS by device-pixel-ratio • device-pixel-ratio: 2 - iPhone4, iPad3 • device-pixel-ratio: 3 - Galaxy S4, LG G3, HTC One • device-pixel-ratio: 4 - Galaxy Note Edge, Xiaomi Mi3 - images should be served in HW pixel resolutions PA165 - SpringMVC 12 Bootstrap • CSS framework for responsive web design • navigation menu collapses on small screens • 12-column grid for positioning • 4 screen sizes: extra small, small, medium, large • CSS classes for rows and columns
|
PA165 - SpringMVC 13 desktop 24" 1920x1080 90ppi tablet 10" 1920x1200 224ppi PA165 SpringMVC eShop Nákupy Správa^ Dokumentace^ Odkazy eShop overview 1.Food Strawberries 80.00 CZK Raspberries 90.00 CZK Blackberries 20.00 CZK Blueberries 25.00 CZK Figs 100.00 CZK < A □ the same 10" in portrait mode © — ^ (mi 6:16 J \£s eShop overview Am Ct @Autowired private MessageSource messageSource; @RequestMapping("/foo") public String too(@RequestParam irrt a, Model model) { //pass data as request attributes to views model.addAttributeC'b", a+1); // ViewResolver resolves to /WEB-INF/jsp/foo. jsp return "foo"; } PA165 - SpringMVC 22 Controller • any class annotated with ©Controller • mapping of methods to URLs is set by @RequestMapping, can have common prefix for the whole class • dependencies are injected using @Autowired • can return String, which is resolved by ViewResolver (provided by @ Enable We bMvc) to view, usually a JSP page • data are passed through instance of Model • method parameters specify inputs • automatic type conversion for request params and path PA165 - SpringMVC 23 Controller method parameters ^RequestMapping C Vf oo/{a}/-[rl: [a -z]+}{r2: \\df >") public String foot @PathVariable irrt a, @PathVariable String rl, @RequestParam long b, Locale locale, HttpMethod httpMethod, @RequestHeader("User-agenftBB) String userAgent, @CookieValue("inycookie") Cookie mycookie, Model model, HttpServletRequest req, HttpServletResponse res ) { | return "foo"; }_ PA165 - SpringMVC 24 Redirect @RequestMappingfVredir") jublic String someRedirect( Locale locale, RedirectAttributes redirAttrs) { String message = messageSource.getMessage("msg", new Object[0], locale); redirAttrs.addFlashAttribute("message", message); redirAttrs.addAttribute("pid",10); redirAttrs.addAttribute("cid",15); return "redirect: /product/-[pid}/category/-[cid}"; PA165 - SpringMVC 25 Redirects • triggered by return value starting with "redir:" • RedirectAttributes - attributes replace placeholders {attr} in URL - ©PathVariable parameters automatically added as attributes - provide so called flash attributes, which exist only during the first next request • more complex URL building possible using UriComponentsBuilder class • redirect-after-post to avoid duplicate submissions PA165 - SpringMVC 26 Product Controller ^Controller !)@RequestMapping ("/product") public class ProductController { @Autowired private ProductFacade productFacade: @RequestMapping(value = "/view/-[id}", method = RequestMethod. GfD jublic String view(@PathVariable long id, Model model) { model.addAttribute("product", productFacade,getProductWithld(id)); return "mMkS/XA^"; } @RequestMapping(value = "/delete/lid}", method = RequestMethod.POST) jublic String delete(@PathVariable long id, RedirectAttributes redirectAttributes) { productFacade,deleteProduct(id); redirectAttributes.addFlashAttribute("message", "Product was deleted."); return "redirect:/product/Iist"; } SpringMVC tag library for forms • binds form fields to bean properties • displays error messages when validation fails • keeps values entered by user when validation fails ■=%@ taglib prefix="form" uri="http://www.springframework.org/tags/forni" %> Name C re a t e PA165 - SpringMVC 28 ©Valid and BindingResult @RequestMapping(value = "/create", method = RequestMethod.POST) jublic String create(@Valid @ModelAttribute ProductCreateDTO productCreate, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); } return "podW^SLft^"; } //create product Long id = productFacade.createProduct(productCreate); redirectAttributes.addFlashAttribute("alert_success", "Product was created"); redirectAttributes.addAttribute("id", id); return "redirect:/product/view/{id}"; } PA165 - SpringMVC 29 Input data validation • JSR-303 "Bean validation" provides annotations and validators for Java bean properties • Hibernate Validator is implementation of JSR-303 • @NotNull, @Max, @Min, @Size, ©Pattern, ... • a single definition of validation reused in various layers - e.g. persistence and web forms • you can define your own annotation and provide its validator and localized error messages • example is @AIIOrNothing and AIIOrNothingValidator in eshop-persistence • class with @EnableWebMvc has to provide Validator instance PA165 - SpringMVC 30 Example of JSR-303 annotations public class ProductCreateDTO { @NotNull @Size(min = 3, max = 50) private String name; @NotNull @Size(min = 3, max = 500) private String description; @NotNull @Min(0) private BigDecimal price; @NotNull private Currency currency; @NotNull private Long categoryld; PA165 - SpringMVC 31 SpringMVC validation • method marked with @lnitBinder can add another validator implementing org.springframework.validation.Validator instead of javax. validation. Validator • implements validate (Object target, Errors errors) • can do complex validation including checking relations among values of multiple properties • ProductCreateDTOValidator class in example eShop PA165 - SpringMVC 32 Summary • controllers process HTTP requests - send Model to views to display - or send redirects (always after POST) • flash attributes for passing data through redirects • forms tag library helps in form handling • request parameters may be bound to properties of a method parameter with @ModelAttribute • JSR-303 Bean Validation and SpringMVC validation can be used together or separately PA165 - SpringMVC 33 Thank you for you attention PA165 - SpringMVC 34