Andrey Stukalenko Last update: March, 2012 Spring Framework Module 8 – Spring 3 MVC.

Презентация:



Advertisements
Похожие презентации
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
Advertisements

1/27 Chapter 9: Template Functions And Template Classes.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
Evgeniy Krivosheev Vyacheslav Yakovenko Last update: Feb, 2012 Spring Framework Module 4 – JNDI.
1 © Luxoft Training 2012 Inner and anonymous classes.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
11 BASIC DRESS-UP FEATURES. LESSON II : DRESS UP FEATURES 12.
Carousel from flshow.netflshow.net by Saverio CaminitiSaverio Caminiti.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Evgeniy Krivosheev Andrey Stukalenko Vyacheslav Yakovenko Last update: Nov, 2013 Spring Framework Module 1 - Introduction.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
1 © Luxoft Training 2013 Spring Framework Module 10 JMS & EJB.
Unit II Constructor Cont… Destructor Default constructor.
Linux Daemons. Agenda What is a daemon What is a daemon What Is It Going To Do? What Is It Going To Do? How much interaction How much interaction Basic.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Optimizing BGP Scalability Implementing BGP Peer Groups.
1 When And How To Make Interfaces Work For You Advanced OO Techniques Alex Herbstritt Principal Software Engineer, Progress Software Session 102.
Overview of the Paysonnel CE. Overview Paysonnel CE Go to URL- 1 Click [Login to Paysonnel CE] 2 How to Log-in to Paysonnel CE 1 2.
Транксрипт:

Andrey Stukalenko Last update: March, 2012 Spring Framework Module 8 – Spring 3 MVC

2 Spring:: MVC :: Introduction

3 Spring model is more flexible:

4 Spring :: MVC :: Introduction Spring MVC Controller – is not a classic MVC Controller. Role of MVC Controller is done by Spring MVC DispatcherServlet:

5 Spring:: MVC :: Example public class OrderController implements Controller { private OrderRepository public OrderController(OrderRepository orderRepository) { repo = orderRepository; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Order order = repo.getOrderById(id); return new ModelAndView("orderView", "order", order); } The following example shows how simple Spring controller can access business objects defined in the same application context. This controller looks up Order object and returns it through handleRequest () method:

6 Spring:: MVC :: Example Spring IoC isolates this controller from OrderRepository implementation, which can work on the basis of JDBC in the same manner as on the basis of web service. An interface can be implemented with: –POJO, –Stub, –Proxy –Remote object. Controller doesnt include anything related to searching resources; what it includes is a code needed for web interaction.

7 Spring:: MVC :: Spring MVC benefits –Spring offers clear separation between controllers, JavaBean models and views. –Spring MVC is flexible. Spring MVC is fully interface-based. You can substitute any Spring MVC part for your implementation of required interface. For this purpose Spring offers out-of-the-box implementations of all necessary interfaces. –Along with controllers Spring provides interceptors that are useful when you want to implement logic common to all requests. –Spring is really independent from a specific view technology. You dont have to write JSPs if you dont want to. You can use Velocity, XSLT or any other view technology. If youre going to use your own technology, for example a template language, you can do that by simply implementing the SpringView interface as you need. –Spring controllers are configured via IoC as any other object. That facilitates testing and integration with other Spring-controlled objects. –Generally, Spring MVC Web layer is easy testable, as long as inheriting specific classes is not required, and controller is not tied to dispatcher servlet.

8 Spring :: MVC :: Introduction

9 Spring:: MVC :: Example Spring MVC supports data binding, forms, masters and more complex approaches. Binding: binding and charting parameters of HTTP requests for objects properties (Java beans) and vice versa. Useful when interacting with user input. Resolver, mapping: an object implementing mapping (for example, URL requests and views)

10 Spring:: MVC :: Architecture WebApplicationContext: ApplicationContext adapted for work in Web. DispatcherServlet: a servlet used in intercepting all users requests. It implements FrontController pattern. Model: java.util.Map Stores data as key-value pair View: interface View When this interface is implemented the data is viewed Controller: interface Controller When this interface is implemented users requests are handled

11 Spring:: MVC :: WebApplicationContext This is an extension of ApplicationContext that has some extra features necessary for web applications (for example, association with ServletContext ). Adds three scopes of bean lifecycle that are only available in web context (request, scope, global). Special bean types can only exist in WebApplicationContext.

12 Spring:: MVC :: WebApplicationContext Configuration To initialize a context, add ContextLoaderListener to web.xml During context initialization, beans defined in files applicationContext.xml and [servlet-name]-servlet.xml (except for lazy-init beans) are instantiated (for each DispatcherServlet ) File set used in beans instantiation can be changed by specifying contextConfigLocation parameter in application descriptor.

13 Spring:: MVC :: WebApplicationContext WebApplicationContext configuration in several files (web.xml): org.springframework.web.context.ContextLoaderListener contextConfigLocation /WEB-INF/context.xml /WEB-INF/handlers.xml /WEB-INF/validators.xml

14 Spring:: MVC :: DispatcherServlet web.xml configuration: viewer org.springframework.web.servlet.DispatcherServlet 1 viewer *

15 Spring:: MVC :: Web & RESTful service controllers Basic interface: package org.springframework.web.servlet.mvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; public interface Controller { ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response ) throws Exception; }

