Sie sind auf Seite 1von 37

Click to edit Master title style

Click to edit Master text styles


Second level

Spring Web MVC


Third level
Fourth level
Fifth level
Trainer: An Tran Hoai Apr 2015
Click to edit Master title style
Notes
This istoaedit
Click training,
MasterNOT a presentation
text styles
Please
Second asklevel
questions
Prerequisites
Third level
BasicJava Fourth level
Installed Eclipse IDE (or other equivalent)
Fifth level
Spring, Servlet, and JSP Trainings
Click
A Noteto About
edit Master title style
Security
The scope
Click of this text
to edit Master training
stylesis limited to teaching you how to use
Spring
SecondMVC level
The way welevel
Third output values in JSPs is insecure they contain XSS
vulnerabilities.
Fourth level
Fifth level
Click to edit Master title style
Objectives
By the
Click endMaster
to edit of thistext
training,
styles you should:
- Have
Seconda general
level understanding of MVC in general and Spring
MVC inThird
particular
level
- Understand how Spring MVC is configured and be able to
Fourth level
add it to any project
- Know how toFifth level a simple controller
create
- Know how to map an incoming request to a controller
Click to
What edit Master title style
is MVC?
Click to edit Master architectural
Well-established text styles pattern for dealing with UI
Model
Secondmanages
level the behavior and data of the application
View renders the model into UI elements
Third level
Controller processes
Fourth level user inputs and generates a response by
operating on model objects
Fifth level
Click to
MVC edit
in a WebMaster title style
Application
Model
Click encapsulates
to edit the application data and in general they
Master text styles
will consistlevel
Second of POJO.
View isThird
responsible
level for rendering the model data and in
general it generates
Fourth level HTML output that the client's browser can
interpret.
Fifth level
Controller is responsible for processing user requests and
building appropriate model and passes it to the view for
rendering.
Click to edit
Benefits Master title style
of MVC
Decoupling viewstext
Click to edit Master and models.
styles
Reduces
Secondthe levelcomplexity of your design.
Makes code
Third more flexible.
level
Makes code more
Fourth maintainable
level
Fifth level
Click to
What edit Master
is Spring MVC?title style
MVCtoWeb
Click Framework.
edit Master text styles
Developed by the Spring team in response to what they felt
Second level
were deficiencies
Third level in frameworks like Struts.
Deeply integrated
Fourth levelwith Spring.
Allows most parts
Fifthto be customized.
level
RESTful functionality (URI templates, Content Negotiation).
Click to edit
Features MasterWeb
of Spring title MVC
style
Clear
Click toseparation of roles.
edit Master text styles
Simple,
Second powerful
level annotation-based configuration
Controllers
Third are
levelconfigured via Spring, which makes them easy
to use with otherlevel
Fourth Spring objects and makes them easy to test
Customizable datalevel
Fifth binding
Flexible view technology
Customizable handler mapping and view resolution
Click to edit Master title style
DispatcherServlet
Click to edit Master text styles
Second level
Third level
Fourth level
Fifth level
Click to Spring
Adding edit Master
MVC title
to astyle
project
Spring
Click MVC
to edit is relatively
Master easy to add to any existing Spring
text styles
project
Second level
When you
Thirdcreate
level a project type Spring
But wellgo through
Fourth level the configuration steps so you know what
is going on Fifth level
3 basic steps
Click 1:
Step toAdd
edit dependencies
Master title style
First, to
Click you
editneed totext
Master add the Spring MVC dependency to your
styles
web POMlevel
Second
Third level
<dependency> Fourth level
<groupId>org.springframework</groupId>
Fifth level
<artifactId>spring-webmvc</artifactId>
</dependency>
Click 2:
Step toConfigure
edit Master title style
web.xml
We need
Click to editto define
Master textthe DispatcherServlet , give it a name
styles
(helloworld
Second levelin this case), and map it to a url pattern (/ in this
case, which is the default servlet)
Third level
<servlet>
Fourth level
<servlet-name>helloworld</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
Fifth level
class>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Click 3:
Step toAdd
edit the
Master title style file
configuration
We need
Click to editto create
Master textastyles
configuration file name [servlet-name]-
servlet.xml,
Second levelwhere [servlet-name] is the name we gave our
servlet in Step
Third level2 (helloworld)
This is a normal
FourthSpring
level configuration file that defines a web
context
Fifth level
We tell it to look for classes in the com.hvn.helloworld
namespace, annotated with @Controller
<context:component-scan base-package="com.hvn.helloworld use-default-
filters="false">
<context:include-filter
expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
Click 3:
Step toContinue
edit Master title style
We also
Click need
to edit Masterto text
tell Spring
styles MVC that we are going to
configure it via annotations:
Second level
Third level
<mvc:annotation-driven />
Fourth level
If you map the DispatcherServlet
Fifth level to the default servlet (we
did), you need to add the following:
<mvc:default-servlet-handler />
Finally, we need to configure a ViewResolver to find our JSPs
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="redirectHttp10Compatible" value="false"/>
</bean>
Click to edit
Hierarchy of Master title style
Contexts
When
Click to we
edit create thestyles
Master text [servlet-name]-servlet.xml file, we are
creating
Secondalevel
new Spring context that is a child of your
application context
Third level
It can resolve beans
Fourth level from the root context, but other contexts
cant resolve beans from it
Fifth level
You can create as many of these as you need (ie, you might
have another one for web services)
You need to make sure you dont redefine beans, though
Click to edit
Hierarchy of Master title style
Contexts
Click to edit Master text styles
Second level a DefaultWebContext
/

