SlideShare a Scribd company logo
1 of 72
Download to read offline
Spring Framework - MVC




                SPRING FRAMEWORK 3.0
Dmitry Noskov   Spring MVC
The Spring WEB stack




              Spring Framework - MVC   Dmitry Noskov
MVC




      Spring Framework - MVC   Dmitry Noskov
Web frameworks
   request-based
       Struts, Spring MVC
   component-based
       JSF, GWT, Wicket
   RIA
       Flex




                             Spring Framework - MVC   Dmitry Noskov
What is Spring MVC?
   web component of Spring Framework
   request based web framework




                      Spring Framework - MVC   Dmitry Noskov
Request processing workflow


                 Spring Framework - MVC   Dmitry Noskov
Front controller
<servlet>
  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/web-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
  <url-pattern>/app/*</url-pattern>
</servlet-mapping>
                                   Spring Framework - MVC   Dmitry Noskov
Application context
<web-app version="2.5">
  <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/root-context.xml</param-value>
  </context-param>


  <listener>
   <listener-class>
     org.springframework.web.context.ContextLoaderListener
   </listener-class>
  </listener>
</web-app>



                           Spring Framework - MVC   Dmitry Noskov
Context




          Spring Framework - MVC   Dmitry Noskov
UrlRewrite
http://www.tuckey.org/urlrewrite/


<filter>
  <filter-name>UrlRewriteFilter</filter-name>
  <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>UrlRewriteFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>




                                   Spring Framework - MVC   Dmitry Noskov
Mapping
<urlrewrite default-match-type="wildcard">
 <rule>
   <from>/</from>
   <to>/app/welcome</to>
 </rule>
 <rule>
   <from>/**</from>
   <to>/app/$1</to>
 </rule>
 <outbound-rule>
   <from>/app/**</from>
   <to>/$1</to>
 </outbound-rule>
</urlrewrite>


                            Spring Framework - MVC   Dmitry Noskov
WebApplicationContextUtils(1)

public class ExchangerServlet extends HttpServlet {


    private AccountService accountService;


    @Override
    public void init() throws ServletException {
        ServletContext sc = super.getServletContext();
        ApplicationContext context =
            WebApplicationContextUtils.getWebApplicationContext(sc);


        accountService = context.getBean(AccountService.class);
    }
}


                                Spring Framework - MVC   Dmitry Noskov
WebApplicationContextUtils(2)

public class ExchangerFilter implements Filter {
    private AccountService accountService;


    @Override
    public void init(FilterConfig config) throws ServletException {
        ServletContext sc = config.getServletContext();
        ApplicationContext context =
            WebApplicationContextUtils.getWebApplicationContext(sc);


        accountService = context.getBean(AccountService.class);
    }
}


                                Spring Framework - MVC   Dmitry Noskov
Controller
@Controller
@RequestMapping
@RequestParam
@PathVariable




              Spring Framework - MVC   Dmitry Noskov
Mapping requests
   by path
@RequestMapping("/welcome")

   by HTTP method
@RequestMapping(value = "/welcome", method=RequestMethod.GET)

   by presence / value of query parameter
@RequestMapping(params = {"find=ByMake", "form" })

   by presence / value of request header
@RequestMapping(value = "/welcome", headers="accept=text/*")




                              Spring Framework - MVC   Dmitry Noskov
Simple Controller


@Controller
public class WelcomeController {


    @RequestMapping("/welcome")
    public void welcome() {
    }
}




                              Spring Framework - MVC   Dmitry Noskov
Use case controller
@Controller
public class CarController {
    @RequestMapping("/showcar.do")
    public String show(@RequestParam("id") id, Model model) {
        model.addAttribute("car", Car.findCar(id));
        return "jsp/cars/car.jsp";
    }


    @RequestMapping("/carlist.do")
    public String list(Model model) { /** such business logic*/}


    /** such method handlers*/
}


                                 Spring Framework - MVC   Dmitry Noskov
Unfriendly URLs

                            direct command




URL: http://localhost:8080/carbase/showcar.do?id=77




                          for each item              not very cacheable and
                                                     search engine friendly




                        Spring Framework - MVC   Dmitry Noskov
REST
   Representation State Transfer
   style of software architecture
   RPC is antipode




   http://en.wikipedia.org/wiki/Representational_State_Transfer

                                 Spring Framework - MVC   Dmitry Noskov
Http methods
   get
   post
       when the resource URL is unknown (create item)
   put
       when the resource URL is known (update item)
   delete

   post vs put
       http://stackoverflow.com/questions/630453/put-vs-post-in-rest


                                Spring Framework - MVC   Dmitry Noskov
RESTful mapping
Resource                        GET                       PUT       POST       DELETE
http://domain.com/cars          obtain list of item       update create           X
http://domain.com/cars/7        obtain item                 X              X   delete
http://domain.com/cars?form     create empty form           X              X      X
http://domain.com/cars/7?form   pre-populated form          X              X      X




                                 Spring Framework - MVC    Dmitry Noskov
