SlideShare a Scribd company logo
1 of 48
•Generating the Server Response,
HTTP Status Codes, Specifying Status
Codes,
•HTTP / 1.1 Status Codes, Using
Redirections,
• HTTP Response Headers,
•Setting Response Headers from
Servlets,
•Understanding HTTP / 1.1 Response
Headers,
•Using Servlets to Generate JPEG
Images
Generating the Server Response
 when a Web server responds to a HTTP request to the
browser, the response typically consists of a status line,
some response headers, a blank line, and the document.
 A typical response looks like this:
The status line consists of the
 HTTP version (HTTP/1.1 in the example),
 a status code (200 in the example),
 and a very short message corresponding to the
status code (OK in the example)
Servlets can perform a variety of important
tasks by manipulating the status line and the
response headers.
For example,
 they can forward the user to other sites;
 indicate that the attached document is an image,
Adobe Acrobat file, or HTML file;
 tell the user that a password is required to access the
document;
 and so forth
HTTP Status Codes
 100 Continue
 200 OK
 202 Accepted
 400 Bad Request
 401 Unauthorized
 404 Not Found
 500 Internal Server Error
Specifying Status Codes
 The HTTP response status line consists of an HTTP
version, a status code, and an associated message.
 The message is directly associated with the status
code and the HTTP version is determined by the
server, all a servlet needs to do is to set the status
code.
A code of 200 is set automatically, so servlets
don't usually need to specify a status code at
all.
When they do want to, they use
 response.setStatus,
 response.sendRedirect,
 or response.sendError.
Setting Arbitrary Status Codes:
setStatus
 When you want to set an arbitrary status code, do so
with the setStatus method of HttpServletResponse
 The setStatus method takes an int (the status code) as
an argument
302 : sendRedirect
public void sendRedirect(String url)
 The 302 status code directs the browser to
connect to a new location.
 The sendRedirect method generates a 302
response along with a Location header giving
the URL of the new document.
404:sendError
 public void sendError(int code, String message)
 The 404 status code is used when no document
is found on the server.
 The sendError method sends a status code
(usually 404) along with a short message that is
automatically formatted inside an HTML
document and sent to the client.
HTTP / 1.1 Status Codes
 100–199
 Codes in the 100s are informational, indicating that the
client should respond with some other action.
 200–299
 Values in the 200s signify that the request was successful.
 300–399
 Values in the 300s are used for files that have moved and
usually include a Location header indicating the new
address.
400–499
 Values in the 400s indicate an error by the client
500–599
 Codes in the 500s signify an error by the server
 100 (Continue)
 If the server receives an Expect request header with a value of
100-continue, it means that the client is asking if it can send an
attached document in a follow-up request. This status code is
new in HTTP 1.1.
 200 (OK)
 A value of 200 (SC_OK) means that everything is fine; the
document follows for GET and POST requests.
 This status is the default for servlets;
 if you don't use setStatus, you'll get 200.
 202 (Accepted)
 A value of 202 (SC_ACCEPTED) tells the client that
the request is being acted upon but processing is
not yet complete.
 204 (No Content)
 A status code of 204 (SC_NO_CONTENT) stipulates
that the browser should continue to display the
previous document because no new document is
available.
 This behavior is useful if the user periodically
reloads a page by pressing the Reload button and
you can determine that the previous page is already
up-to-date
 205 (Reset Content)
 A value of 205 (SC_RESET_CONTENT) means that there is
no new document but the browser should reset the
document view.
 Thus, this status code is used to instruct browsers to clear
form fields.
 It is new in HTTP 1.1.
 301 (Moved Permanently)
 The 301 (SC_MOVED_PERMANENTLY) status indicates that
the requested document is elsewhere;
 the new URL for the document is given in the Location
response header.
 Browsers should automatically follow the link to the new
URL.
302 (Found)
 This value is similar to 301, except that in principle the
URL given by the Location header should be
interpreted as a temporary replacement, not a
permanent one
303 (See Other)
 The 303 (SC_SEE_OTHER) status is similar to 301 and
302, except that if the original request was POST, the
new document (given in the Location header) should
be retrieved with GET
400 (Bad Request)
 A 400 (SC_BAD_REQUEST) status indicates bad
syntax in the client request
401 (Unauthorized)
 A value of 401 (SC_UNAUTHORIZED) signifies that
the client tried to access a password-protected
page but that the request did not have proper
identifying information in the Authorization header
403 (Forbidden)
 A status code of 403 (SC_FORBIDDEN) means that
the server refuses to supply the resource,
regardless of authorization.
 This status is often the result of bad file or directory
permissions on the server.
404 (Not Found)
 The infamous 404 (SC_NOT_FOUND) status tells the
client that no resource could be found at that
address
 405 (Method Not Allowed)
 A 405 (SC_METHOD_NOT_ALLOWED) value signifies that
the request method (GET, POST, HEAD, PUT, DELETE,
etc.) was not allowed for this particular resource.
 This status code is new in HTTP 1.1.
 415 (Unsupported Media Type)
 A value of 415 (SC_UNSUPPORTED_MEDIA_TYPE) means
that the request had an attached document of a type
the server doesn't know how to handle.
 This status code is new in HTTP 1.1.
 417 (Expectation Failed)
 If the server receives an Expect request header with a
value of 100-continue, it means that the client is asking if
it can send an attached document in a follow-up request.
 In such a case, the server should either respond with this
status (417) to tell the browser it won't accept the
document or use 100 (SC_CONTINUE) to tell the client to
go ahead.
 This status code is new in HTTP 1.1.
 500 (Internal Server Error)
 500 (SC_INTERNAL_SERVER_ERROR) is the generic "server
is confused" status code
 501 (Not Implemented)
 The 501 (SC_NOT_IMPLEMENTED) status notifies the client
that the server doesn't support the functionality to fulfill
the request
 503 (Service Unavailable)
 A status code of 503 (SC_SERVICE_UNAVAILABLE) signifies
that the server cannot respond because of maintenance or
overloading
 505 (HTTP Version Not Supported)
 The 505 (SC_HTTP_VERSION_NOT_SUPPORTED) code
means that the server doesn't support the version of HTTP
named in the request line.
 This status code is new in HTTP 1.1.
sendRedirect()
 The sendRedirect() method of HttpServletResponse
interface can be used to redirect response to another
resource, it may be servlet, jsp or html file.
 It accepts relative as well as absolute URL.
 It works at client side because it uses the url bar of the
browser to make another request. So, it can work inside and
outside the server.
 Syntax of sendRedirect() method
 public void sendRedirect(String URL)throws IOException;
 Example of sendRedirect() method
 response.sendRedirect("http://www.google.com");
RequestDispatcher in Servlet
 The RequestDispatcher interface provides the facility of
dispatching the request to another resource it may be html,
servlet or jsp.
 This interface can also be used to include the content of
another resource also.
 It is one of the way of servlet collaboration.
 Syntax of getRequestDispatcher method
 public RequestDispatcher getRequestDispatcher(String resource);
 Example of using getRequestDispatcher method
 RequestDispatcher rd=request.getRequestDispatcher("servlet2");
 //servlet2 is the url-pattern of the second servlet
 rd.forward(request, response);//method may be include or forward
Methods of RequestDispatcher interface
 The RequestDispatcher interface provides two methods. They
are:
 public void forward(ServletRequest request,ServletResponse
response)throws
ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
 public void include(ServletRequest request,ServletResponse
response)throws
ServletException,java.io.IOException:Includes the content of
a resource (servlet, JSP page, or HTML file) in the response.
response of second servlet is sent to the client. Response of the
first servlet is not displayed to the user.
response of second servlet is included in the response of the first
servlet that is being sent to the client.
HTTP Response Headers
 specifying headers can play a useful role even when no
unusual status code is set.
 Response headers can be used to specify cookies, to supply
the modification date (for caching), to instruct the browser to
reload the page after a designated interval, to say how long
the file is so that persistent HTTP connections can be used,
and many other tasks.
 The most general way to specify headers is by
the setHeader method of HttpServletResponse, which takes
two strings: the header name and the header value.
 Like setting the status codes, this must be done before any
document content is sent.
Setting Response Header
setHeader(String headerName, String headerValue)
 This method sets the response header with the
designated name to the given value
setDateHeader(String header, long milliseconds)
 This method saves you the trouble of translating a Java
date in milliseconds since 1970 (as returned by
System.currentTimeMillis, Date.getTime, or
Calendar.getTimeInMillis) into a GMT time string
setIntHeader(String header, int headerValue)
 This method spares you the minor inconvenience of
converting an int to a String before inserting it into a
header.
HttpServletResponse Methods
setContentType(String mimeType)
 This method sets the Content-Type header and is used
by the majority of servlets.
setContentLength(int length)
 This method sets the Content-Length header, which is
useful if the browser supports persistent (keep-alive)
HTTP connections.
addCookie(Cookie c)
 This method inserts a cookie into the Set-Cookie
header
sendRedirect(String address)
 It sets the Location header as well as setting the
status code to 302
HTTP 1.1 Response Headers
Allow
 The Allow header specifies the request methods (GET,
POST, etc.) that the server supports
Cache-Control
 This header specifies the circumstances in which the
response document can safely be cached. It can have
values public, privateor no-cache etc. Public means
document is cacheable, Private means document is for a
single user and can only be stored in private (non-shared)
caches and nocache means document should never be
cached.
Connection
 This header instructs the browser whether to use
persistent in HTTP connections or not.
 A value of close instructs the browser not to use
persistent HTTP connections and keepalive means using
persistent connections.
 Content-Disposition
 The Content-Disposition header lets you request that the
browser ask the user to save the response to disk in a file
of the given name
 Content-Language
 The Content-Language header signifies the language in which
the document is written
 The value of the header should be one of the standard
language codes such as en, en-us, da, etc
 Content-Length
 This header indicates the number of bytes in the response
Content-Type
 The Content-Type header gives the MIME
(Multipurpose Internet Mail Extension) type of the
response document
Last-Modified
 This very useful header indicates when the document
was last changed
Location
 This header, which should be included with all
responses that have a status code in the 300s
Set-Cookie
 The Set-Cookie header specifies a cookie associated
with the page. Each cookie requires a separate Set-
Cookie header
Refresh
 This header indicates how soon (in seconds) the
browser should ask for an updated page. For
example, to tell the browser to ask for a new copy in
30 seconds, you would specify a value of 30 with
 response.setIntHeader("Refresh", 30);
Expires
 This header specifies the time at which the content should
be considered out-of-date and thus no longer be cached.
Retry-After
 This header can be used in conjunction with a 503 (Service
Unavailable) response to tell the client how soon it can
repeat its request.
WWW-Authenticate
 This header is required in responses that have a 401
(Unauthorized) status line.
Using servlet to Generate jpeg images
 two main steps servlets have to perform to build multimedia
content.
 Inform the browser of the content type they are sending.
To accomplish this task, servlets set the Content-Type
response header by using the setContentType method of
HttpServletResponse .
 Send the output in the appropriate format. This format
varies among document types, of course, but in most cases
you send binary data, not strings as you do with HTML
documents. therefore, servlets will usually get the raw
output stream by using the getOutputStream method,
rather than getting a PrintWriter by using getWriter .
 Putting these two steps together, servlets that generate non-
HTML content usually have a section of their doGet or
doPost method that looks like this:
 response.setContentType(" type / subtype ");
 OutputStream out = response.getOutputStream();
The specific steps required to generate JPEG images.
1. Create a BufferedImage .
 You create a java.awt.image.BufferedImage object by calling the
BufferedImage constructor with a width, a height, and an image
representation type as defined by one of the constants in the
BufferedImage class.
 The representation type is not important, since we do not manipulate the