16 Spring:: MVC :: Web & RESTful service controllers AbstractController: Provides access to ServletContext and ApplicationContext Undertakes work with some HTTP headers Manages caching and synchronization Is a superclass for all other implementations

17 СвойствоОбъяснение supportedMethodssupported HTTP methods (by default, GET,POST) requireSessionif no session is found while processing the request, an exception will be thrown synchronizeOnSession indicates whether the call to main method should be synchronized around the session cacheSecondscaching the result for XX seconds useExpiresHeaderShould HTTP-header "Expires should be in the response; true by default useCacheHeader Should header Cache-Control be in response Spring :: MVC :: AbstractController AbstractController - Manages caching and synchronization Is a superclass for all other implementations

18 Spring:: MVC :: AbstractController Example of using AbstractController: package samples; public class SampleController extends AbstractController { public ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response ) throws Exception { ModelAndView mav = new ModelAndView("hello"); mav.addObject("message", "Hello World!"); return mav; }.xml:

19 Spring :: MVC :: DispatcherServlet

20 Spring :: MVC :: WebApplicationContext ControllersProcess user requests Handler mappings Analyze URL and forwards user request to controller, according URL controller mapping For example, /viewOrder OrderController View resolvers Defines which view should be returned in response to name, for example orderView /jsp/orderView.jsp Locale resolverDefines what locale should be used Theme resolverDefines theme (visual look) Multipart file resolverProvides file upload Handler exception resolver Defines how exceptions will be handled We can describe follow beans in WebApplicationContext :

21 Spring:: MVC annotation Dont forget about context public class HelloWorldController public ModelAndView helloWorld() { ModelAndView mav = new ModelAndView(); mav.setViewName("helloWorld"); mav.addObject("message", "Hello World!"); return mav; }

22 Spring:: public class OrderController private OrderRepository repo; public OrderController(OrderRepository orderRepository) { repo = orderRepository; public String viewOrder(int orderId, Model model) { Order order = repo.getOrderById(id); model.put(order); return orderView; } Dont forget to add component-scan:

23 Spring:: MVC A common pitfall when working with annotated controllers is using AOP, on the whole, and declarative transaction management, in particular. Standard JDK Dynamic Proxies only work with interfaces. To use it with controllers you have to move annotations to the interface (as far as mapping mechanism can see proxy), which is notably uncomfortable. Alternatively, activate - proxy-target-class="true" and use CGLib Therefore (think of AOP and TX), when working with web applications, do everything DIRECTLY on classes

24 Spring:: MVC Configuring mapping annotations: Specified for: Controller (class): path to all controller methods; Controllers methods: If class path is specified then the path is relative; Absolute path if not specified for public String String String petId, Model model) { // public class RelativePathUriTemplateController public void String String petId, Model model) { // implementation } URL patterns are is used to bind variable (argument) to the value of URL template; Used in implementing RESTful services;

25 Spring:: MVC value: specifies URL pattern. Supports: parameterized (/somepath/{someVar}) URL patterns Ant-style (/somepath/*.do) their combinations (/owners/*/pets/{petId}) If there is no argument, method name is used in mapping method: binding to request type: RequestMethod.POST RequestMethod.GET params: indicates whether some specific parameters for the request are needed myParam = myValue: parameter with specified value myParam: parameter with arbitrary value !myParam: no parameter in the request headers: narrowing to request header (for example, "content-type=text/*»)

26 Spring:: Binding to request parameters is made annotation By default, such parameters are mandatory, but could be turned to optional with required=false command. = RequestMethod.POST) public String int petId, ModelMap = RequestMethod.GET) public String required=false) int id, ModelMap model)