RESTful URLs



URL: http://localhost:8080/carbase/cars/11




                        Spring Framework - MVC   Dmitry Noskov
Typical actions
   simple list page
   filtered list page
   CRUD:
     create
     read (retrieve)

     update

     delete

   workflow
       submit / approve / etc.
                            Spring Framework - MVC   Dmitry Noskov
List page
URL: http://localhost:8080/carbase/cars


@Controller
@RequestMapping("/cars")
public class CarController {


    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("cars", Car.findAllCars());
        return "cars/list";
    }
}



                                Spring Framework - MVC   Dmitry Noskov
Detailed page
URL: http://localhost:8080/carbase/cars/11


@Controller
@RequestMapping("/cars")
public class CarController {


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model model) {
        model.addAttribute("car", Car.findCar(id));
        return "cars/show";
    }
}



                                Spring Framework - MVC   Dmitry Noskov
Create
URL: http://localhost:8080/carbase/cars


@Controller
@RequestMapping("/cars")
public class CarController {


    @RequestMapping(method = RequestMethod.POST)
    public String create(Car car) {
        car.persist();
        return "redirect:/cars/" + car.getId();
    }
}



                                Spring Framework - MVC   Dmitry Noskov
Update
URL: http://localhost:8080/carbase/cars/


@Controller
@RequestMapping("/cars")
public class CarController {


    @RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Car car, BindingResult result) {


        /** Spring Validator*/
        //result.hasErrors();
        car.merge();
        return "redirect:/cars/" + car.getId();
    }
}
                                 Spring Framework - MVC   Dmitry Noskov
Delete
URL: http://localhost:8080/carbase/cars/11


@Controller
@RequestMapping("/cars")
public class CarController {


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id) {
        Car.findCar(id).remove();
        return "redirect:/cars;
    }
}



                                  Spring Framework - MVC   Dmitry Noskov
Filtered page
URL: http://localhost:8080/carbase/cars


@Controller
@RequestMapping("/cars")
public class CarController {


    @RequestMapping(params="find=ByMake", method=RequestMethod.GET)
    public String findByMake(@RequestParam("make")Make make, Model m) {
        m.addAttribute("cars", Car.findCarsByMake(make).getResultList());
        return "cars/list";
    }
}



                                  Spring Framework - MVC   Dmitry Noskov
Delete and put through post
   Spring tag
    <form:form action="/carbase/cars" method="PUT">

   html
    <form id="car" action="/carbase/cars" method="post">
    <input type="hidden" name="_method" value="PUT"/>



   server side
    <filter>
     <filter-name>HttpMethodFilter</filter-name>
     <filter-class>
       org.springframework.web.filter.HiddenHttpMethodFilter
     </filter-class>
    </filter>


                              Spring Framework - MVC   Dmitry Noskov
Handler arguments
   HttpSession / HttpServletRequest / etc.
   Spring’s WebRequest / NativeWebRequest
   path variable
   java.io.InputStream / java.io.OutputStream
   request’s param / header / body / cookies
   command objects

   http://static.springsource.org/spring/docs/3.0.x/spring-framework-
    reference/html/mvc.html#mvc-ann-requestmapping-arguments

                                 Spring Framework - MVC   Dmitry Noskov
Return types
   ModelAndView
   Model / Map / ModelMap
   View
   String / void
   @ResponseBody / @ModelAttribute



   http://static.springsource.org/spring/docs/3.0.x/spring-framework-
    reference/html/mvc.html#mvc-ann-requestmapping-arguments

                                 Spring Framework - MVC   Dmitry Noskov
Additional annotations
@ModelAttribute
@SessionAttributes
@RequestHeader
@CookieValue
@RequestBody / @ResponseBody


            Spring Framework - MVC   Dmitry Noskov
ModelAttribute
   maps a model attribute to the specific parameter
@RequestMapping(method = RequestMethod.POST)
public String create(@ModelAttribute("car") Car car) {}



   provide reference data for the model
    @ModelAttribute("makes")
    public Collection<Make> populateMakes() {
        return Make.findAllMakes();
    }




                                Spring Framework - MVC   Dmitry Noskov
SessionAttributes
   list the names or types of model attributes which should
    be stored in the session
@Controller
@SessionAttributes("car")//@SessionAttributes(value={}, types={})
public class CarController {
    public String updateForm(@PathVariable("id") Long id, Model model) {
        m.addAttribute("car", Car.findCar(id));
    }


    public String update(Car request, SessionStatus status) {
        status.setComplete();
    }
}


                                  Spring Framework - MVC   Dmitry Noskov
RequestHeader
   typical request header
