SlideShare a Scribd company logo
© 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 Library
Ilio Catallo
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQL
Peter Eisentraut
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
seleciii44
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
Holger 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 Objects
AJINKYA N
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
Yuval Zilberstein
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
Mohammad Faizan
 
Data repositories
Data repositoriesData repositories
Data repositories
Corneil du Plessis
 
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
Tricode (part of Dept)
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter API
meysholdt
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
Gagan 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.0
Dmytro 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 - slides
Hitesh-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 Apps
Michele 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 Vulnerability
Miroslav 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
 
The Change! Tool
The Change! ToolThe Change! Tool
The Change! Tool
EmmaCranidge
 
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 CSPs
Kind 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

Android networking-2
Android networking-2Android networking-2
Android networking-2
Aravindharamanan S
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Adrien Guéret
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
Rossen Stoyanchev
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
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
Jonathan Linowes
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
ejlp12
 
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
DeeptiJava
 
Practical OData
Practical ODataPractical OData
Practical OData
Vagif Abilov
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
Teng Shiu Huang
 
07 response-headers
07 response-headers07 response-headers
07 response-headers
hanichandra
 
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 API
07.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

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

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