27 Ant-style URI will process request /antstyle/a/hi or /antstyle/b/hi or /antstyle/abracadabra/hi, because of use symbol = "/antstyle/*/hi") public String antStyle() { return ANT_STYLE_VIEW_NAME; } Spring :: MVC

28 Spring :: MVC Request headers Method catches only requests which has Content-Type header, which value starts with text/ = "/headers", headers="content-type=text/*") public String headersText(Model model) { model.addAttribute("contentType", "text/*"); return HEADERS_VIEW_NAME; } Method catches only requests which has Content-Type header, which value equals to = "/headers", headers="content-type=application/json") public ResponseEntity headersJson() { String json = "{\"contentType\":\"application/json\"}"; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity ( json, responseHeaders, HttpStatus.CREATED ); }

29 Use of standard HttpServletRequest and HttpSession in controller To provide easier work on legacy code we can use javax.servlet.http.HttpServletRequest and = "/httpservletrequest") public String httpServletRequest(HttpServletRequest request, Model model) { model.addAttribute("content", "User-Agent: " + request.getHeader("User-Agent") ); return OTHER_VIEW_NAME; = "/httpsession") public String httpSession(HttpSession session, Model model) { model.addAttribute("content", "Session id: " + session.getId() ); return OTHER_VIEW_NAME; } Spring :: MVC

30 WebRequest in controller The most powerful class to process requests is org.springframework.web.context.request.WebRequest. It has all necessary to get all information about request: headers, localization, session, Principal object, = "/webrequest") public String webRequest(WebRequest webRequest, Model model) { model.addAttribute("content", "Session id (WebRequest): " + webRequest.getSessionId() ); return OTHER_VIEW_NAME; } Spring :: MVC WebRequest methods: checkNotModified(long lastModifiedTimestamp), getContextPath(), getLocale(), getParameterMap() getRemoteUser(), isSecure(), isUserInRole(String role), getUserPrincipal(), getDescription(boolean includeClientInfo)

31 Use Locale in Spring MVC Its very easy to get a user = "/locale") public String locale(Locale locale, Model model) { model.addAttribute("content", "Locale language: " + locale.getLanguage() ); return OTHER_VIEW_NAME; } Spring :: MVC

32 Principal (user) in Spring MVC Principal contains information about autorized = "/principal") public String principal(Principal principal, Model model) { model.addAttribute("content", "Principal: " + (principal == null ? "null" : principal.getName() ) ); return OTHER_VIEW_NAME; } Spring :: MVC

33 Processing of additional requests As translates request parameter to variable. Also you shouldnt worry about type: Spring will cast it itself. If the param is not required, just set required required=false) int = "/requestparam") public String int foo, Model model) { model.addAttribute("content", "foo=" + foo ); return OTHER_VIEW_NAME; } Spring :: MVC

34 Processing = "/requestheader") public String String userAgent, Model model) { model.addAttribute("content", "User-Agent: " + userAgent ); return OTHER_VIEW_NAME; } Spring :: MVC

35 Spring :: MVC :: AJAX var checkResult = { available: false, suggestions: ["john0", "john1", "john2013", "john2014"] } class CheckResult { public boolean available; public List suggestions; } JavaScript function to check a user name availability: function checkName() { $.getJSON("/checkName", { name: $('#name').val() }, function(checkResults) { if (checkResults.available) { $("#nameCheckResult").html("name is available!") } else { $("#nameCheckResult").html("name is not available! try " +checkResults.suggestions.join(",")); } }); } john Enter user name: Register name is not available! try john0, john1, john2013, john2014