host = localhost:8080
user-agent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203
Firefox/3.6.13 ( .NET CLR 3.5.30729; .NET4.0E)
accept = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language = en-us,en;q=0.5

   obtain request header
@RequestMapping("/welcome")
public void welcome(@RequestHeader("user-agent") String agent) {}

   narrow mappings
@RequestMapping(value = "/welcome", headers="accept=text/*")
public void welcome() {}



                                       Spring Framework - MVC   Dmitry Noskov
CookieValue

   get the JSESSIONID of the cookie
    @RequestMapping(value = "/welcome")
    public void welcome(@CookieValue("JSESSIONID") String session){
    }




                              Spring Framework - MVC   Dmitry Noskov
Data Representation




           Spring Framework - MVC   Dmitry Noskov
Approach
   template view
     ViewResolver, View
     HTML, Excel, PDF, etc.



   data view
     HttpMessageConverter
     XML, JSON, etc.




                           Spring Framework - MVC   Dmitry Noskov
View resolver
   XmlViewResolver
   ResourceBundleViewResolver
   UrlBasedViewResolver
   InternalResourceViewResolver
   BeanNameViewResolver
   ContentNegotiatingViewResolver

   http://static.springsource.org/spring/docs/3.0.x/spring-framework-
    reference/html/mvc.html#mvc-viewresolver-resolver

                                 Spring Framework - MVC   Dmitry Noskov
View
   JSP & JSTL
   Tiles
   Velocity
   FreeMarker
   etc.
   prefix
     redirect:
     forward:


                  Spring Framework - MVC   Dmitry Noskov
ResourceBundleViewResolver
   configuration
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basename" value="view"/>
</bean>

   view.properties
welcome.(class)=org.springframework.web.servlet.view.JstlView
welcome.url=/WEB-INF/jsp/welcome.jsp


cars.(class)=org.springframework.web.servlet.view.JstlView
cars.url=/WEB-INF/jsp/cars.jsp

   controller
@Controller return "cars"


                                  Spring Framework - MVC   Dmitry Noskov
UrlBasedViewResolver
<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>




   use case
If @Controller return "cars/show"
view class will process "/WEB-INF/jsp/cars/show.jsp"



                                   Spring Framework - MVC   Dmitry Noskov
Tiles(1)
   configuration
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>

<bean id="tilesConfigurer"
      class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
  <property name="definitions">
    <list>
      <value>/WEB-INF/layouts/layouts.xml</value>
      <value>/WEB-INF/**/views.xml</value>
    </list>
  </property>
</bean>

   views.xml
<definition extends="default" name="cars/show"></definition>


                                           Spring Framework - MVC    Dmitry Noskov
Tiles(2)
<bean id="tilesConfigurer"
      class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
  <property name="definitions">
    <list>
      <value>/WEB-INF/layouts/layouts.xml</value>
      <value>/WEB-INF/**/views.xml</value>
    </list>
  </property>
  <property name="preparerFactoryClass">
    <value>
     org.springframework.web.servlet.view.tiles2.   SpringBeanPreparerFactory
    </value>
  </property>
</bean>


                                          Spring Framework - MVC   Dmitry Noskov
HttpMessageConverter
   reads the request body and writes the response
   converters mapped to content types

   http://static.springsource.org/spring/docs/3.0.x/spring-framework-
    reference/html/remoting.html#rest-message-conversion


   registered by default if jar present in classpath
       Jackson, JAXB, Atom, RSS


                               Spring Framework - MVC   Dmitry Noskov
ContentNegotiatingViewResolver




           Spring Framework - MVC   Dmitry Noskov
Strategies
   URI
     www.domain.com/cars.html
     www.domain.com/cars.json

   content negotiation
     Accept: text/html…
     Accept: text/xml…

     Accept: application/pdf…




                          Spring Framework - MVC   Dmitry Noskov
Example(1)
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 <property name="mediaTypes">
    <map>
      <entry key="atom" value="application/atom+xml"/>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
 </property>
 <property name="viewResolvers">
    <list>
      <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
    </list>
 </property>
 <property name="defaultViews">
   <list><bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/></list>
 </property>
</bean>



                                        Spring Framework - MVC   Dmitry Noskov
Example(2)
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 <property name="order" value="1" />
 <property name="mediaTypes">
    <map>
      <entry key="json" value="application/json"/>
      <entry key="xml" value="application/xml" />
    </map>
 </property>
 <property name="defaultViews">
    <list><bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/></list>
 </property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="order" value="2" />
 <property name="prefix" value="/WEB-INF/views/"/>
 <property name="suffix" value=".jsp"/>
</bean>

                                        Spring Framework - MVC   Dmitry Noskov
Additional features
Locales
Themes
File upload
Handling mappings / exceptions




                 Spring Framework - MVC   Dmitry Noskov
