Spring MVC Part 2 Spencer Uresk. Notes This is a training, NOT a presentation Please ask questions This is being recorded https://tech.lds.org/wiki/Java_Stack_Training.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
CS320 Web and Internet Programming Generating HTTP Responses
16-Jun-15 HTTP Hypertext Transfer Protocol. 2 HTTP messages HTTP is the language that web clients and web servers use to talk to each other HTTP is largely.
HTTP Hypertext Transfer Protocol. HTTP messages HTTP is the language that web clients and web servers use to talk to each other –HTTP is largely “under.
Data and Computer Communications Eighth Edition by William Stallings Lecture slides by Lawrie Brown Chapter 23 – Internet Applications Internet Directory.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
Client, Server, HTTP, IP Address, Domain Name. Client-Server Model Client Bob Yahoo Server yahoo.com/finance.html A text file named finance.html.
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
Rensselaer Polytechnic Institute CSC-432 – Operating Systems David Goldschmidt, Ph.D.
TP2653 Adv Web Programming SOAP and WSDL. SOAP Simple Object Access Protocol – Lightweight XML-based messaging protocol – A protocol for accessing a Web.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Separation of Concerns Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 © 1.
FTP (File Transfer Protocol) & Telnet
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
HyperText Transfer Protocol (HTTP).  HTTP is the protocol that supports communication between web browsers and web servers.  A “Web Server” is a HTTP.
CSC 2720 Building Web Applications Getting and Setting HTTP Headers (With PHP Examples)
CP476 Internet Computing Lecture 5 : HTTP, WWW and URL 1 Lecture 5. WWW, HTTP and URL Objective: to review the concepts of WWW to understand how HTTP works.
TCP/IP Protocol Suite 1 Chapter 22 Upon completion you will be able to: World Wide Web: HTTP Understand the components of a browser and a server Understand.
1 EIE424 Distributed Systems and Networking Programming –Part II 2. XML-RPC.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
Maryam Elahi University of Calgary – CPSC 441.  HTTP stands for Hypertext Transfer Protocol.  Used to deliver virtually all files and other data (collectively.
Java Omar Rana University of South Asia. Course Overview JAVA  C/C++ and JAVA Comparison  OOP in JAVA  Exception Handling  Streams  Graphics User.
Sistem Jaringan dan Komunikasi Data #9. DNS The Internet Directory Service  the Domain Name Service (DNS) provides mapping between host name & IP address.
GET Examples – db.org/sops/3/experimental_conditions/55http://seek.sysmo- db.org/sops/3/experimental_conditions/55 –
Introduction to Java Server Pages (JSPs) Robert Thornton.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
James Holladay, Mario Sweeney, Vu Tran. Web Services Presentation Web Services Theory James Holladay Tools – Visual Studio Vu Tran Tools – Net Beans Mario.
Or, Hey can’t we just do it using HTTP for the envelope?
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
HTTP - Forms - AppEngine Jim Eng
1 Seminar on Service Oriented Architecture Principles of REST.
WWW: an Internet application Bill Chu. © Bei-Tseng Chu Aug 2000 WWW Web and HTTP WWW web is an interconnected information servers each server maintains.
Server - Client Communication Getting data from server.
INTEGRATION OF BACKBONE.JS WITH SPRING 3.1. Agenda New Features and Enhancements in Spring 3.1 What is Backbone.js and why I should use it Spring 3.1.
Appendix E: Overview of HTTP ©SoftMoore ConsultingSlide 1.
Operating Systems Lesson 12. HTTP vs HTML HTML: hypertext markup language ◦ Definitions of tags that are added to Web documents to control their appearance.
Jan 2001C.Watters1 World Wide Web and E-Commerce Client Side Processing.
McGraw-Hill©The McGraw-Hill Companies, Inc., 2004 Chapter 27 HTTP and WWW.
IS-907 Java EE World Wide Web - Overview. World Wide Web - History Tim Berners-Lee, CERN, 1990 Enable researchers to share information: Remote Access.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 1 Fundamentals.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
Web Server Design Week 13 Old Dominion University Department of Computer Science CS 495/595 Spring 2010 Martin Klein 4/7/10.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
RESTful Web Services What is RESTful?
Lecture IV: REST Web Service
Overview of Servlets and JSP
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
COMP 431 Internet Services & Protocols
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
SOAP, Web Service, WSDL Week 14 Web site:
Web Services Essentials. What is a web service? web service: software functionality that can be invoked through the internet using common protocols like.
CITA 330 Section 10 Web Remoting Techniques. Web Remoting Web Remoting is a term used to categorize the technique of using JavaScript to directly make.
Web Programming Week 1 Old Dominion University Department of Computer Science CS 418/518 Fall 2007 Michael L. Nelson 8/27/07.
Introduction to Servlets
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
HTTP – An overview.
Play Framework: Introduction
J2EE Lecture 7: Spring – Spring MVC
XMLHttp Object.
Generating the Server Response: HTTP Status Codes
Spring MVC Part 2 Spencer Uresk.
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Spring MVC Part 2 Spencer Uresk

Notes This is a training, NOT a presentation Please ask questions This is being recorded Prerequisites – Beginning Spring MVC (and all of its prerequisites)

Overview Last time, we showed how to map requests to handler methods, get information about the request, and how to pass information back to the view We’ll see what an HTTP message looks like This week, we’ll look at some of Spring MVC’s RESTful features, including RequestBody, ResponseBody, HttpMessageConverters, HttpEntity objects, and dealing with exceptions These are useful for RESTful web services and normal form-based interactions

HTTP Message What does an HTTP message look like? Sample Requests: GET /view/1 HTTP/1.1 User-Agent: Chrome Accept: application/json [CRLF] POST /save HTTP/1.1 User-Agent: IE Content-Type: application/x-www-form-urlencoded [CRLF] name=x&id=2 Request Line Headers Request Line Headers Request Body

HTTP Message (Responses) Sample Responses HTTP/ OK Content-Type: text/html Content-Length: 1337 [CRLF] Some HTML Content. HTTP/ Internal Server Error HTTP/ Created Location: /view/7 [CRLF] Some message goes here. Status Line Headers Response Body Status Line Headers Response Body

RequestBody Annotating a handler method parameter will bind that parameter to the request public void String input) public void SomeObject input) {}