36 Spring :: MVC :: AJAX interface NameService { User findByName(String name); List getNameSuggestions(String name); method=RequestMethod.GET) CheckResult String name) { CheckResult result = new CheckResult(); User user = getNameService().findByName(name); if (user != null) { result.available = true; return result; } result.available = false; result.suggestions = getNameService().getNameSuggestions(name); return result; } class CheckResult { public boolean available; public List suggestions; }

37 Spring :: MVC :: AJAX domain model DB table Java modelJSON on JS DB business logic (Java) client code (JS) Client information Name: Phone: Save serialization (Spring)

38 allows to use HTTP-cookie in controller method. Here we get JSESSIONID value from = "/cookie", method = RequestMethod.GET) public String String jsessionid, Model model) { model.addAttribute("msg", "JSESSIONID: " + jsessionid ); return "info"; } Spring :: MVC

allows to get HTTP header in controller = "/header", method = RequestMethod.GET) public String String encoding, Model model) { model.addAttribute("msg", "Accept-Encoding: " + encoding ); return "info"; } Spring :: MVC

40 Spring:: MVC Supported arguments of handler methods: Request / Response objects (Servlet API). Subtypes can be used (for example, ServletRequest or HttpServletRequest); Servlet API Session object (HttpSession). An argument of this type enforces the presence of a corresponding session when it is absent; WebRequest and NativeWebRequest (org.springframework.web.context.request package) allows for request parameters access without ties to Servlet/Portlet API ; java.util.Locale for the current request locale; InputStream / Reader for access to the requests content; OutputStream / Writer for generating the responses content; java.security.Principal containing the currently authenticated annotated parameters for access to URI template variables annotated parameters for access to request parameters ;

41 Spring:: MVC Supported arguments of handler methods annotated parameters for access to specific request for access to the request body; java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap to access to the model that is exposed to the web view; org.springframework.validation.Errors / org.springframework.validation.BindingResult : for access/validation results for an object. This argument shall follow the validated object immediately, as each object is validated and tied to validation result separately; org.springframework.web.bind.support.SessionStatus for controlling session state and session closing (it triggers cleanup of session attributes);

42 Spring:: MVC Supported method return types: ModelAndView: for returning model and View name; Model: for returning model. View name will be determined through RequestToViewNameTranslator ; Map is analogous to Model ; View is a view object. Model will be automatically inserted (changes introduced to model with handler argument will be inserted); String is a logical view name that is handled by ViewResolver; void: if method handles a response itself or if view name is determined through RequestToViewNameTranslator; If the method is annotated the return type is written to the response HTTP body; Any other return type is considered to be a single model attribute using name specified at the method level or automatically generated based on the return type;

43 Spring :: MVC Let we have to print the list of address: We can use this public class AddressController { private AddressService method = RequestMethod.GET) public String getAllAddresses(Model model) { model.addAttribute("addresses", addressService.getAll()); return "addressespage"; } URL: /address/list2

44 Spring :: MVC Or we @RequestMapping("/address") public class AddressController public List getAllAddresses() { // Delegate to service return addressService.getAll(); } private AddressService method = RequestMethod.GET) public String getAllAddresses(Model model) { model.addAttribute("addresses", addressService.getAll()); return "addressespage"; }

45 Spring :: MVC Id: First Name: Last Name Money Currency:

46 Spring :: @RequestMapping("/main") public class MainController = "/edit/{id}", method = RequestMethod.GET) public String Integer id, Model model) { model.addAttribute("personAttribute", personService.get(id)); return "editpage"; = "/edit/{id}", method = RequestMethod.POST) public String Person Integer id, Model model) { // Добавляем id в person т.к. поле id было disabled и не передалось person.setId(id); // обращаемся к сервису, чтобы сохранить заполненную модель personService.save(person); // вручную добавляем persons в модель, т.к. getPersons() // вызывается ДО saveEdit() // и иначе не будет включать только что добавленного человека model.addAttribute("persons", personService.getAll()); return "personspage"; }

47 Spring :: MVC So we have 2 scenarios of : Method annotation – to get the model public List getAllAddresses() { return addressService.getAll(); } Annotation to the method parameter – links module attribute to the parameter. It can be used to get access to data entered by the user in the = "/edit/{id}", method = RequestMethod.POST) public String Person Integer id, Model model) { } Call happens before calling method annotated