Locales
   LocaleResolver
       AcceptHeaderLocaleResolver
       CookieLocaleResolver
       SessionLocaleResolver
   LocaleChangeInterceptor
<bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang"/>
</bean>


http://localhost:8080/carbase/?lang=ru


                                         Spring Framework - MVC   Dmitry Noskov
Themes
   ThemeSource
       ResourceBundleThemeSource
   ThemeResolver
     FixedThemeResolver
     SessionThemeResolver

     CookieThemeResolver




                          Spring Framework - MVC   Dmitry Noskov
File upload
   MultipartResolver
<bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">


    <!-- one of the properties; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>



   MultipartFile
@RequestMapping(method = RequestMethod.POST)
public String upload (@RequestParam("file") MultipartFile file) {
}


                                   Spring Framework - MVC   Dmitry Noskov
Handling mappings
   interceptors
   default handler
   order
   lazy init handlers

<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
      <bean class="myInterceptor"/>
    </property>
</bean>

                                      Spring Framework - MVC   Dmitry Noskov
Handler interceptors

public interface HandlerInterceptor {


    /** Called before HandlerAdapter invokes the handler.
    * @return true if the execution chain should proceed */
    boolean preHandle(Request, Response, Handler) {}


    /** Called after HandlerAdapter actually invoked the handler,
    * but before the DispatcherServlet renders the view.*/
    void postHandle(Request, Response, Handler, ModelAndView) {}


    /** Callback after rendering the view. */
    void afterCompletion(Request, Response, Handler, Exception) {}
}


                              Spring Framework - MVC   Dmitry Noskov
Handling Exceptions
   application
       HandlingExeptionResolver
   controller
       @ExceptionHandler(Exception.class)
        public String handleException(Exception e) {
            return ClassUtils.getShortName(e.getClass());
        }

   method
       try {} catch (Exception e) {}


                            Spring Framework - MVC   Dmitry Noskov
Magic tags
<mvc:annotation-driven>
<mvc:interceptors>
<mvc:view-controller>
<mvc:resources>
<mvc:default-servlet-handler>


             Spring Framework - MVC   Dmitry Noskov
mvc:annotation-driven
   registers necessary beans
   support formatting
     Number fields using the @NumberFormat
     Date, Calendar, Long fields using the @DateTimeFormat

   support for reading and writing
     XML, if JAXB is present in classpath
     JSON, if Jackson is present in classpath

   support validating with @Valid

                           Spring Framework - MVC   Dmitry Noskov
mvc:interceptors

<!-- register "global" interceptor beans to apply to all
registered HandlerMappings -->
<mvc:interceptors>


 <!–- applied to all URL paths -->
 <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>


 <!–- applied to a specific URL path -->
 <mvc:interceptor>
   <mvc:mapping path="/secure/*"/>
   <bean class="org.example.MyInterceptor" />
 </mvc:interceptor>
</mvc:interceptors>


                                Spring Framework - MVC   Dmitry Noskov
mvc:view-controller
   immediately forwards to a view when invoked

    <mvc:view-controller path="/" view-name="index"/>


    <mvc:view-controller path="/resourceNotFound"/>




                              Spring Framework - MVC   Dmitry Noskov
mvc:resources


