SlideShare una empresa de Scribd logo
1 de 44
Spring Web
MVC
By: Zeeshan Hanif
Sr. Software Engineer
Etilize Pvt. Ltd.
A GfK Product data company
Agenda
 What is spring MVC
 Features
 Spring MVC Workflow
 Important Components of Spring MVC
 Demo – External configuration
 Demo – Annotation
 Convention over Configuration
 World without Rules
 Demo – Form Submission
 Demo – Session Storage
 Demo – REST based URL
 Demo – Ajax
Prerequisite
 Spring Core
 IOC & Dependency Injection
Source: www.springsource.org
Spring MVC
 The Spring Web MVC Framework is a
robust, flexible, and well-designed
framework for rapidly developing web
applications using the MVC design
pattern.
Features
 Clear separation of roles. Each role —
controller, validator, command object,
form object, model object, handler
mapping, view resolver and so on.
 Powerful and straightforward
configuration of both framework and
application classes as JavaBeans
 Adaptability and flexibility. Define any
controller method signature you need for
a given scenario
Features (cont.)
 Use existing business objects as command
or form objects instead of mirroring them
to extend a particular framework base
class
 Flexible model transfer. Model transfer
with a name/value Map supports easy
integration with any view technology
 A simple yet powerful JSP tag library
 Easier testing
 REST based URL support
Spring MVC Workflow
Source: www.springsource.org
Important Components
 DispatcherServlet
 Controller
 HandlerMapping/@RequestMapping
 ModelAndView
 Model & @ModelAttribute
 ViewResolver
DispatcherServlet
 The Dispatcher Servlet follows the Front
Controller Design Pattern for handling
Client Requests.
 It means that whatever Url comes from
the Client, this Servlet will intercept the
Client Request before passing the
Request Object to the Controller.
DispatcherServlet (cont.)
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.gfk</url-pattern>
</servlet-mapping>
</web-app>
Controller
 Controllers are components that are
being called by the Dispatcher Servlet for
doing any kind of Business Logic
 Spring Distribution already comes with a
variety of Controller Components each
doing a specific purpose - spring 2.x
 SimpleFormController
 AbstractController
 MultiActionController
 Spring 3 Controller
 @Controller Annotation
Controller (Cont.)
 Old School of Spring MVC
public class MySimpleController extends AbstractController
{
public ModelAndView handleRequestInternal
(HttpServletRequest request,
HttpServletResponse response)
{
return new ModelAndView("myView");
}
}
Controller (Cont.)
 Spring MVC 3.0
@Controller
public class DemoSpring3Controller {
@RequestMapping("/demoSpring3")
public ModelAndView helloWorld() {
String msg = "Hello Spring 3 World! Etilize -- GfK";
return new ModelAndView("demosp",
"message", msg);
}
}
<context:component-scan base-package="com.gfk.etilize.controller" />
HandlerMapping
 A Handler Mapping provides an abstract
way that tell how the Client's Url has to be
mapped to the Handlers.
 Four concrete variation of Handler
Mapping are available
 BeanNameUrl HandlerMapping
 CommonsPathMap HandlerMapping
 ControllerClassName HandlerMapping
 SimpleUrl HandlerMapping
HandlerMapping (Cont.)
 BeanNameUrl HandlerMapping
 URL request
http://localhost:8080/spweb/showStudents
 Bean Mapping
<beans>
<bean id="beanNameUrl"
class="org.springframework.web.servlet.handler.
BeanNameUrlHandlerMapping"/>
<bean name="/showStudents.jsp"
class="com.gfk.etilize.ShowStudentsController">
</bean>
</beans>
HandlerMapping (Cont.)
 SimpleUrlHandlerMapping
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHan
dlerMapping">
<property name="urlMap">
<map>
<entry key="/demoSpring.gfk">
<ref bean="demoSpringController"/>
</entry>
</map>
</property>
</bean>
<bean id="demoSpringController"
class="com.gfk.etilize.controller.DemoSpringController" />
HandlerMapping (Cont.)
 Spring 3.0 uses @RequestMapping for
