You are on page 1of 32

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
Objectives
Welltosee
Click editwhat
Master an HTTP
text message looks like
styles
well look level
Second at some of Spring MVCs RESTful features, including
RequestBody,
Third levelResponseBody, HttpMessageConverters,
HttpEntity objects,
Fourth leveland dealing with exceptions
These are useful forlevel
Fifth RESTful web services and normal form-
based interactions
Click Message
HTTP to edit Master title style
Sample
Click Requests:
to edit Master text styles
SecondHTTP/1.1
GET /view/1 level
Third
User-Agent: Chrome
level
Accept: application/json
Fourth level
[CRLF]
Fifth level
POST /save HTTP/1.1
User-Agent: IE
Content-Type: application/x-www-form-urlencoded
[CRLF]
name=x&id=2
Click Message
HTTP to edit Master title style
(Responses)
Sample
Click Responses:
to edit Master text styles
Second
HTTP/1.1 200 OKlevel
Content-Type:
Thirdtext/html
level
Content-Length: 1337
[CRLF] Fourth level
<html> Fifth level
Some HTML Content.
</html>

HTTP/1.1 500 Internal Server Error

HTTP/1.1 201 Created


Location: /view/7
[CRLF]
Some message goes here.
Click to edit Master title style
RequestBody
Annotating
Click a handler
to edit Master method parameter with @RequestBody
text styles
will bind that
Second levelparameter to the request body
Third level
@RequestMapping("/echo/string")
public void writeString(@RequestBody
Fourth level String input) {}
Fifth level
@RequestMapping("/echo/json")
public void writeJson(@RequestBody SomeObject input) {}
Click to edit Master title style
ResponseBody
Annotating
Click a return
to edit Master text type
styles with @ResponseBody tells Spring
MVC that level
Second the object returned should be treated as the
response body
Third level
No view is Fourth
rendered
level in this case
@RequestMapping("/echo/string")
Fifth level
public @ResponseBody String readString() {}