<!-- Handles HTTP GET requests for /resources/** by efficiently
serving up static resources -->
<mvc:resources location="/, classpath:/META-INF/web-resources/"
                 mapping="/resources/**"/>




   http://static.springsource.org/spring/docs/3.0.x/spring-framework-
    reference/html/mvc.html#mvc-static-resources

                               Spring Framework - MVC   Dmitry Noskov
mvc:default-servlet-handler


<!-- Allows for mapping the DispatcherServlet to "/" by
forwarding static resource requests to the container's default
Servlet -->
<mvc:default-servlet-handler/>




                            Spring Framework - MVC   Dmitry Noskov
Ajax




       Spring Framework - MVC   Dmitry Noskov
Getting JSON
   server
@RequestMapping(value="/availability", method=RequestMethod.GET)
public @ResponseBody AvailabilityStatus
                          getAvailability(@RequestParam String name) {
    return AvailabilityStatus.AVAILABLE;
}

   client
function checkAvailability() {
    $.getJSON("account/availability", {name: $('#name').val()},
         function(availability) {}
    );
}


                                 Spring Framework - MVC   Dmitry Noskov
Post JSON
   client
$("#account").submit(function() {
    var account = $(this).serializeObject();
    $.postJSON("account", account, function(data) {
      $("#assignedId").val(data.id);
    });
    return false;
});

   server
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object>
                                 create(@RequestBody Account account) {
    return Collections.singletonMap("id", account.getId());
}

                                Spring Framework - MVC   Dmitry Noskov
Spring Framework - MVC   Dmitry Noskov
Features
   clear separation of roles
   reusable business code
   flexible model transfer
   customizable binding and validation
   customizable handler mapping and view resolution
   pluggability




                        Spring Framework - MVC   Dmitry Noskov
Spring MVC
   lightweight web framework
   controller is a Spring bean




                         Spring Framework - MVC   Dmitry Noskov
Information
   reference
       http://www.springsource.org/documentation
   samples
       https://src.springsource.org/svn/spring-samples/
   blog
       http://blog.springsource.com/category/web/
   forum
       http://forum.springsource.org/forumdisplay.php?f=25




                                   Spring Framework - MVC   Dmitry Noskov
Questions




            Spring Framework - MVC   Dmitry Noskov
The end




             http://www.linkedin.com/in/noskovd

      http://www.slideshare.net/analizator/presentations

More Related Content

What's hot

Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
React workshop presentation
React workshop presentationReact workshop presentation
React workshop presentationBojan Golubović
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 

What's hot (20)

Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
React & GraphQL
React & GraphQLReact & GraphQL
React & GraphQL
 
React workshop presentation
React workshop presentationReact workshop presentation
React workshop presentation
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring boot
Spring bootSpring boot
Spring boot
 

Similar to Spring Framework - MVC

Spring-training-in-bangalore
Spring-training-in-bangaloreSpring-training-in-bangalore
Spring-training-in-bangaloreTIB Academy
 
Build your web app with asp.net mvc 2 from scratch
Build your web app with asp.net mvc 2 from scratchBuild your web app with asp.net mvc 2 from scratch
Build your web app with asp.net mvc 2 from scratchChalermpon Areepong
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoasZeid Hassan
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web FlowDzmitry Naskou
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Creating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsCreating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsDeepak Chandani
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17GreeceJS
 
Jlook web ui framework
Jlook web ui frameworkJlook web ui framework
Jlook web ui frameworkHongSeong Jeon
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introductionTomi Juhola
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...OdessaJS Conf
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?Tomasz Bak
 

Similar to Spring Framework - MVC (20)

Spring-training-in-bangalore
Spring-training-in-bangaloreSpring-training-in-bangalore
Spring-training-in-bangalore
 
Build your web app with asp.net mvc 2 from scratch
Build your web app with asp.net mvc 2 from scratchBuild your web app with asp.net mvc 2 from scratch
Build your web app with asp.net mvc 2 from scratch
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web Flow
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Day7
Day7Day7
Day7
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Creating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsCreating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 Components
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
 
Google Polymer Framework
Google Polymer FrameworkGoogle Polymer Framework
Google Polymer Framework
 
Jlook web ui framework
Jlook web ui frameworkJlook web ui framework
Jlook web ui framework
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
Servlet 3.0
Servlet 3.0Servlet 3.0
Servlet 3.0
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
 

Recently uploaded

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 

Recently uploaded (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 

Spring Framework - MVC

  • 1. Spring Framework - MVC SPRING FRAMEWORK 3.0 Dmitry Noskov Spring MVC
  • 2. The Spring WEB stack Spring Framework - MVC Dmitry Noskov
  • 3. MVC Spring Framework - MVC Dmitry Noskov
  • 4. Web frameworks  request-based  Struts, Spring MVC  component-based  JSF, GWT, Wicket  RIA  Flex Spring Framework - MVC Dmitry Noskov
  • 5. What is Spring MVC?  web component of Spring Framework  request based web framework Spring Framework - MVC Dmitry Noskov
  • 6. Request processing workflow Spring Framework - MVC Dmitry Noskov
  • 7. Front controller <servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/web-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping> Spring Framework - MVC Dmitry Noskov
  • 8. Application context <web-app version="2.5"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/root-context.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Spring Framework - MVC Dmitry Noskov
  • 9. Context Spring Framework - MVC Dmitry Noskov
  • 10. UrlRewrite http://www.tuckey.org/urlrewrite/ <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Spring Framework - MVC Dmitry Noskov
  • 11. Mapping <urlrewrite default-match-type="wildcard"> <rule> <from>/</from> <to>/app/welcome</to> </rule> <rule> <from>/**</from> <to>/app/$1</to> </rule> <outbound-rule> <from>/app/**</from> <to>/$1</to> </outbound-rule> </urlrewrite> Spring Framework - MVC Dmitry Noskov
  • 12. WebApplicationContextUtils(1) public class ExchangerServlet extends HttpServlet { private AccountService accountService; @Override public void init() throws ServletException { ServletContext sc = super.getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc); accountService = context.getBean(AccountService.class); } } Spring Framework - MVC Dmitry Noskov
  • 13. WebApplicationContextUtils(2) public class ExchangerFilter implements Filter { private AccountService accountService; @Override public void init(FilterConfig config) throws ServletException { ServletContext sc = config.getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc); accountService = context.getBean(AccountService.class); } } Spring Framework - MVC Dmitry Noskov
  • 15. Mapping requests  by path @RequestMapping("/welcome")  by HTTP method @RequestMapping(value = "/welcome", method=RequestMethod.GET)  by presence / value of query parameter @RequestMapping(params = {"find=ByMake", "form" })  by presence / value of request header @RequestMapping(value = "/welcome", headers="accept=text/*") Spring Framework - MVC Dmitry Noskov
  • 16. Simple Controller @Controller public class WelcomeController { @RequestMapping("/welcome") public void welcome() { } } Spring Framework - MVC Dmitry Noskov
  • 17. Use case controller @Controller public class CarController { @RequestMapping("/showcar.do") public String show(@RequestParam("id") id, Model model) { model.addAttribute("car", Car.findCar(id)); return "jsp/cars/car.jsp"; } @RequestMapping("/carlist.do") public String list(Model model) { /** such business logic*/} /** such method handlers*/ } Spring Framework - MVC Dmitry Noskov
  • 18. Unfriendly URLs direct command URL: http://localhost:8080/carbase/showcar.do?id=77 for each item not very cacheable and search engine friendly Spring Framework - MVC Dmitry Noskov
  • 19. REST  Representation State Transfer  style of software architecture  RPC is antipode  http://en.wikipedia.org/wiki/Representational_State_Transfer Spring Framework - MVC Dmitry Noskov
  • 20. Http methods  get  post  when the resource URL is unknown (create item)  put  when the resource URL is known (update item)  delete  post vs put  http://stackoverflow.com/questions/630453/put-vs-post-in-rest Spring Framework - MVC Dmitry Noskov
  • 21. RESTful mapping Resource GET PUT POST DELETE http://domain.com/cars obtain list of item update create X http://domain.com/cars/7 obtain item X X delete http://domain.com/cars?form create empty form X X X http://domain.com/cars/7?form pre-populated form X X X Spring Framework - MVC Dmitry Noskov
  • 22. RESTful URLs URL: http://localhost:8080/carbase/cars/11 Spring Framework - MVC Dmitry Noskov
  • 23. Typical actions  simple list page  filtered list page  CRUD:  create  read (retrieve)  update  delete  workflow  submit / approve / etc. Spring Framework - MVC Dmitry Noskov
  • 24. List page URL: http://localhost:8080/carbase/cars @Controller @RequestMapping("/cars") public class CarController { @RequestMapping(method = RequestMethod.GET) public String list(Model model) { model.addAttribute("cars", Car.findAllCars()); return "cars/list"; } } Spring Framework - MVC Dmitry Noskov
  • 25. Detailed page URL: http://localhost:8080/carbase/cars/11 @Controller @RequestMapping("/cars") public class CarController { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public String show(@PathVariable("id") Long id, Model model) { model.addAttribute("car", Car.findCar(id)); return "cars/show"; } } Spring Framework - MVC Dmitry Noskov
  • 26. Create URL: http://localhost:8080/carbase/cars @Controller @RequestMapping("/cars") public class CarController { @RequestMapping(method = RequestMethod.POST) public String create(Car car) { car.persist(); return "redirect:/cars/" + car.getId(); } } Spring Framework - MVC Dmitry Noskov
  • 27. Update URL: http://localhost:8080/carbase/cars/ @Controller @RequestMapping("/cars") public class CarController { @RequestMapping(method = RequestMethod.PUT) public String update(@Valid Car car, BindingResult result) { /** Spring Validator*/ //result.hasErrors(); car.merge(); return "redirect:/cars/" + car.getId(); } } Spring Framework - MVC Dmitry Noskov
  • 28. Delete URL: http://localhost:8080/carbase/cars/11 @Controller @RequestMapping("/cars") public class CarController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String delete(@PathVariable("id") Long id) { Car.findCar(id).remove(); return "redirect:/cars; } } Spring Framework - MVC Dmitry Noskov
  • 29. Filtered page URL: http://localhost:8080/carbase/cars @Controller @RequestMapping("/cars") public class CarController { @RequestMapping(params="find=ByMake", method=RequestMethod.GET) public String findByMake(@RequestParam("make")Make make, Model m) { m.addAttribute("cars", Car.findCarsByMake(make).getResultList()); return "cars/list"; } } Spring Framework - MVC Dmitry Noskov
  • 30. Delete and put through post  Spring tag <form:form action="/carbase/cars" method="PUT">  html <form id="car" action="/carbase/cars" method="post"> <input type="hidden" name="_method" value="PUT"/>  server side <filter> <filter-name>HttpMethodFilter</filter-name> <filter-class> org.springframework.web.filter.HiddenHttpMethodFilter </filter-class> </filter> Spring Framework - MVC Dmitry Noskov
  • 31. Handler arguments  HttpSession / HttpServletRequest / etc.  Spring’s WebRequest / NativeWebRequest  path variable  java.io.InputStream / java.io.OutputStream  request’s param / header / body / cookies  command objects  http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-ann-requestmapping-arguments Spring Framework - MVC Dmitry Noskov
  • 32. Return types  ModelAndView  Model / Map / ModelMap  View  String / void  @ResponseBody / @ModelAttribute  http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-ann-requestmapping-arguments Spring Framework - MVC Dmitry Noskov
  • 34. ModelAttribute  maps a model attribute to the specific parameter @RequestMapping(method = RequestMethod.POST) public String create(@ModelAttribute("car") Car car) {}  provide reference data for the model @ModelAttribute("makes") public Collection<Make> populateMakes() { return Make.findAllMakes(); } Spring Framework - MVC Dmitry Noskov
  • 35. SessionAttributes  list the names or types of model attributes which should be stored in the session @Controller @SessionAttributes("car")//@SessionAttributes(value={}, types={}) public class CarController { public String updateForm(@PathVariable("id") Long id, Model model) { m.addAttribute("car", Car.findCar(id)); } public String update(Car request, SessionStatus status) { status.setComplete(); } } Spring Framework - MVC Dmitry Noskov
  • 36. RequestHeader  typical request header host = localhost:8080 user-agent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729; .NET4.0E) accept = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language = en-us,en;q=0.5  obtain request header @RequestMapping("/welcome") public void welcome(@RequestHeader("user-agent") String agent) {}  narrow mappings @RequestMapping(value = "/welcome", headers="accept=text/*") public void welcome() {} Spring Framework - MVC Dmitry Noskov
  • 37. CookieValue  get the JSESSIONID of the cookie @RequestMapping(value = "/welcome") public void welcome(@CookieValue("JSESSIONID") String session){ } Spring Framework - MVC Dmitry Noskov
  • 38. Data Representation Spring Framework - MVC Dmitry Noskov
  • 39. Approach  template view  ViewResolver, View  HTML, Excel, PDF, etc.  data view  HttpMessageConverter  XML, JSON, etc. Spring Framework - MVC Dmitry Noskov
  • 40. View resolver  XmlViewResolver  ResourceBundleViewResolver  UrlBasedViewResolver  InternalResourceViewResolver  BeanNameViewResolver  ContentNegotiatingViewResolver  http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-viewresolver-resolver Spring Framework - MVC Dmitry Noskov
  • 41. View  JSP & JSTL  Tiles  Velocity  FreeMarker  etc.  prefix  redirect:  forward: Spring Framework - MVC Dmitry Noskov
  • 42. ResourceBundleViewResolver  configuration <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="view"/> </bean>  view.properties welcome.(class)=org.springframework.web.servlet.view.JstlView welcome.url=/WEB-INF/jsp/welcome.jsp cars.(class)=org.springframework.web.servlet.view.JstlView cars.url=/WEB-INF/jsp/cars.jsp  controller @Controller return "cars" Spring Framework - MVC Dmitry Noskov
  • 43. UrlBasedViewResolver <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>  use case If @Controller return "cars/show" view class will process "/WEB-INF/jsp/cars/show.jsp" Spring Framework - MVC Dmitry Noskov
  • 44. Tiles(1)  configuration <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/> </bean> <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/layouts/layouts.xml</value> <value>/WEB-INF/**/views.xml</value> </list> </property> </bean>  views.xml <definition extends="default" name="cars/show"></definition> Spring Framework - MVC Dmitry Noskov
  • 45. Tiles(2) <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/layouts/layouts.xml</value> <value>/WEB-INF/**/views.xml</value> </list> </property> <property name="preparerFactoryClass"> <value> org.springframework.web.servlet.view.tiles2. SpringBeanPreparerFactory </value> </property> </bean> Spring Framework - MVC Dmitry Noskov
  • 46. HttpMessageConverter  reads the request body and writes the response  converters mapped to content types  http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/remoting.html#rest-message-conversion  registered by default if jar present in classpath  Jackson, JAXB, Atom, RSS Spring Framework - MVC Dmitry Noskov
  • 47. ContentNegotiatingViewResolver Spring Framework - MVC Dmitry Noskov
  • 48. Strategies  URI  www.domain.com/cars.html  www.domain.com/cars.json  content negotiation  Accept: text/html…  Accept: text/xml…  Accept: application/pdf… Spring Framework - MVC Dmitry Noskov
  • 49. Example(1) <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="atom" value="application/atom+xml"/> <entry key="html" value="text/html"/> <entry key="json" value="application/json"/> </map> </property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/> </list> </property> <property name="defaultViews"> <list><bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/></list> </property> </bean> Spring Framework - MVC Dmitry Noskov
  • 50. Example(2) <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml" /> </map> </property> <property name="defaultViews"> <list><bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/></list> </property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="order" value="2" /> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> Spring Framework - MVC Dmitry Noskov
  • 51. Additional features Locales Themes File upload Handling mappings / exceptions Spring Framework - MVC Dmitry Noskov
  • 52. Locales  LocaleResolver  AcceptHeaderLocaleResolver  CookieLocaleResolver  SessionLocaleResolver  LocaleChangeInterceptor <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang"/> </bean> http://localhost:8080/carbase/?lang=ru Spring Framework - MVC Dmitry Noskov
  • 53. Themes  ThemeSource  ResourceBundleThemeSource  ThemeResolver  FixedThemeResolver  SessionThemeResolver  CookieThemeResolver Spring Framework - MVC Dmitry Noskov
  • 54. File upload  MultipartResolver <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties; the maximum file size in bytes --> <property name="maxUploadSize" value="100000"/> </bean>  MultipartFile @RequestMapping(method = RequestMethod.POST) public String upload (@RequestParam("file") MultipartFile file) { } Spring Framework - MVC Dmitry Noskov
  • 55. Handling mappings  interceptors  default handler  order  lazy init handlers <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <bean class="myInterceptor"/> </property> </bean> Spring Framework - MVC Dmitry Noskov
  • 56. Handler interceptors public interface HandlerInterceptor { /** Called before HandlerAdapter invokes the handler. * @return true if the execution chain should proceed */ boolean preHandle(Request, Response, Handler) {} /** Called after HandlerAdapter actually invoked the handler, * but before the DispatcherServlet renders the view.*/ void postHandle(Request, Response, Handler, ModelAndView) {} /** Callback after rendering the view. */ void afterCompletion(Request, Response, Handler, Exception) {} } Spring Framework - MVC Dmitry Noskov
  • 57. Handling Exceptions  application  HandlingExeptionResolver  controller  @ExceptionHandler(Exception.class) public String handleException(Exception e) { return ClassUtils.getShortName(e.getClass()); }  method  try {} catch (Exception e) {} Spring Framework - MVC Dmitry Noskov
  • 59. mvc:annotation-driven  registers necessary beans  support formatting  Number fields using the @NumberFormat  Date, Calendar, Long fields using the @DateTimeFormat  support for reading and writing  XML, if JAXB is present in classpath  JSON, if Jackson is present in classpath  support validating with @Valid Spring Framework - MVC Dmitry Noskov
  • 60. mvc:interceptors <!-- register "global" interceptor beans to apply to all registered HandlerMappings --> <mvc:interceptors> <!–- applied to all URL paths --> <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/> <!–- applied to a specific URL path --> <mvc:interceptor> <mvc:mapping path="/secure/*"/> <bean class="org.example.MyInterceptor" /> </mvc:interceptor> </mvc:interceptors> Spring Framework - MVC Dmitry Noskov
  • 61. mvc:view-controller  immediately forwards to a view when invoked <mvc:view-controller path="/" view-name="index"/> <mvc:view-controller path="/resourceNotFound"/> Spring Framework - MVC Dmitry Noskov
  • 62. mvc:resources <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources --> <mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>  http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-static-resources Spring Framework - MVC Dmitry Noskov
  • 63. mvc:default-servlet-handler <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource requests to the container's default Servlet --> <mvc:default-servlet-handler/> Spring Framework - MVC Dmitry Noskov
  • 64. Ajax Spring Framework - MVC Dmitry Noskov
  • 65. Getting JSON  server @RequestMapping(value="/availability", method=RequestMethod.GET) public @ResponseBody AvailabilityStatus getAvailability(@RequestParam String name) { return AvailabilityStatus.AVAILABLE; }  client function checkAvailability() { $.getJSON("account/availability", {name: $('#name').val()}, function(availability) {} ); } Spring Framework - MVC Dmitry Noskov
  • 66. Post JSON  client $("#account").submit(function() { var account = $(this).serializeObject(); $.postJSON("account", account, function(data) { $("#assignedId").val(data.id); }); return false; });  server @RequestMapping(method=RequestMethod.POST) public @ResponseBody Map<String, ? extends Object> create(@RequestBody Account account) { return Collections.singletonMap("id", account.getId()); } Spring Framework - MVC Dmitry Noskov
  • 67. Spring Framework - MVC Dmitry Noskov
  • 68. Features  clear separation of roles  reusable business code  flexible model transfer  customizable binding and validation  customizable handler mapping and view resolution  pluggability Spring Framework - MVC Dmitry Noskov
  • 69. Spring MVC  lightweight web framework  controller is a Spring bean Spring Framework - MVC Dmitry Noskov
  • 70. Information  reference  http://www.springsource.org/documentation  samples  https://src.springsource.org/svn/spring-samples/  blog  http://blog.springsource.com/category/web/  forum  http://forum.springsource.org/forumdisplay.php?f=25 Spring Framework - MVC Dmitry Noskov
  • 71. Questions Spring Framework - MVC Dmitry Noskov
  • 72. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations