SlideShare a Scribd company logo
1 of 9
Download to read offline
© 2010 Marty Hall
Generating theg
Server Response:
HTTP Status CodesHTTP Status CodesOriginals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.3
p j p
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Agenda
• Format of the HTTP response
• How to set status codes
• What the status codes are good for
• Shortcut methods for redirection and error
pages
A l t th t di t t b• A servlet that redirects users to browser-
specific pages
• A front end to various search engines• A front end to various search engines
5
HTTP Request/Responseq p
• Request • Response
GET /servlet/SomeName HTTP/1.1
Host: ...
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN:
Content Type: text/html
Header2: ...
...
HeaderN: ...HeaderN:
(Blank Line)
HeaderN: ...
(Blank Line)
<!DOCTYPE ...>
<HTML><HTML>
<HEAD>...</HEAD>
<BODY>
...
</BODY></HTML>
6
Setting Status Codes
• response.setStatus(int statusCode)
– Use a constant for the code, not an explicit int.
Constants are in HttpServletResponse
– Names derived from standard message– Names derived from standard message.
E.g., SC_OK, SC_NOT_FOUND, etc.
• response.sendError(int code,p ( ,
String message)
– Wraps message inside small HTML document
• response.sendRedirect(String url)
– Sets status code to 302
S t L ti h d l– Sets Location response header also
7
Common HTTP 1.1 Status
CodesCodes
• 200 (OK)
– Everything is fine; document follows.
– Default for servlets.
204 (No Content)• 204 (No Content)
– Browser should keep displaying previous document.
• 301 (Moved Permanently)• 301 (Moved Permanently)
– Requested document permanently moved elsewhere
(indicated in Location header).
– Browsers go to new location automatically.
– Browsers are technically supposed to follow 301 and 302
(next page) requests only when the incoming request is(next page) requests only when the incoming request is
GET, but do it for POST with 303. Either way, the
Location URL is retrieved with GET.8
Common HTTP 1.1 Status
Codes (Continued)Codes (Continued)
• 302 (Found)
R t d d t t il d l h– Requested document temporarily moved elsewhere
(indicated in Location header).
– Browsers go to new location automatically.
– Servlets should use sendRedirect, not setStatus, when
setting this header. See example.
• 401 (Unauthorized)401 (Unauthorized)
– Browser tried to access password-protected page without
proper Authorization header.
• 404 (Not Found)• 404 (Not Found)
– No such page. Servlets should use sendError to set this.
– Problem: Internet Explorer and small (< 512 bytes) error
pages. IE ignores small error page by default.
– Fun and games: http://www.plinko.net/404/
9
A Servlet That Redirects Users
to Browser-Specific Pagesto Browser-Specific Pages
public class WrongDestination extends HttpServlet {
public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String userAgent = request.getHeader("User-Agent");g g q g ( g )
if ((userAgent != null) &&
(userAgent.contains("MSIE")) {
response.sendRedirect("http://home.mozilla.com");
} else {
response.sendRedirect("http://www.microsoft.com");
}
}}
}
10
A Servlet That Redirects Users
to Browser-Specific Pagesto Browser-Specific Pages
• Original URL for both
– http://localhost/status-codes/servlet/coreservlets.WrongDestination
11
A Front End to Various
Search EnginesSearch Engines
public class SearchEngines extends HttpServlet {
public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String searchString =
request.getParameter("searchString");
if ((searchString == null) ||
(searchString.length() == 0)) {
reportProblem(response "Missing search string");reportProblem(response, Missing search string );
return;
}
searchString = URLEncoder.encode(searchString, "utf-8");
String searchEngineName =
request.getParameter("searchEngine");
if ((searchEngineName == null) ||
( hE i N l th() 0)) {(searchEngineName.length() == 0)) {
reportProblem(response, "Missing search engine name");
return;
}12
A Front End to Various
Search Engines (Continued)Search Engines (Continued)
String searchURL =
SearchUtilities.makeURL(searchEngineName,SearchUtilities.makeURL(searchEngineName,
searchString);
if (searchURL != null) {
response.sendRedirect(searchURL);
} else {
reportProblem(response,
"Unrecognized search engine");
}}
}
private void reportProblem(HttpServletResponse response,
String message)
throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
)message);
}
}
13
A Front End to Various
Search Engines (Continued)Search Engines (Continued)
public class SearchSpec {
/** Builds a URL for the results page by
* simply concatenating the base URL
//* (http://...?someVar=") with the
* URL-encoded search string (jsp+training).
*/
public String makeURL(String searchString) {
return(baseURL + searchString);( g);
}
…
}}
14
Front End to Search Engines:
HTML FormHTML Form
15
Front End to Search Engines:
Result for Valid DataResult for Valid Data
16
Front End to Search Engines:
Result for Invalid DataResult for Invalid Data
17
Summary
• Many servlet tasks can only bey y
accomplished with HTTP status codes
• Setting status codes:
Redirect user with response sendRedirect(someURL)– Redirect user with response.sendRedirect(someURL)
• If you insert user-supplied data into the URL, encode with
URLEncoder.encode
S d 404 ith dE– Send 404 error pages with sendError
– In general, set via response.setStatus
• Most important status codesp
– 200 (default)
– 302 (forwarding; set with sendRedirect)
401 (password needed)– 401 (password needed)
– 404 (not found; set with sendError)
18
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.19

More Related Content

What's hot

JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag LibraryIlio Catallo
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPeter Eisentraut
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLseleciii44
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
CQ5 QueryBuilder - .adaptTo(Berlin) 2011CQ5 QueryBuilder - .adaptTo(Berlin) 2011
CQ5 QueryBuilder - .adaptTo(Berlin) 2011Alexander Klimetschek
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO ObjectsAJINKYA N
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter APImeysholdt
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide LineGagan Vishal Mishra
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Dmytro Chyzhykov
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsMichele Capra
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.fRui Apps
 
Spot the Web Vulnerability
Spot the Web VulnerabilitySpot the Web Vulnerability
Spot the Web VulnerabilityMiroslav Stampar
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernatehr1383
 

What's hot (20)

JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQL
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
CQ5 QueryBuilder - .adaptTo(Berlin) 2011CQ5 QueryBuilder - .adaptTo(Berlin) 2011
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Data repositories
Data repositoriesData repositories
Data repositories
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter API
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 Apps
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spot the Web Vulnerability
Spot the Web VulnerabilitySpot the Web Vulnerability
Spot the Web Vulnerability
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 

Viewers also liked

13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
11 page-directive
11 page-directive11 page-directive
11 page-directivesnopteck
 
ICT observatories for better governance
ICT observatories for better governanceICT observatories for better governance
ICT observatories for better governancezalisova
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
01 web-apps
01 web-apps01 web-apps
01 web-appssnopteck
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
07 cookies
07 cookies07 cookies
07 cookiessnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
Linea Viso-Corpo "Naturale" by Delta BkB
Linea Viso-Corpo "Naturale" by Delta BkBLinea Viso-Corpo "Naturale" by Delta BkB
Linea Viso-Corpo "Naturale" by Delta BkBgravercosmetici
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPsKind of Digital
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 

Viewers also liked (19)

13 java beans
13 java beans13 java beans
13 java beans
 
11 page-directive
11 page-directive11 page-directive
11 page-directive
 
ICT observatories for better governance
ICT observatories for better governanceICT observatories for better governance
ICT observatories for better governance
 
03 form-data
03 form-data03 form-data
03 form-data
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
14 mvc
14 mvc14 mvc
14 mvc
 
01 web-apps
01 web-apps01 web-apps
01 web-apps
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
07 cookies
07 cookies07 cookies
07 cookies
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
The Change! Tool
The Change! ToolThe Change! Tool
The Change! Tool
 
Linea Viso-Corpo "Naturale" by Delta BkB
Linea Viso-Corpo "Naturale" by Delta BkBLinea Viso-Corpo "Naturale" by Delta BkB
Linea Viso-Corpo "Naturale" by Delta BkB
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPs
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 

Similar to 05 status-codes

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocratJonathan Linowes
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuseejlp12
 
Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesDeeptiJava
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersTeng Shiu Huang
 
07 response-headers
07 response-headers07 response-headers
07 response-headershanichandra
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 

Similar to 05 status-codes (20)

Android networking-2
Android networking-2Android networking-2
Android networking-2
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
 
Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
servlets
servletsservlets
servlets
 
Practical OData
Practical ODataPractical OData
Practical OData
 
Jsp
JspJsp
Jsp
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
07 response-headers
07 response-headers07 response-headers
07 response-headers
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 

Recently uploaded

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
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
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
 
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
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
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
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
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
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Recently uploaded (20)

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
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.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
 
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
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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)
 
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!
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
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
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

05 status-codes

  • 1. © 2010 Marty Hall Generating theg Server Response: HTTP Status CodesHTTP Status CodesOriginals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.3 p j p © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Agenda • Format of the HTTP response • How to set status codes • What the status codes are good for • Shortcut methods for redirection and error pages A l t th t di t t b• A servlet that redirects users to browser- specific pages • A front end to various search engines• A front end to various search engines 5 HTTP Request/Responseq p • Request • Response GET /servlet/SomeName HTTP/1.1 Host: ... HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: Content Type: text/html Header2: ... ... HeaderN: ...HeaderN: (Blank Line) HeaderN: ... (Blank Line) <!DOCTYPE ...> <HTML><HTML> <HEAD>...</HEAD> <BODY> ... </BODY></HTML> 6
  • 3. Setting Status Codes • response.setStatus(int statusCode) – Use a constant for the code, not an explicit int. Constants are in HttpServletResponse – Names derived from standard message– Names derived from standard message. E.g., SC_OK, SC_NOT_FOUND, etc. • response.sendError(int code,p ( , String message) – Wraps message inside small HTML document • response.sendRedirect(String url) – Sets status code to 302 S t L ti h d l– Sets Location response header also 7 Common HTTP 1.1 Status CodesCodes • 200 (OK) – Everything is fine; document follows. – Default for servlets. 204 (No Content)• 204 (No Content) – Browser should keep displaying previous document. • 301 (Moved Permanently)• 301 (Moved Permanently) – Requested document permanently moved elsewhere (indicated in Location header). – Browsers go to new location automatically. – Browsers are technically supposed to follow 301 and 302 (next page) requests only when the incoming request is(next page) requests only when the incoming request is GET, but do it for POST with 303. Either way, the Location URL is retrieved with GET.8
  • 4. Common HTTP 1.1 Status Codes (Continued)Codes (Continued) • 302 (Found) R t d d t t il d l h– Requested document temporarily moved elsewhere (indicated in Location header). – Browsers go to new location automatically. – Servlets should use sendRedirect, not setStatus, when setting this header. See example. • 401 (Unauthorized)401 (Unauthorized) – Browser tried to access password-protected page without proper Authorization header. • 404 (Not Found)• 404 (Not Found) – No such page. Servlets should use sendError to set this. – Problem: Internet Explorer and small (< 512 bytes) error pages. IE ignores small error page by default. – Fun and games: http://www.plinko.net/404/ 9 A Servlet That Redirects Users to Browser-Specific Pagesto Browser-Specific Pages public class WrongDestination extends HttpServlet { public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userAgent = request.getHeader("User-Agent");g g q g ( g ) if ((userAgent != null) && (userAgent.contains("MSIE")) { response.sendRedirect("http://home.mozilla.com"); } else { response.sendRedirect("http://www.microsoft.com"); } }} } 10
  • 5. A Servlet That Redirects Users to Browser-Specific Pagesto Browser-Specific Pages • Original URL for both – http://localhost/status-codes/servlet/coreservlets.WrongDestination 11 A Front End to Various Search EnginesSearch Engines public class SearchEngines extends HttpServlet { public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String searchString = request.getParameter("searchString"); if ((searchString == null) || (searchString.length() == 0)) { reportProblem(response "Missing search string");reportProblem(response, Missing search string ); return; } searchString = URLEncoder.encode(searchString, "utf-8"); String searchEngineName = request.getParameter("searchEngine"); if ((searchEngineName == null) || ( hE i N l th() 0)) {(searchEngineName.length() == 0)) { reportProblem(response, "Missing search engine name"); return; }12
  • 6. A Front End to Various Search Engines (Continued)Search Engines (Continued) String searchURL = SearchUtilities.makeURL(searchEngineName,SearchUtilities.makeURL(searchEngineName, searchString); if (searchURL != null) { response.sendRedirect(searchURL); } else { reportProblem(response, "Unrecognized search engine"); }} } private void reportProblem(HttpServletResponse response, String message) throws IOException { response.sendError(HttpServletResponse.SC_NOT_FOUND, )message); } } 13 A Front End to Various Search Engines (Continued)Search Engines (Continued) public class SearchSpec { /** Builds a URL for the results page by * simply concatenating the base URL //* (http://...?someVar=") with the * URL-encoded search string (jsp+training). */ public String makeURL(String searchString) { return(baseURL + searchString);( g); } … }} 14
  • 7. Front End to Search Engines: HTML FormHTML Form 15 Front End to Search Engines: Result for Valid DataResult for Valid Data 16
  • 8. Front End to Search Engines: Result for Invalid DataResult for Invalid Data 17 Summary • Many servlet tasks can only bey y accomplished with HTTP status codes • Setting status codes: Redirect user with response sendRedirect(someURL)– Redirect user with response.sendRedirect(someURL) • If you insert user-supplied data into the URL, encode with URLEncoder.encode S d 404 ith dE– Send 404 error pages with sendError – In general, set via response.setStatus • Most important status codesp – 200 (default) – 302 (forwarding; set with sendRedirect) 401 (password needed)– 401 (password needed) – 404 (not found; set with sendError) 18
  • 9. © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.19