@RequestMapping("/echo/json")
public @ResponseBody SomeObject readJson() {}
Click to edit Master title style
HttpMessageConverters
Howto
Click does Spring text
edit Master MVC know how to turn a JSON string into
styles
SomeObject,
Second level or vice-versa?
HttpMessageConverters
Third level
These are responsible
Fourth level for converting a request body to a
certain type, or a certain
Fifth level type into a response body
Spring MVC figures out which converter to use based on
Accept and Content-Type headers, and the Java type
Your Accept and Content-Type headers DONT have to
match. For example, you can send in JSON and ask for XML
back
Click to edit Master title style
HttpMessageConverters
A number
Click of HttpMessageConverters
to edit Master text styles are already provided
You can define
Second level your own
You dont
Thirdspecify
level which ones are used to convert
request/response bodies they are selected based on the
Fourth level
Content-Type/Accept
Fifth level headers
Click to
MIME edit Master title style
Types
HttpMessageConverters
Click to edit Master text stylesmake heavy use of MIME types
These are level
Second the value for Accept and Content-Type headers
Two-part identifier
Third level for content formats
First part is thelevel
Fourth type. ie, application
Second part is the
Fifth levelsub-type. ie, json
application/json
Click to edit Master title style
StringHttpMessageConverter
Reads
Click andMaster
to edit writestext
Strings.
styles
Reads
Secondtext/*
level
Writes text/plain
Third level
Fourth level
Fifth level
Click to edit Master title style
StringHttpMessageConverter
@RequestMapping("/echo/string")
Click
public to edit MasterString
@ResponseBody text styles
echoString(@RequestBody String input) {
return
Second Your
level Text Was: + input;
}
Third level
POST /echo/string HTTP/1.1 REQUEST
Fourth level
Accept: text/plain
Content-Type: text/plain
Fifth level
Hello!
HTTP/1.1 200 OK RESPONSE
Content-Type: text/plain
Content-Length: 17

Your Text Was: Hello!


Click to edit Master title style
MappingJacksonHttpMessageCo
nverter
Click to edit Master text styles
Maps to/from
Second level JSON objects using the Jackson library
Reads application/json
Third level
Writes application/json
Fourth level
Fifth level
Click to edit Master title style
MappingJacksonHttpMessageCo
nverter
Click to edit Master text styles
Second level
public Person {
Third level
// String name, int age;
} Fourth level
Fifth level
@RequestMapping("/echo/json")
public @ResponseBody Person echoJson(@RequestBody Person person) {
// Upper case name, square age
return person;
}
Click to edit Master title style
MappingJacksonHttpMessageCo
nverter
Click to edit Master text styles
Second levelHTTP/1.1
POST /echo/string REQUEST
Accept: application/json
Third
Content-Type: level
application/json
Fourth level
{ name : Spencer, age : 5 }
Fifth level
HTTP/1.1 201 Created RESPONSE
Content-Type: application/json

{ name : SPENCER, age : 25 }


Click to edit Master title style
Jaxb2RootElementHttpMessageC
onverter
Click to edit Master text styles
Maps to/from
Second level XML objects
Musthave
Third your
level object at least annotated with
@XmlRootElement
Fourth level
Reads text/xml, application/xml
Fifth level
Writes text/xml, application/xml
Click to edit Master title style
Jaxb2RootElementHttpMessageC
onverter
Click to edit Master text styles
Second level
@XmlRootElement
public Person {//
Third String name, int age;}
level
Fourth level
@RequestMapping("/echo/xml")
public @ResponseBody Person
Fifth level echoXml(@RequestBody Person person) {
// Upper case name, square age
return person;
}
Click to edit Master title style
Jaxb2RootElementHttpMessageC
onverter
Click to edit Master text styles
Second levelHTTP/1.1
POST /echo/string REQUEST
Accept: application/xml
Third level
Content-Type: application/xml
Fourth level
<thing><name>Spencer</name><age>5</age></thing>
Fifth level
HTTP/1.1 201 Created RESPONSE
Content-Type: application/xml

<thing><name>SPENCER</name><age>25</age></thing>
Click to edit Master title style
ByteArrayHttpMessageConverter
Click to edit Master text styles
Can read/write
Second level byte arrays (useful for dealing with binary
data, such
Third as images)
level
Reads */* Fourth level
Writes application/octet-stream
Fifth level
Click to edit Master title style
ByteArrayHttpMessageConverter
@RequestMapping("/echo/string")
Click to edit Master text styles
public @ResponseBody String echoString(@RequestBody byte[] input) {
return
Second new
levelString(input);
}
Third level
POST /echo/string HTTP/1.1
Fourth level REQUEST
Accept: text/plain
Fifth level
Content-Type: text/plain

Hello!

HTTP/1.1 200 OK RESPONSE


Content-Type: application/octet-stream
Content-Length: 6