48 Spring :: MVC :: Scopes Scopes in web-application: how long the bean does exist

49 Spring :: MVC :: Scopes Scope Description singleton The single instance in IoC container prototype One definition, but multiple instances request One definition in single HTTP request Example: session Obe definition is HTTP session Example: global session One definition in a global HTTP-session (only for portlets).

50 Spring:: is specified at the level of controller class; Declares which model attributes should be stored in session for transferring between requests; Initialized when you put object into model; Refreshed from HTTP parameters, when controller method is being executed Processing POST request, Spring is doing the following: Spring creates new instance of User and fill it with form data Spring gets User from session (it was placed to session when executing GET-request, was presented), refresh fields by form values and send to saveForm().

51 public class UserController { private UserService = RequestMethod.GET) public String showUserForm(ModelMap model) { // set new User id User user = new User(); // put user to session model.addAttribute(user); return "userForm"; } // user comes from session and joined with other form = RequestMethod.POST) public String User user) { // fields coming from the form are renewed; // other fields(such as id) left the same (taken from session) userService.save(user); return "redirect:userSuccess.htm"; } Spring :: MVC User form User name: Password: Save

52 Spring:: public class EditPetForm public Collection populatePetTypes() { return this.clinic.getPetTypes(); = RequestMethod.POST) public String Pet pet, BindingResult result, SessionStatus status) { new PetValidator().validate(pet, result); if (result.hasErrors()) { return "petForm"; } else { this.clinic.storePet(pet); status.setComplete(); return "redirect:owner.do?ownerId=" + pet.getOwner().getId(); }

53 Spring:: MVC :: Exceptions Handling exceptions: HandlerExceptionResolver interface and one ready SimpleMappingExceptionResolver implementation. Mapping between exception classes and view names based on the Properties. Catches exceptions thrown by handlers and passes them via model. More flexible mechanism as compared to web.xml, as far as its own implementation can be done. <bean id="exceptionResolver class=org.springframework.web.servlet. handler.SimpleMappingExceptionResolver"> com.luxoft.spring.CustomException=customException java.lang.SecurityException=error403 java.lang.Throwable=error

54 Spring :: public class MyExceptionHandlerExampleController = "/makeNPE") public ModelAndView npe() { String oops = null; oops.indexOf("oops"); return new ModelAndView("hello"); public ModelAndView handleNPException(NullPointerException e) { ModelAndView modelAndView = new ModelAndView("oops"); modelAndView.addObject("message", "NullPointerException at " + System.currentTimeMillis()); return modelAndView; }

55 Spring:: MVC Within a controller you can specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods Method arguments are equal to handler public class SimpleController public String handleIOException(IOException ex, HttpServletRequest request) { return ClassUtils.getShortName(ex.getClass()); }

56 Spring :: MVC :: View Render model built in controller; Out of the box, Spring enables you to use JSPs, Velocity templates, XSLT views, View or Tiles interface implementations; Interface implementations of ViewResolver are used for mapping between view names (with locales) and view objects;

57 Spring :: MVC :: ViewResolver To resolve View using the result of controller method ViewResolver is used:

58 Spring :: MVC :: ViewResolver Configuration example for JstlView: <bean id="viewResolver" class="org.springframework.web.servlet.view. InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

59 Spring :: MVC :: ViewResolver All ViewResolver implementations are caching data processed by view Its possible to change it, by setting cache to false. Also its possible to remove view from cache programmatically: removeFromCache(String viewName, Locale loc )

60 <bean class="org.springframework.web.servlet.view. ResourceBundleViewResolver"> WelcomePage.(class)=org.springframework.web.servlet.view.JstlView WelcomePage.url=/WEB-INF/pages/WelcomePage.jsp spring-views.properties (file should be in classpath): Spring :: MVC :: ViewResolver Use of ResourceBundleViewResolver public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("WelcomePage"); } Controller:

61 <bean class="org.springframework.web.servlet.view. XmlViewResolver"> <bean id="WelcomePage" class="org.springframework.web.servlet.view.JstlView"> /WEB-INF/spring-views.xml: Spring :: MVC :: ViewResolver Use of XmlViewResolver: public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("WelcomePage"); } Controller:

62 Spring:: MVC :: ViewResolver All view resolvers implement Ordered interface. This allows to have several resolvers that work in a certain sequence. For this reason order property should be set. If not specified explicitly, such a resolver will work the last. This may be necessary in some cases to redefine certain views if a single resolver doesnt support all View implementations used.

63 Spring:: MVC :: Localization For JSP, use custom tag. As a substitute for entries, you specify entry keys stored in properties files; Define MessageSource in a context; Entries text should be carried to. properties files named according to supported locales; Specify locale resolution, a LocaleResolver implementation, in the context (this is optional, because there is a default resolver);

64 Spring :: MVC :: Localization... applicationContext.xml: <bean id="messageSource" class="org.springframework.context.support. ResourceBundleMessageSource"> messages_en.properties: exception.thrown=Exception was thrown error.page=Information about the error This is an error page:

65 Spring:: MVC :: Localization:: LocaleResolver AcceptHeaderLocaleResolver (default resolver): inspects accept-language header in the HTTP request; CookieLocaleResolver : inspect a cookie to retrieve locale; SessionLocaleResolver : retrieves locales from the sessions; FixedLocaleResolver : retrieves locale specified when bean is configured;

66 Spring :: MVC :: Localization applicationContext.xml: <bean id="localeResolver" сlass="org.springframework.web.servlet.i18n.SessionLocaleResolver"> <bean class="org.springframework.web.servlet.i18n. LocaleChangeInterceptor" p:paramName=lang /> URL to change the language: /?lang=ro

67 Spring:: MVC :: Localization:: LocaleResolver To change locale user is able to: Configure browser settings (if AcceptHeader resolver is used) ; Invoke method RequestContextUtils.getLocaleResolver(request).setLocale(request, response, locale). A cookie or session attribute will be created; Directly set Locale in controller code Specify HandlerMapping interceptor like LocaleChangeInterceptor. Specify locale as request parameter (the easiest way of language switch support);

68 Spring:: MVC :: Themes A theme is a collection of static resources that affect the visual style of the application. Generally, it is images and style sheets (CSS). You can: Use spring:theme tag in pages instead of hard links to resources; Specify ThemeSource in the context; Move links to different resources (images, style sheets) to properties files that are named in accordance with themes; Define theme resolution in the context: ThemeResolver implementation;

69 Spring :: MVC :: Themes <link rel="stylesheet" type="text/css" href=" " /> ">... applicationContext.xml: <bean id="themeSource class="org.springframework.ui.context.support. ResourceBundleThemeSource"/> cool.properties: css=/themes/cool/style.css bg=/themes/cool/img/bg.jpg

70 Spring:: MVC :: Themes You can: Use spring:theme tag in pages instead of hard links to resources; Specify ThemeSource in the context; Carry links to different resource (images, style sheets) to properties files that are named in accordance with themes; Define theme resolution in the context: ThemeResolver implementation;

71 Spring:: MVC :: Themes Example of JSP file: <link rel="stylesheet" type="text/css" href=" " /> ">...

72 Spring:: MVC :: Themes CookieThemeResolver : theme name is retrieved from cookie; SessionThemeResolver : theme name is retrieved from session; FixedThemeResolver : retrieves theme name specified during bean configuration;

73 Spring::MVC::Themes::ThemeResolver applicationContext.xml: <bean id="themeResolver" сlass=" org.springframework.web.servlet.theme. SessionThemeResolver /> <bean class="org.springframework.web.servlet.theme. ThemeChangeInterceptor" p:paramName=look /> URL to change the theme: /?look=dark

74 Spring:: MVC :: Themes One-time theme change: Invoke RequestContextUtils.getThemeResolver(request).setThemeName(themeName) method. A cookie or session attribute will be created; Directly in controller code; Specify for HandlerMapping an interceptor like ThemeChangeInterceptor. Specify theme name as request parameter;

75 Spring:: MVC :: Themes + Localization Sometimes in the themes you want images to have text. It is enough to create additional properties files that are named according to locales for each theme, for example: cool.properties cool_ru_RU.properties cool_en_US.properties dark.properties dark_ru_RU.properties dark_en_US.properties