bits of the BufferedImage directly and since most types give in identical
results when converted to JPEG.
 We use TYPE_INT_RGB . Putting this all together, here is the normal
process:
int width = ...;
int height = ...;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
2.Draw into the BufferedImage .
 You accomplish this task by calling the image's getGraphics
method, casting the resultant Graphics object to Graphics2D ,
then making use of Java 2D's rich set of drawing operations,
coordinate transformations, font settings, and fill patterns to
perform the drawing.
 Here is a simple example.
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.set Xxx (...);
g2d.fill( someShape );
g2d.draw( someShape );
3. Set the Content-Type response header.
you use the setContentType method of
HttpServletResponse for this task.
The MIME type for JPEG images is image/jpeg .
Thus, the code is as follows .
response.setContentType("image/jpeg");
4. Get an output stream.
As discussed previously, if you are sending binary
data, you should call the getOutputStream method
of HttpServletResponse rather than the getWriter
method.
For instance:
OutputStream out = response.getOutputStream();
5.Send the BufferedImage in JPEG format to the
output stream.
 When you use the ImageIO class, you just pass a BufferedImage , an
image format type ( "jpg" , "png" , etc.call
ImageIO.getWriterFormatNames for a complete list), and either an
OutputStream or a File to the write method of ImageIO .
 Except for catching the required IOException.
try
{
ImageIO.write(image, "jpg", out);
}
catch(IOException ioe)
{
System.err.println("Error writing JPEG file: " + ioe);
}

More Related Content

What's hot

Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...
Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...
Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...notesapps.org
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2Ben Abdallah Helmi
 
Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...
Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...
Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...ChristopherBow2
 
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocpIsabella789
 
Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...Woodruff Solutions LLC
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity FrameworksRich Helton
 
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Massimo Cenci
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injectionamiable_indian
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)SqliChema Alonso
 
Learning How to Shape and Configure an OData Feed for High Performing Web Sit...
Learning How to Shape and Configure an OData Feed for High Performing Web Sit...Learning How to Shape and Configure an OData Feed for High Performing Web Sit...
Learning How to Shape and Configure an OData Feed for High Performing Web Sit...Woodruff Solutions LLC
 
A-Project Report- SSIS
A-Project Report- SSISA-Project Report- SSIS
A-Project Report- SSISYubaraj Khanal
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookiesMahmoudOHassouna
 

What's hot (20)

Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...
Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...
Doc Ext Configs - free application to manage data in IBM ( Lotus ) Notes / Do...
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
 
Database Connection Pane
Database Connection PaneDatabase Connection Pane
Database Connection Pane
 
Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...
Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...
Designing Database Solutions for Microsoft SQL Server 2012 2012 Microsoft 70-...
 
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
 
Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
 
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
Recipes 8 of Data Warehouse and Business Intelligence - Naming convention tec...
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
SQL2SPARQL
SQL2SPARQLSQL2SPARQL
SQL2SPARQL
 
Sql injection
Sql injectionSql injection
Sql injection
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)Sqli
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
Learning How to Shape and Configure an OData Feed for High Performing Web Sit...
Learning How to Shape and Configure an OData Feed for High Performing Web Sit...Learning How to Shape and Configure an OData Feed for High Performing Web Sit...
Learning How to Shape and Configure an OData Feed for High Performing Web Sit...
 
A-Project Report- SSIS
A-Project Report- SSISA-Project Report- SSIS
A-Project Report- SSIS
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 

Similar to Servlet unit 2

Servlets http-status-codes
Servlets http-status-codesServlets http-status-codes
Servlets http-status-codesRachana Joshi
 
HTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive ListHTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive ListMainstreethost
 
Jsp server response
Jsp   server responseJsp   server response
Jsp server responsechauhankapil
 
BITM3730Week9(1).pptx
BITM3730Week9(1).pptxBITM3730Week9(1).pptx
BITM3730Week9(1).pptxMattMarino13
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Sun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideSun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideAlberto Romero Jiménez
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdfZani10
 
Jsp server response
Jsp   server responseJsp   server response
Jsp server responsechauhankapil
 
6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring FrameworkArcadian Learning
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1Aleh Struneuski
 
BITM3730 Networking.pdf
BITM3730 Networking.pdfBITM3730 Networking.pdf
BITM3730 Networking.pdfMattMarino13
 
BITM3730 11-1.pptx
BITM3730 11-1.pptxBITM3730 11-1.pptx
BITM3730 11-1.pptxMattMarino13
 
Web Application Technologies
Web Application TechnologiesWeb Application Technologies
Web Application TechnologiesSehan Lee
 

Similar to Servlet unit 2 (20)

Servlets http-status-codes
Servlets http-status-codesServlets http-status-codes
Servlets http-status-codes
 
Troubleshooting.pptx
Troubleshooting.pptxTroubleshooting.pptx
Troubleshooting.pptx
 
HTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive ListHTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive List
 
Jsp server response
Jsp   server responseJsp   server response
Jsp server response
 
BITM3730Week9(1).pptx
BITM3730Week9(1).pptxBITM3730Week9(1).pptx
BITM3730Week9(1).pptx
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
 
Web technology Unit-I Part D - message format
Web technology Unit-I  Part D - message formatWeb technology Unit-I  Part D - message format
Web technology Unit-I Part D - message format
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Sun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguideSun certifiedwebcomponentdeveloperstudyguide
Sun certifiedwebcomponentdeveloperstudyguide
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Servlets
ServletsServlets
Servlets
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf
 
Jsp server response
Jsp   server responseJsp   server response
Jsp server response
 
6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework6 Months Industrial Training in Spring Framework
6 Months Industrial Training in Spring Framework
 
Hypertext Transfer Protocol
Hypertext Transfer ProtocolHypertext Transfer Protocol
Hypertext Transfer Protocol
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1
 
BITM3730 Networking.pdf
BITM3730 Networking.pdfBITM3730 Networking.pdf
BITM3730 Networking.pdf
 
BITM3730 11-1.pptx
BITM3730 11-1.pptxBITM3730 11-1.pptx
BITM3730 11-1.pptx
 
Web Application Technologies
Web Application TechnologiesWeb Application Technologies
Web Application Technologies
 
Servlets intro
Servlets introServlets intro
Servlets intro
 

More from Shree M.L.Kakadiya MCA mahila college, Amreli

More from Shree M.L.Kakadiya MCA mahila college, Amreli (20)

Machine Learning by Rj
Machine Learning by RjMachine Learning by Rj
Machine Learning by Rj
 
Listeners and filters in servlet
Listeners and filters in servletListeners and filters in servlet
Listeners and filters in servlet
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
Motion capture by Rj
Motion capture by RjMotion capture by Rj
Motion capture by Rj
 
Research paper on big data and hadoop
Research paper on big data and hadoopResearch paper on big data and hadoop
Research paper on big data and hadoop
 
Text processing by Rj
Text processing by RjText processing by Rj
Text processing by Rj
 
Python and data analytics
Python and data analyticsPython and data analytics
Python and data analytics
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Database programming
Database programmingDatabase programming
Database programming
 
CGI by rj
CGI by rjCGI by rj
CGI by rj
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
Seminar on Project Management by Rj
Seminar on Project Management by RjSeminar on Project Management by Rj
Seminar on Project Management by Rj
 
Spring by rj
Spring by rjSpring by rj
Spring by rj
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Leadership & Motivation
Leadership & MotivationLeadership & Motivation
Leadership & Motivation
 