Hello!
Click1to edit Master title style
Lab
Create
Click a handler
to edit Master textthat takes a request body and echoes it
styles
back.
Second level
Create a handler
Third level that takes a request body, creates an
object with it, and
Fourth returns it as JSON.
level
Create a handler Fifth that
level takes an XML input and echoes it back
as JSON.
Test all of these with your HttpClient
Click to
Other editof
parts Master titleMessage
the HTTP style
Whattoifedit
Click youMaster
needtext
to get/set
styles headers?
Or set the level
Second status code?
Third level
@RequestMapping("/echo/string")
public @ResponseBody
Fourth String
level echoString(@RequestBody String input,
HttpServletRequest request,
Fifth level HttpServletResponse response) {
String requestType = request.getHeader(Content-Type);
response.setHeader(Content-Type, text/plain);

response.setStatus(200);

return input
}
Click to edit Master title style
@ResponseStatus
There
Click toisedit
a convenient way to set what the default status for a
Master text styles
particular
Second levelhandler should be
@ResponseStatus
Third level
Fourth level
@RequestMapping("/create")
@ResponseStatus(HttpStatus.CREATED)
Fifth level // CREATED == 201
public void echoString(String input) {
}
Click to edit Master title style
HttpEntity
Convenience
Click class
to edit Master textfor dealing with bodies, headers, and
styles
status
Second level
Converts messages
Third level with HttpMessageConverters
@RequestMapping("/image/upload")
Fourth level
public ResponseEntity<String> upload(HttpEntity<byte[]> rEntity) {
Fifth level
String t = rEntity.getHeaders().getFirst(Content-Type);
byte[] data = rEntity.getBody();
// Save the file
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set(Location, /image/1);

return new ResponseEntity<String>(Created,


responseHeaders, HttpStatus.CREATED);
}
Click2to edit Master title style
Lab
Convert
Click allMaster
to edit your String controller method to use HttpEntity
text styles
Convert
Secondthe Create Person controller method to use an
level
HttpEntity.
ThirdAlso,
level return a Location header and a 201 (Created)
responsecode.Fourth level
Fifth level
Click to edit
Dealing with Master title style
exceptions
By default,
Click Springtext
to edit Master MVC will map certain exceptions to status
styles
codes
Second level
You can implement
Third level your own HandlerExceptionResolver,
which takes an exception
Fourth level and returns a ModelAndView
You can register Fiftha level
SimpleMappingExceptionResolver to map
exceptions to views
You can annotate methods in the controller to handle specific
exceptions
Click to Exception
Default edit MasterMappings
title style
Click to take
These effecttext
edit Master if you have no other configuration
styles
ConversionNotSupportedException
Second level => 500
NoSuchMethodHandlingException
Third level => 404
MissingServletRequestParameterException
Fourth level => 400
HttpRequestMethodNotSupportedException
Fifth level => 405
TypeMismatchException => 400
HttpMediaTypeNotSupportedException => 415
HttpMediaTypeNotAcceptableException => 406
Click to edit Master title style
HandlerExceptionResolver
Allows
Click youMaster
to edit to control how exceptions are resolved
text styles
Implement HandlerExceptionResolver (but youll probably
Second level
extend AbstractHandlerExceptionResolver)
Third level
Fourth level extends AbstractHandlerExceptionResolver
class AnExceptionHandler {
Fifth leveldoResolveException(
protected ModelAndView
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {

System.out.println("I got an error.");


return new ModelAndView("errors/someError");
}
}
Click to edit Master title style
SimpleMappingExceptionResolver
Allows
Click youMaster
to edit to simply
text map
styles exceptions to views
This is howlevel
Second the Stack comes configured
<bean Third level
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
Fourth level
<property name="exceptionMappings">
<props>
Fifth level
<prop key=".DataAccessException">errors/dataAccessFailure</prop>
<prop key=".AccessDeniedException">errors/dataAccessFailure</prop>
<prop key=".TypeMismatchException">errors/resourceNotFound</prop>
</props>
</property>
<property name="defaultErrorView" value="errors/generalError"/>
<property name="warnLogCategory" value=com.hvn.helloworld"/>
</bean>
Click to edit Master title style
@ExceptionHandler
Create
Click a method
to edit to styles
Master text handle the exception, annotate it with
@ExceptionHandler,
Second level and pass in the exception(s) that method
can handle
Third level
ExceptionHandler methods look a lot like normal handler
Fourth level
methods
Fifth level
@RequestMapping("/error")
public void doSomething() {
throw new RecoverableDataAccessException("Unable to access that database.");
}

@ExceptionHandler(DataAccessException.class)
public @ResponseBody String handleDataAccessError(DataAccessException ex) {
return ex.getMessage();
}
Click to edit Master title style
@ResponseStatus
We saw
Click this
to edit annotation
Master earlier
text styles
Itcan alsolevel
Second be placed on Exception classes or
@ExeptionHandler
Third level methods to return a specific status code for
a particular exception
Fourth level
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
Fifth level
@ExceptionHandler(DataAccessException.class)
public void handleDataAccessError(DataAccessException ex) {}

@ResponseStatus(value = HttpStatus.PAYMENT_REQUIRED, message = I need money.)


public class PaymentRequiredException {}
Click3to edit Master title style
Lab
Looktoatedit
Click theMaster
SimpleMappingExceptionResolver
text styles already
configured
Second levelin your project
Create a controller
Third level that throws one of those exceptions and
verify that your request
Fourth level gets redirected to the corresponding
view
Fifth level
Remove the config, and change your exception to
HttpMediaTypeNotSupportedException. Verify that you get a
415 using your Http Client
Implement an @ExceptionHandler method
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

You might also like