76 Spring:: MVC :: Multipart Multipart support handles file uploads from html forms Form attribute enctype should be set to multipart/form-data Files uploaded using By default, multipart processing is turned off

77 Spring:: MVC :: Multipart org.springframework.web.multipart package : MultipartResolver interface CommonsMultipartResolver and CosMultipartResolver implementations Necessary libraries: commons-io.jar and commons-fileupload.jar ; or cos.jar ;

78 Spring:: MVC :: Multipart In application context create bean: MultipartResolver implementation; Each request is inspected for multiparts; if multipart is found the request is wrapped in a MultipartHttpServletRequest Example: <bean id="multipartResolver" class="org.springframework.web.multipart. commons.CommonsMultipartResolver">

79 Spring:: MVC :: Multipart :: MultipartResolver maxInMemorySize : set the maximum allowed size before uploads are written to disk (by default, 10KB) ; maxUploadSize : set the maximum total size (by default, it is not limited); uploadTempDir : set the temporary directory where uploaded files get stored. By default, containers temporary directory; defaultEncoding : set encoding to use for parsing headers of individual parts. Has less priority than one explicitly specified in request;

80 Spring:: MVC :: Multipart Form example: prefix="form uri="

81 Spring:: MVC :: Multipart Controller public class FileUpoadController = "/form", method = RequestMethod.POST) public String String MultipartFile file) { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; }

82 Spring:: MVC :: Tag Library There are 2 tag libraries: Spring prefix="spring uri=" Spring-form prefix="form uri=" Their main purpose is to help binding given API JSPs, form objects and form elements and vice versa; Almost every tag has an attribute htmlEscape that allows to control HTTP/JS code shielding. defaultHtmlEscape parameter from web.xml is taken into account as well.

83 Spring:: MVC :: Tag Library Themes and locales tags: theme tag: using ThemeResolver and ThemeSource substitutes itself for resource path whose name is specified in code attribute. message tag: using LocaleResolver and MessageSource substitutes itself for localized message whose name is specified in code attribute.

84 Spring :: MVC :: Tag Library Tag form : Has commandName attribute, which contains the name of form object. Генерирует html-элемент Input fields: tags input, hidden, textarea, password Generate input of the according type; In value attribute the form property is set, which is stated in path attribute; In name attribute you should set path to allow data binding on sending;...

85 Spring :: MVC :: Tag Library Toggle groups: Tag radiobutton Tag checkbox Generate according html elements; Attributes: path – path to the property of the form; items – java.util.Map, model element; Used several times with the same path and different value. After binding those will be checked which has the same property value as the value attribute Interests: Books Games … Sex:

86 Use spring-form tag library and spring tag library for binding: Spring :: MVC :: Tag Library With use of : Manual binding benefits with use of : -Possibility to use standatd html tags -More flexible processing of binding errors

87 Spring :: MVC :: Tag Library... ${msg} There were ${errors.errorCount} error(s) in total: <spring:message code="${errMsgObj.code}" text="${errMsgObj.defaultMessage}"/>

88 Spring :: MVC :: Validation Tag : Has attributes: modelAttribute/commandName : property for which binding errors are rendered (* = all errors) ; cssClass : css class bound to block; Generates html element that renders binding errors through ; You can create several of them in different page areas for rendering binding errors of specific properties;...

89 public class = 1, max = 20) private private Integer = "Password must not be = 1, max = 10, message = "Password must be between 1 to 10 Characters.") private String password;... } JSP: User Name: Age: … Spring :: MVC :: Validation

90 public class ValidationController { // Display the form on the get = RequestMethod.GET) public String showValidatinForm(Map model) { ValidationForm validationForm = new ValidationForm(); model.put("validationForm", validationForm); return "validationform"; } // Process the = RequestMethod.POST) public String ValidationForm validationForm, BindingResult result, Map model) { if (result.hasErrors()) { return "validationform"; } // Add the saved validationForm to the model model.put("validationForm", validationForm); return "validationsuccess"; } } Spring :: MVC :: Validation

91 Any questions!?

92 Exercises : 9 : Web application development based on Spring MVC – 45 min for practice; – 15 min for discussion;