Third level
Fourth level
Fifth level
b GWT Context
/*.gwtrpc

c Web Services
/ws/
Click torequest
Simple edit Master title style
mapping
We can
Click doMaster
to edit simple mappings
text styles to static content in the xml
configuration,
Second level which maps /helloworld to /WEB-
INF/views/hello.jsp
Third level
<bean id="helloWorldController"
Fourth level
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName"
Fifth level value="hello" />
</bean>

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order" value="1" />
<property name="urlMap">
<map>
<entry key="/hello" value-ref="helloWorldController" />
</map>
</property>
</bean>
Click1:toConfigure
Lab edit Master title style
a project
Taketoaedit
Click basic project
Master (with no view) created via Eclipse IDE (or
text styles
order)
Second level
Add dependencies,
Third level web.xml config, and servlet config
Add a simple request
Fourth level mapping
Verify that it works
Fifth level
Click toController
Simple edit Master title style
For most
Click to editcases,
Masteryoull need to create a controller
text styles
Create
Seconda class
level and annotate it with @Controller
Then, create a method annotated with a @RequestMapping
Third level
Fourth level
package com.hvn.helloworld;
Fifth level
@Controller
public class HelloWorldController {

@RequestMapping(value="/")
public String hello() {
return hello;
}
}
Click to editRequest
Advanced Master title style
Mapping
RequestMappings
Click to edit Master textare really flexible
styles
You can define
Second level a @RequestMapping on a class and all
method @RequestMappings
Third level will be relative to it.
There are a number
Fourth level of ways to define them:
URI Patterns Fifth level
HTTP Methods (GET, POST, etc)
Request Parameters
Header values
Click to edit Master title
@RequestMapping style
Class level
Click to edit Master text styles
package com.hvn.helloworld;
Second level
Third level
@RequestMapping("/customer")
@Controller Fourth level
public class CustomerController
Fifth level {

@RequestMapping("/create")
public String create() {
return create";
}
}
Click to edit Master title
@RequestMapping style
HTTP
Methods
Click to edit Master text styles
package com.hvn.hellworld;
Second level
Third level
@RequestMapping("/customer")
@Controller Fourth level
public class CustomerController
Fifth level {

@RequestMapping(value = "/create, method =


RequestMethod.POST)
public String save() {
return view";
}
}
Click to edit Master title
@RequestMapping style
Request
Params
Click to edit Master text styles
package com.hvn.hellworld;
Second level
Third level
@RequestMapping("/customer")
@Controller Fourth level
public class CustomerController
Fifth level {

@RequestMapping(value = "/view, params=details=all)


public String viewAll() {
return viewAll";
}
}

This will respond to /customer/view?details=all


Click to edit Master title
@RequestMapping URIstyle
Templates
Click to edit Master text styles
package com.hvn.helloworld;
Second level
Third level
@RequestMapping("/customer/{id}")
@Controller
public class CustomerController
Fourth level {
Fifth level
@RequestMapping("/viewProject/{projectId}")
public String viewProject() {
return "viewProject";
}
}

The url for this (relative to your context root) would be:
/customer/1/viewProject/10
Click2:toCreate
Lab edit Master title style
a controller
Create
Click a simple
to edit Master controller
text styles for /hello
Return
Seconda jsp
level
Experiment with some more advanced request mappings
Third level
Fourth level
Fifth level
Click to edit
Controller MasterArguments
Method title style
Sometimes
Click you need
to edit Master access to the request, session, request
text styles
body, or other
Second level items
If you add
Thirdthem
level as arguments to your controller method,
Spring will pass
Fourththem
level in
@RequestMapping(value="/")
Fifth level
public String getProject(HttpServletRequest request,
HttpSession session,
@RequestParam(projectId) Long projectId,
@RequestHeader("content-type") String contentType) {
return "index";
}
Click to editAnnotations
Supported Master title on
style
params
@PathVariable
Click to edit Master text styles
@RequestParam
Second level
@RequestHeader
Third level
@RequestBody
Fourth level
Fifth level
Click to edit
Method Master title
Arguments style
(Samples)
This gives
Click to edityou access
Master to the request/response and session
text styles
Second level
@RequestMapping(value="/")
ThirdgetProject(HttpServletRequest
public String level request,
HttpServletResponse
Fourth level response,
HttpSession session) {
Fifth level
return "index";
}
Click to edit
Method Master title
Arguments style
(Samples)
This gives
Click to edityou access
Master to request parameters and headers
text styles
Second level
@RequestMapping(value="/")
Third level
public String getProject(
Fourth level
@RequestParam Long projectId,
Fifth level
@RequestHeader("content-type") String contentType) {
return "index";
}
Click to edit
Method Master title
Arguments style
(Samples)
@PathVariable
Click to edit Masterties
textdynamic
styles elements of the URI to method
arguments
Second level
Third level
@RequestMapping(value="/project/{portfolioId}/{projectId}")
public String getProject(
Fourth level
@PathVariable(projectId) Long id,
Fifth @PathVariable
level Long portfolioId) {
return "index";
}
ClickModel
The to edit Master title style
You to
Click populate thetext
edit Master view with data by via the ModelMap or
styles
ModelAndView
Second level (which has a ModelMap underneath)
This is basically
Third levela Map
All attributes are level
Fourth added to the request so that they can be
picked up by JSPs
Fifth level
Click to edit Master title style
ModelMap
Add it edit
Click to as aMaster
parameter to your controller method
text styles
public Second
String leveldoController(ModelMap modelMap){
modelMap.addAttribute(user);
Third level
modelMap.addAttribute(otherUser,
Fourth level user);
return index;
} Fifth level

Wed consume it in our JSP like this:


User: ${user}<br /><br />

Other User: ${otherUser}


Click to edit Master title style
ModelAndView
Combines
Click the model
to edit Master and view into one object
text styles
Second
public level
ModelAndView doController() {
Third level mav = new ModelAndView(index);
ModelAndView
mav.addObject(user);
Fourth level
mav.addObject(otherUser,
Fifth level user);
return mav;
}

Wed consume it in our JSP like this:


User: ${user}<br /><br />

Other User: ${otherUser}


Click3:toPutting
Lab edit Master title style
it all together
Addto
Click a edit
more complex
Master controller that takes a path param and
text styles
displays
Second it level
back to the user
Also,have
Third itlevel
echo back a header
Fourth level
Fifth level
Click to edit Master title style
Resources
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%9
Click to edit Master text styles
3controller
Second level
http://en.wikipedia.org/wiki/Spring_Framework#Model-view-
Third level
controller_framework
Fourth level
http://static.springsource.org/spring/docs/3.0.x/spring-
Fifth level
framework-reference/html/mvc.html
Click to edit Master title style
Click to edit Master text styles
Second level
Third level

Thanks for listening


Fourth level
Fifth level

Questions & Answers

Das könnte Ihnen auch gefallen