Mapping
@Controller
public class DemoSpring3Controller {
@RequestMapping("/demoSpring3")
public ModelAndView helloWorld() {
String msg = "Hello Spring 3 World";
return new ModelAndView("demosp",
"message", msg);
}
}
ModelAndView
 ModelandView is returned by the
Controller object back to the Dispatcher
Servlet.
 This class is just a Container class for
holding the Model and the View
information.
 This way of specifying a View is called a
Logical View. It means that demosp either
can point to something called demosp.jsp
or demosp.pdf or demosp.xml
ModelAndView(viewName, “Key”, object);
return new ModelAndView("demosp", "message", msg);
Model & @ModelAttribute
 Model object Automatically created on
every request
@RequestMapping
public void showList(Model model){
model.addAttribute("studentList",
studentService.getAllStudents());
}
Implicitly added to Model and can be accessed with key
“student”
@RequestMapping
public Student showList(){
return studentService.getStudent();
}
Model & @ModelAttribute
@ModelAttribute – customized name
@RequestMapping
public @ModelAttribute(“stu”) Student showList(){
return studentService.getStudent();
}
@ModelAttribute – Form values
@RequestMapping("/new")
public ModelAndView getStudentForm(){
return new ModelAndView("studentForm","student",new Student());
}
<form:form action="add.gfk" method="POST" commandName=" student " >
Name:<form:input path="name" size="60" /><br>
<input type="submit" value="Register" /></td>
</form:form>
@RequestMapping
public void saveStudent(@ModelAttribute Student stu){
studentService.saveStudent(stu);
}
View Resolver
 The mapping between the Logical name
and the Physical View Location is taken
care by the View Resolver object.
 Spring comes with a set of Built-In Spring
Resolvers.
 We can write Custom View Resolvers by
implementing the
org.springframework.web.servlet.ViewResolver
interface
View Resolver (Cont.)
 BeanNameViewResolver
 FreeMarkerViewResolver
 InternalResourceViewResolver
 JasperReportsViewResolver
 ResourceBundleViewResolver
 UrlBasedViewResolver
 VelocityLayoutViewResolver
 VelocityViewResolver
 XmlViewResolver
 XsltViewResolver
View Resolver (Cont.)
 InternalResourceViewResolver
Controller returns - new ModelAndView("myView1")
<bean id="viewResolver“
class="org.springframework.web.servlet.view.InternalResourceVie
wResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
the prefix + the logical View Name + the suffix
/WEB-INF/myView.jsp
View Resolver (Cont.)
 BeanNameViewResolver
 One of the dis-advantage of
using InternalResourceViewResolver is that
the name of the View file (jsp or pdf) must
be present in the Web Application Context.
 Dynamically generated View files may not
be possible.
 In such a case, we may use the BeanName