ResponseBody Annotating a return type tells Spring MVC that the object returned should be treated as the response body No view is rendered in this String readString() SomeObject readJson() {}

HttpMessageConverters How does Spring MVC know how to turn a JSON string into SomeObject, or vice-versa? HttpMessageConverters These are responsible for converting a request body to a certain type, or a certain 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 DON’T have to match. For example, you can send in JSON and ask for XML back

HttpMessageConverters A number of HttpMessageConverters are already provided You can define your own, but that is outside the scope of this training You don’t specify which ones are used to convert request/response bodies – they are selected based on the Content-Type/Accept headers

MIME Types HttpMessageConverters make heavy use of MIME types (RFC 2046) These are the value for Accept and Content-Type headers Two-part identifier for content formats First part is the type. ie, application Second part is the sub-type. ie, json application/json

StringHttpMessageConverter Reads and writes Strings. Reads text/* Writes text/plain

StringHttpMessageConverter a POST /echo/string HTTP/1.1 Accept: text/plain Content-Type: text/plain String String input) { return “Your Text Was: “ + input; } HTTP/ OK Content-Type: text/plain Content-Length: 17 Your Text Was: Hello! REQUEST RESPONSE

MappingJacksonHttpMessageConverter Maps to/from JSON objects using the Jackson library Reads application/json Writes application/json

MappingJacksonHttpMessageConverter a POST /echo/string HTTP/1.1 Accept: application/json Content-Type: application/json { “name” : “Spencer”, “age” : 5 } public Person { // String name, int age; Person Person person) { // Upper case name, square age return person; } HTTP/ Created Content-Type: application/json { “name” : “SPENCER”, “age” : 25 } REQUEST RESPONSE

Jaxb2RootElementHttpMessageConverter Maps to/from XML objects Must have your object at least annotated Reads text/xml, application/xml Writes text/xml, application/xml

Jaxb2RootElementHttpMessageConverter a POST /echo/string HTTP/1.1 Accept: application/xml Content-Type: application/xml Spencer public Person {// String name, int Person Person person) { // Upper case name, square age return person; } HTTP/ Created Content-Type: application/xml SPENCER 25 REQUEST RESPONSE

ByteArrayHttpMessageConverter Can read/write byte arrays (useful for dealing with binary data, such as images) Reads */* Writes application/octet-stream