Event handling
Event handlingEvent handling
Event handling
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Servlet unit 2

  • 1. •Generating the Server Response, HTTP Status Codes, Specifying Status Codes, •HTTP / 1.1 Status Codes, Using Redirections, • HTTP Response Headers, •Setting Response Headers from Servlets, •Understanding HTTP / 1.1 Response Headers, •Using Servlets to Generate JPEG Images
  • 2. Generating the Server Response  when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document.  A typical response looks like this:
  • 3.
  • 4. The status line consists of the  HTTP version (HTTP/1.1 in the example),  a status code (200 in the example),  and a very short message corresponding to the status code (OK in the example)
  • 5. Servlets can perform a variety of important tasks by manipulating the status line and the response headers. For example,  they can forward the user to other sites;  indicate that the attached document is an image, Adobe Acrobat file, or HTML file;  tell the user that a password is required to access the document;  and so forth
  • 6. HTTP Status Codes  100 Continue  200 OK  202 Accepted  400 Bad Request  401 Unauthorized  404 Not Found  500 Internal Server Error
  • 7. Specifying Status Codes  The HTTP response status line consists of an HTTP version, a status code, and an associated message.  The message is directly associated with the status code and the HTTP version is determined by the server, all a servlet needs to do is to set the status code.
  • 8. A code of 200 is set automatically, so servlets don't usually need to specify a status code at all. When they do want to, they use  response.setStatus,  response.sendRedirect,  or response.sendError.
  • 9. Setting Arbitrary Status Codes: setStatus  When you want to set an arbitrary status code, do so with the setStatus method of HttpServletResponse  The setStatus method takes an int (the status code) as an argument
  • 10. 302 : sendRedirect public void sendRedirect(String url)  The 302 status code directs the browser to connect to a new location.  The sendRedirect method generates a 302 response along with a Location header giving the URL of the new document.
  • 11. 404:sendError  public void sendError(int code, String message)  The 404 status code is used when no document is found on the server.  The sendError method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client.
  • 12. HTTP / 1.1 Status Codes  100–199  Codes in the 100s are informational, indicating that the client should respond with some other action.  200–299  Values in the 200s signify that the request was successful.  300–399  Values in the 300s are used for files that have moved and usually include a Location header indicating the new address.
  • 13. 400–499  Values in the 400s indicate an error by the client 500–599  Codes in the 500s signify an error by the server
  • 14.  100 (Continue)  If the server receives an Expect request header with a value of 100-continue, it means that the client is asking if it can send an attached document in a follow-up request. This status code is new in HTTP 1.1.  200 (OK)  A value of 200 (SC_OK) means that everything is fine; the document follows for GET and POST requests.  This status is the default for servlets;  if you don't use setStatus, you'll get 200.
  • 15.  202 (Accepted)  A value of 202 (SC_ACCEPTED) tells the client that the request is being acted upon but processing is not yet complete.  204 (No Content)  A status code of 204 (SC_NO_CONTENT) stipulates that the browser should continue to display the previous document because no new document is available.  This behavior is useful if the user periodically reloads a page by pressing the Reload button and you can determine that the previous page is already up-to-date
  • 16.  205 (Reset Content)  A value of 205 (SC_RESET_CONTENT) means that there is no new document but the browser should reset the document view.  Thus, this status code is used to instruct browsers to clear form fields.  It is new in HTTP 1.1.  301 (Moved Permanently)  The 301 (SC_MOVED_PERMANENTLY) status indicates that the requested document is elsewhere;  the new URL for the document is given in the Location response header.  Browsers should automatically follow the link to the new URL.
  • 17. 302 (Found)  This value is similar to 301, except that in principle the URL given by the Location header should be interpreted as a temporary replacement, not a permanent one 303 (See Other)  The 303 (SC_SEE_OTHER) status is similar to 301 and 302, except that if the original request was POST, the new document (given in the Location header) should be retrieved with GET
  • 18. 400 (Bad Request)  A 400 (SC_BAD_REQUEST) status indicates bad syntax in the client request 401 (Unauthorized)  A value of 401 (SC_UNAUTHORIZED) signifies that the client tried to access a password-protected page but that the request did not have proper identifying information in the Authorization header
  • 19. 403 (Forbidden)  A status code of 403 (SC_FORBIDDEN) means that the server refuses to supply the resource, regardless of authorization.  This status is often the result of bad file or directory permissions on the server. 404 (Not Found)  The infamous 404 (SC_NOT_FOUND) status tells the client that no resource could be found at that address
  • 20.  405 (Method Not Allowed)  A 405 (SC_METHOD_NOT_ALLOWED) value signifies that the request method (GET, POST, HEAD, PUT, DELETE, etc.) was not allowed for this particular resource.  This status code is new in HTTP 1.1.  415 (Unsupported Media Type)  A value of 415 (SC_UNSUPPORTED_MEDIA_TYPE) means that the request had an attached document of a type the server doesn't know how to handle.  This status code is new in HTTP 1.1.
  • 21.  417 (Expectation Failed)  If the server receives an Expect request header with a value of 100-continue, it means that the client is asking if it can send an attached document in a follow-up request.  In such a case, the server should either respond with this status (417) to tell the browser it won't accept the document or use 100 (SC_CONTINUE) to tell the client to go ahead.  This status code is new in HTTP 1.1.
  • 22.  500 (Internal Server Error)  500 (SC_INTERNAL_SERVER_ERROR) is the generic "server is confused" status code  501 (Not Implemented)  The 501 (SC_NOT_IMPLEMENTED) status notifies the client that the server doesn't support the functionality to fulfill the request
  • 23.  503 (Service Unavailable)  A status code of 503 (SC_SERVICE_UNAVAILABLE) signifies that the server cannot respond because of maintenance or overloading  505 (HTTP Version Not Supported)  The 505 (SC_HTTP_VERSION_NOT_SUPPORTED) code means that the server doesn't support the version of HTTP named in the request line.  This status code is new in HTTP 1.1.
  • 24. sendRedirect()  The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.  It accepts relative as well as absolute URL.  It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.  Syntax of sendRedirect() method  public void sendRedirect(String URL)throws IOException;  Example of sendRedirect() method  response.sendRedirect("http://www.google.com");
  • 25. RequestDispatcher in Servlet  The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.  This interface can also be used to include the content of another resource also.  It is one of the way of servlet collaboration.  Syntax of getRequestDispatcher method  public RequestDispatcher getRequestDispatcher(String resource);  Example of using getRequestDispatcher method  RequestDispatcher rd=request.getRequestDispatcher("servlet2");  //servlet2 is the url-pattern of the second servlet  rd.forward(request, response);//method may be include or forward
  • 26. Methods of RequestDispatcher interface  The RequestDispatcher interface provides two methods. They are:  public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.  public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
  • 27. response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.
  • 28. response of second servlet is included in the response of the first servlet that is being sent to the client.
  • 29.
  • 30. HTTP Response Headers  specifying headers can play a useful role even when no unusual status code is set.  Response headers can be used to specify cookies, to supply the modification date (for caching), to instruct the browser to reload the page after a designated interval, to say how long the file is so that persistent HTTP connections can be used, and many other tasks.  The most general way to specify headers is by the setHeader method of HttpServletResponse, which takes two strings: the header name and the header value.  Like setting the status codes, this must be done before any document content is sent.
  • 31.
  • 32. Setting Response Header setHeader(String headerName, String headerValue)  This method sets the response header with the designated name to the given value
  • 33. setDateHeader(String header, long milliseconds)  This method saves you the trouble of translating a Java date in milliseconds since 1970 (as returned by System.currentTimeMillis, Date.getTime, or Calendar.getTimeInMillis) into a GMT time string setIntHeader(String header, int headerValue)  This method spares you the minor inconvenience of converting an int to a String before inserting it into a header.
  • 34. HttpServletResponse Methods setContentType(String mimeType)  This method sets the Content-Type header and is used by the majority of servlets. setContentLength(int length)  This method sets the Content-Length header, which is useful if the browser supports persistent (keep-alive) HTTP connections.
  • 35. addCookie(Cookie c)  This method inserts a cookie into the Set-Cookie header sendRedirect(String address)  It sets the Location header as well as setting the status code to 302
  • 36. HTTP 1.1 Response Headers Allow  The Allow header specifies the request methods (GET, POST, etc.) that the server supports Cache-Control  This header specifies the circumstances in which the response document can safely be cached. It can have values public, privateor no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (non-shared) caches and nocache means document should never be cached.
  • 37. Connection  This header instructs the browser whether to use persistent in HTTP connections or not.  A value of close instructs the browser not to use persistent HTTP connections and keepalive means using persistent connections.  Content-Disposition  The Content-Disposition header lets you request that the browser ask the user to save the response to disk in a file of the given name
  • 38.  Content-Language  The Content-Language header signifies the language in which the document is written  The value of the header should be one of the standard language codes such as en, en-us, da, etc  Content-Length  This header indicates the number of bytes in the response
  • 39. Content-Type  The Content-Type header gives the MIME (Multipurpose Internet Mail Extension) type of the response document Last-Modified  This very useful header indicates when the document was last changed Location  This header, which should be included with all responses that have a status code in the 300s
  • 40. Set-Cookie  The Set-Cookie header specifies a cookie associated with the page. Each cookie requires a separate Set- Cookie header Refresh  This header indicates how soon (in seconds) the browser should ask for an updated page. For example, to tell the browser to ask for a new copy in 30 seconds, you would specify a value of 30 with  response.setIntHeader("Refresh", 30);
  • 41. Expires  This header specifies the time at which the content should be considered out-of-date and thus no longer be cached. Retry-After  This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. WWW-Authenticate  This header is required in responses that have a 401 (Unauthorized) status line.
  • 42. Using servlet to Generate jpeg images  two main steps servlets have to perform to build multimedia content.  Inform the browser of the content type they are sending. To accomplish this task, servlets set the Content-Type response header by using the setContentType method of HttpServletResponse .  Send the output in the appropriate format. This format varies among document types, of course, but in most cases you send binary data, not strings as you do with HTML documents. therefore, servlets will usually get the raw output stream by using the getOutputStream method, rather than getting a PrintWriter by using getWriter .
  • 43.  Putting these two steps together, servlets that generate non- HTML content usually have a section of their doGet or doPost method that looks like this:  response.setContentType(" type / subtype ");  OutputStream out = response.getOutputStream();
  • 44. The specific steps required to generate JPEG images. 1. Create a BufferedImage .  You create a java.awt.image.BufferedImage object by calling the BufferedImage constructor with a width, a height, and an image representation type as defined by one of the constants in the BufferedImage class.  The representation type is not important, since we do not manipulate the bits of the BufferedImage directly and since most types give in identical results when converted to JPEG.  We use TYPE_INT_RGB . Putting this all together, here is the normal process: int width = ...; int height = ...; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  • 45. 2.Draw into the BufferedImage .  You accomplish this task by calling the image's getGraphics method, casting the resultant Graphics object to Graphics2D , then making use of Java 2D's rich set of drawing operations, coordinate transformations, font settings, and fill patterns to perform the drawing.  Here is a simple example. Graphics2D g2d = (Graphics2D)image.getGraphics(); g2d.set Xxx (...); g2d.fill( someShape ); g2d.draw( someShape );
  • 46. 3. Set the Content-Type response header. you use the setContentType method of HttpServletResponse for this task. The MIME type for JPEG images is image/jpeg . Thus, the code is as follows . response.setContentType("image/jpeg");
  • 47. 4. Get an output stream. As discussed previously, if you are sending binary data, you should call the getOutputStream method of HttpServletResponse rather than the getWriter method. For instance: OutputStream out = response.getOutputStream();
  • 48. 5.Send the BufferedImage in JPEG format to the output stream.  When you use the ImageIO class, you just pass a BufferedImage , an image format type ( "jpg" , "png" , etc.call ImageIO.getWriterFormatNames for a complete list), and either an OutputStream or a File to the write method of ImageIO .  Except for catching the required IOException. try { ImageIO.write(image, "jpg", out); } catch(IOException ioe) { System.err.println("Error writing JPEG file: " + ioe); }