ViewResolver which will dynamically
generate View in Pdf or Excel Formats.
View Resolver (Cont.)
Controller returns - new ModelAndView(“excel")
<bean id="beanNameResolver"
class="org.springframework.web.servlet.view.BeanNameViewReso
lver"/>
<bean id = “excel" class = "MyExcelGenerator"/>
Demo – External configuration
Demo – Annotation
Convention over Configuration
 Write less code, get consistency
 Conventions available for
 Request mapping
 View name selection
 Model population
Convention over Configuration
 Mapping By RequestMapping
@Controller
public class DemoSpring3Controller {
@RequestMapping("/demoSpring3")
public void helloWorld(){}
}
Convention over Configuration
@Controller
public class StudentController {
@RequestMapping
public void listAll(Model model){
model.addAttribute(new Student("Test",23));
}
}
GET /student/listAll
Mapping of class and
method name
View with method name
selected from request path
Model key generated from object type
Convention over Configuration
 Mapping By Convention
@Controller
public class StudentController {
URL  /student/showList , View  showList.jsp
@RequestMapping
public void showList(Model model){}
URL  /student/getStudent, View  getStudent.jsp
@RequestMapping
public Student getStudent(){
…
return stu;
}
}
World without Rules
 Return Type?
 Return Type Can be:
 ModelAndViewObject
 Model
 Map
 View
 String
 Void
 Any Custom or built-in datatype
 e.g. Student, Student[],ArrayList etc.
World without Rules (Cont.)
 Parameter Type?
 Parameter can be in any order:
 ServletRequest/HttpServletRequest
 ServletResponse/HttpServletResponse
 HttpSession
 InputStream/java.io.Reader
 OutputStream/java.io.Writer
 @RequestParam("product") int id or any type
 @PathVariable String name or any type
 @CookieValue("cookie_name") String or any type
 @RequestHeader("content") String or any type
 @ModelAttribute User us or any custom object
 Errors
 BindingResult
 SessionStatus
Demo – Form Submission
@RequestParam
 Type Conversion
@RequestMapping("/login")
public void login(@RequestParam String userName,
@RequestParam int age){
}
 Optional Request parameter -- must use
object for optional
@RequestMapping("/login")
public void login(@RequestParam(required=false) String
userName){
}
Demo – @RequestParam
@SessionAttribute
@Controller
@SessionAttributes("user")
public class LoginController {
@RequestMapping("/login")
public User login(@RequestParam int id){
return loginService.login(id);
}
}
User Object will be stored in session with key “user”
Demo – @SessionAttribute
@PathVariable – REST URLs
 GET /students/find/5
@RequestMapping(“/find/{id}")
public ModelAndView findStudent(@PathVariable int id ,
Model model){
model.addAttribute("stu", studentService.getStudent(id));
return new ModelAndView("searchStudent");
}
Demo – @PathVariable – REST URLs
Demo – Ajax
 @ResponseBody annotation instructs
Spring MVC to serialize the Student to the
client.
 Spring MVC automatically serializes to
JSON because the client accepts that
content type
@RequestMapping(value="/student")
public @ResponseBody Student getStudent(
@RequestParam int id) {
return studentService.getStudent(id);
}
Q & A
 Source Code
http://www.4shared.com/zip/sHRtnXXd/De
moSpringMVC.html
 You can find this presentation on
slideshare
http://www.slideshare.net/zeeshanhanif
Contact
zeeshanhanif@gmail.com
http://www.linkedin.com/in/zeeshanhanif
http://www.facebook.com/zeeshanhanif

Más contenido relacionado

La actualidad más candente

Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
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
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 

La actualidad más candente (20)

Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
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
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring boot
Spring bootSpring boot
Spring boot
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 

Similar a Spring Web 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 topicsGuy Nir
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actionsonsela
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Build your website with angularjs and web apis
Build your website with angularjs and web apisBuild your website with angularjs and web apis
Build your website with angularjs and web apisChalermpon Areepong
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs WorkshopRan Wahle
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
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
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3Ilio Catallo
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4soelinn
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 

Similar a Spring Web MVC (20)

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
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Build your website with angularjs and web apis
Build your website with angularjs and web apisBuild your website with angularjs and web apis
Build your website with angularjs and web apis
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 

Último

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Spring Web MVC

  • 1. Spring Web MVC By: Zeeshan Hanif Sr. Software Engineer Etilize Pvt. Ltd. A GfK Product data company
  • 2. Agenda  What is spring MVC  Features  Spring MVC Workflow  Important Components of Spring MVC  Demo – External configuration  Demo – Annotation  Convention over Configuration  World without Rules  Demo – Form Submission  Demo – Session Storage  Demo – REST based URL  Demo – Ajax
  • 3. Prerequisite  Spring Core  IOC & Dependency Injection
  • 5. Spring MVC  The Spring Web MVC Framework is a robust, flexible, and well-designed framework for rapidly developing web applications using the MVC design pattern.
  • 6. Features  Clear separation of roles. Each role — controller, validator, command object, form object, model object, handler mapping, view resolver and so on.  Powerful and straightforward configuration of both framework and application classes as JavaBeans  Adaptability and flexibility. Define any controller method signature you need for a given scenario
  • 7. Features (cont.)  Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class  Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view technology  A simple yet powerful JSP tag library  Easier testing  REST based URL support
  • 8. Spring MVC Workflow Source: www.springsource.org
  • 9. Important Components  DispatcherServlet  Controller  HandlerMapping/@RequestMapping  ModelAndView  Model & @ModelAttribute  ViewResolver
  • 10. DispatcherServlet  The Dispatcher Servlet follows the Front Controller Design Pattern for handling Client Requests.  It means that whatever Url comes from the Client, this Servlet will intercept the Client Request before passing the Request Object to the Controller.
  • 12. Controller  Controllers are components that are being called by the Dispatcher Servlet for doing any kind of Business Logic  Spring Distribution already comes with a variety of Controller Components each doing a specific purpose - spring 2.x  SimpleFormController  AbstractController  MultiActionController  Spring 3 Controller  @Controller Annotation
  • 13. Controller (Cont.)  Old School of Spring MVC public class MySimpleController extends AbstractController { public ModelAndView handleRequestInternal (HttpServletRequest request, HttpServletResponse response) { return new ModelAndView("myView"); } }
  • 14. Controller (Cont.)  Spring MVC 3.0 @Controller public class DemoSpring3Controller { @RequestMapping("/demoSpring3") public ModelAndView helloWorld() { String msg = "Hello Spring 3 World! Etilize -- GfK"; return new ModelAndView("demosp", "message", msg); } } <context:component-scan base-package="com.gfk.etilize.controller" />
  • 15. HandlerMapping  A Handler Mapping provides an abstract way that tell how the Client's Url has to be mapped to the Handlers.  Four concrete variation of Handler Mapping are available  BeanNameUrl HandlerMapping  CommonsPathMap HandlerMapping  ControllerClassName HandlerMapping  SimpleUrl HandlerMapping
  • 16. HandlerMapping (Cont.)  BeanNameUrl HandlerMapping  URL request http://localhost:8080/spweb/showStudents  Bean Mapping <beans> <bean id="beanNameUrl" class="org.springframework.web.servlet.handler. BeanNameUrlHandlerMapping"/> <bean name="/showStudents.jsp" class="com.gfk.etilize.ShowStudentsController"> </bean> </beans>
  • 17. HandlerMapping (Cont.)  SimpleUrlHandlerMapping <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHan dlerMapping"> <property name="urlMap"> <map> <entry key="/demoSpring.gfk"> <ref bean="demoSpringController"/> </entry> </map> </property> </bean> <bean id="demoSpringController" class="com.gfk.etilize.controller.DemoSpringController" />
  • 18. HandlerMapping (Cont.)  Spring 3.0 uses @RequestMapping for Mapping @Controller public class DemoSpring3Controller { @RequestMapping("/demoSpring3") public ModelAndView helloWorld() { String msg = "Hello Spring 3 World"; return new ModelAndView("demosp", "message", msg); } }
  • 19. ModelAndView  ModelandView is returned by the Controller object back to the Dispatcher Servlet.  This class is just a Container class for holding the Model and the View information.  This way of specifying a View is called a Logical View. It means that demosp either can point to something called demosp.jsp or demosp.pdf or demosp.xml ModelAndView(viewName, “Key”, object); return new ModelAndView("demosp", "message", msg);
  • 20. Model & @ModelAttribute  Model object Automatically created on every request @RequestMapping public void showList(Model model){ model.addAttribute("studentList", studentService.getAllStudents()); } Implicitly added to Model and can be accessed with key “student” @RequestMapping public Student showList(){ return studentService.getStudent(); }
  • 21. Model & @ModelAttribute @ModelAttribute – customized name @RequestMapping public @ModelAttribute(“stu”) Student showList(){ return studentService.getStudent(); } @ModelAttribute – Form values @RequestMapping("/new") public ModelAndView getStudentForm(){ return new ModelAndView("studentForm","student",new Student()); } <form:form action="add.gfk" method="POST" commandName=" student " > Name:<form:input path="name" size="60" /><br> <input type="submit" value="Register" /></td> </form:form> @RequestMapping public void saveStudent(@ModelAttribute Student stu){ studentService.saveStudent(stu); }
  • 22. View Resolver  The mapping between the Logical name and the Physical View Location is taken care by the View Resolver object.  Spring comes with a set of Built-In Spring Resolvers.  We can write Custom View Resolvers by implementing the org.springframework.web.servlet.ViewResolver interface
  • 23. View Resolver (Cont.)  BeanNameViewResolver  FreeMarkerViewResolver  InternalResourceViewResolver  JasperReportsViewResolver  ResourceBundleViewResolver  UrlBasedViewResolver  VelocityLayoutViewResolver  VelocityViewResolver  XmlViewResolver  XsltViewResolver
  • 24. View Resolver (Cont.)  InternalResourceViewResolver Controller returns - new ModelAndView("myView1") <bean id="viewResolver“ class="org.springframework.web.servlet.view.InternalResourceVie wResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> the prefix + the logical View Name + the suffix /WEB-INF/myView.jsp
  • 25. View Resolver (Cont.)  BeanNameViewResolver  One of the dis-advantage of using InternalResourceViewResolver is that the name of the View file (jsp or pdf) must be present in the Web Application Context.  Dynamically generated View files may not be possible.  In such a case, we may use the BeanName ViewResolver which will dynamically generate View in Pdf or Excel Formats.
  • 26. View Resolver (Cont.) Controller returns - new ModelAndView(“excel") <bean id="beanNameResolver" class="org.springframework.web.servlet.view.BeanNameViewReso lver"/> <bean id = “excel" class = "MyExcelGenerator"/>
  • 27. Demo – External configuration Demo – Annotation
  • 28. Convention over Configuration  Write less code, get consistency  Conventions available for  Request mapping  View name selection  Model population
  • 29. Convention over Configuration  Mapping By RequestMapping @Controller public class DemoSpring3Controller { @RequestMapping("/demoSpring3") public void helloWorld(){} }
  • 30. Convention over Configuration @Controller public class StudentController { @RequestMapping public void listAll(Model model){ model.addAttribute(new Student("Test",23)); } } GET /student/listAll Mapping of class and method name View with method name selected from request path Model key generated from object type
  • 31. Convention over Configuration  Mapping By Convention @Controller public class StudentController { URL  /student/showList , View  showList.jsp @RequestMapping public void showList(Model model){} URL  /student/getStudent, View  getStudent.jsp @RequestMapping public Student getStudent(){ … return stu; } }
  • 32. World without Rules  Return Type?  Return Type Can be:  ModelAndViewObject  Model  Map  View  String  Void  Any Custom or built-in datatype  e.g. Student, Student[],ArrayList etc.
  • 33. World without Rules (Cont.)  Parameter Type?  Parameter can be in any order:  ServletRequest/HttpServletRequest  ServletResponse/HttpServletResponse  HttpSession  InputStream/java.io.Reader  OutputStream/java.io.Writer  @RequestParam("product") int id or any type  @PathVariable String name or any type  @CookieValue("cookie_name") String or any type  @RequestHeader("content") String or any type  @ModelAttribute User us or any custom object  Errors  BindingResult  SessionStatus
  • 34. Demo – Form Submission
  • 35. @RequestParam  Type Conversion @RequestMapping("/login") public void login(@RequestParam String userName, @RequestParam int age){ }  Optional Request parameter -- must use object for optional @RequestMapping("/login") public void login(@RequestParam(required=false) String userName){ }
  • 37. @SessionAttribute @Controller @SessionAttributes("user") public class LoginController { @RequestMapping("/login") public User login(@RequestParam int id){ return loginService.login(id); } } User Object will be stored in session with key “user”
  • 39. @PathVariable – REST URLs  GET /students/find/5 @RequestMapping(“/find/{id}") public ModelAndView findStudent(@PathVariable int id , Model model){ model.addAttribute("stu", studentService.getStudent(id)); return new ModelAndView("searchStudent"); }
  • 40. Demo – @PathVariable – REST URLs
  • 41. Demo – Ajax  @ResponseBody annotation instructs Spring MVC to serialize the Student to the client.  Spring MVC automatically serializes to JSON because the client accepts that content type @RequestMapping(value="/student") public @ResponseBody Student getStudent( @RequestParam int id) { return studentService.getStudent(id); }
  • 42. Q & A
  • 43.  Source Code http://www.4shared.com/zip/sHRtnXXd/De moSpringMVC.html  You can find this presentation on slideshare http://www.slideshare.net/zeeshanhanif