ByteArrayHttpMessageConverter a POST /echo/string HTTP/1.1 Accept: text/plain Content-Type: text/plain String byte[] input) { return new String(input); } HTTP/ OK Content-Type: application/octet-stream Content-Length: 6 Hello! REQUEST RESPONSE

Lab 1 Create a handler that takes a request body and echoes it back. Create a handler that takes a request body, creates an object with it, and returns it as JSON. Create a handler that takes an XML input and echoes it back as JSON. Test all of these with your HttpClient

Other parts of the HTTP Message What if you need to get/set headers? Or set the status String String input, HttpServletRequest request, HttpServletResponse response) { String requestType = request.getHeader(“Content-Type”); response.setHeader(“Content-Type”, “text/plain”); response.setStatus(200); return input }

@ResponseStatus There is a convenient way to set what the default status for a particular handler @ResponseStatus(HttpStatus.CREATED) // CREATED == 201 public void echoString(String input) { }

HttpEntity Convenience class for dealing with bodies, headers, and status Converts messages with public ResponseEntity upload(HttpEntity rEntity) { 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 (“Created”, responseHeaders, HttpStatus.CREATED); }

Lab 2 Convert all your String controller method to use HttpEntity Convert the Create Person controller method to use an HttpEntity. Also, return a Location header and a 201 (Created) response code.

Dealing with exceptions By default, Spring MVC will map certain exceptions to status codes You can implement your own HandlerExceptionResolver, which takes an exception and returns a ModelAndView You can register a SimpleMappingExceptionResolver to map exceptions to views You can annotate methods in the controller to handle specific exceptions

Default Exception Mappings These take effect if you have no other configuration ConversionNotSupportedException => 500 NoSuchMethodHandlingException => 404 MissingServletRequestParameterException => 400 HttpRequestMethodNotSupportedException => 405 TypeMismatchException => 400 HttpMediaTypeNotSupportedException => 415 HttpMediaTypeNotAcceptableException => 406

HandlerExceptionResolver Allows you to control how exceptions are resolved Implement HandlerExceptionResolver (but you’ll probably extend AbstractHandlerExceptionResolver) class AnExceptionHandler extends AbstractHandlerExceptionResolver { protected ModelAndView doResolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("I got an error."); return new ModelAndView("errors/someError"); }

SimpleMappingExceptionResolver Allows you to simply map exceptions to views This is how the Stack comes configured errors/dataAccessFailure errors/resourceNotFound

@ExceptionHandler Create a method to handle the exception, annotate it and pass in the exception(s) that method can handle ExceptionHandler methods look a lot like normal handler public void doSomething() { throw new RecoverableDataAccessException("Unable to access that database."); String handleDataAccessError(DataAccessException ex) { return ex.getMessage(); }

@ResponseStatus We saw this annotation earlier It can also be placed on Exception classes methods to return a specific status code for a public void handleDataAccessError(DataAccessException ex) = HttpStatus.PAYMENT_REQUIRED, message = “I need money.”) public class PaymentRequiredException {}

Lab 3 Look at the SimpleMappingExceptionResolver already configured in your project Create a controller that throws one of those exceptions and verify that your request gets redirected to the corresponding view Remove the config, and change your exception to HttpMediaTypeNotSupportedException. Verify that you get a 415 using your Http Client Implement method