Nearby lessons

28 of 34

Servlet - Examples: HTTP Methods & Response

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Programs demonstrating GET/POST methods, form parameters, request headers, and response MIME types.

Retrieving Form Parameters

It returns all values associated with the specified parameter.

If the specified parameter is not available then this method returns null.

Argument is case sensitive

Eg: String[] s = req.getParameterValues("course");

for(String s1: s)

{

SOP(s1);

}

Example01
Loading editor…

Retrieving Form Parameters

returns all form parameter names.

Example02
Loading editor…

Retrieving Form Parameters

returns Map object which contains all parameter names and values.

getParameter()

getParameterValues()

getParameterNames()

getParameterMap()

Example03
Loading editor…

Demo Program to retrieve Form Parameters

Example04
Loading editor…

FormDemoServlet.java

advapps1D

|-register.html

|-WEB-INF

|-classes

|-FormDemoServlet.class

Example05
Loading editor…

Retrieving Request Headers

2.accept-encoding: encoding types accepted by browser like gzip,dflate etc..

3.accept-language: languages types accepted by browser like un-en

4.user-agent: It represents the type of browser

5.cookie: used to send cookies for session management

etc...

utilities of request headers:

case-1:

By using accept-encoding request header,server can send compressed data instead of original

data.It reduces download time and improves performance.

Eg:

String encoding=req.getHeader("accept-encoding");

if(encoding.equals("gzip"))

{

send movie in gzip format

}

case-2:

By using user-agent request header,server can send browser specific customized response,so that

we can increase hit rate of our application.

String userAgent=req.getHeader("user-agent");

if(userAgent.equals("mozilla"))

{

provide mozilla compatible response

}

else if(userAgent.equals("chrome"))

{

provide chrome compatible response

}

case-3:

By using cookie request header,browser can send cookies to the server so that server can

implement session management.

Note:

Browser will send request headers and server can use these request headers to provide proper

response.

HttpServletRequest defines the following methods to retrieve header information at server side

Example06
Loading editor…

Retrieving Request Headers

returns value associated with specified request header

If the specified request header is not already available then we will get null

If the header associated with multiple values then this method returns only first value.

argument is case insensitive

Eg:

String userAgent=req.getHeader("USER-AGENT");

String userAgent=req.getHeader("user-agent");

Example07
Loading editor…

Retrieving Request Headers

returns all values associated with specified header.

If the specified header is not available then this method returns empty Enumeration object but

not null.

argument is not case sensitive

Example08
Loading editor…

Retrieving Request Headers

returns all header names associated with the request.

Example09
Loading editor…

Retrieving Request Headers

We can use this method if header associated with int value.

String length=req.getHeader("content-length");

int l = Integer.parseInt(length);

or

int l = req.getIntHeader("content-length");

Example10
Loading editor…

Retrieving Request Headers

We can use this method if header associated with Date value.

Returns Date value associated with the header as the number of milli seconds since jan 1st 1970.

If we pass these milliseconds as argument to Date constructor then we will get exact date.

1970 JAN 1st 12:00 AM

Milli Seconds

Date Value

Eg:

long l =req.getDateHeader("date");

Date d = new Date(l);

getHeader()

getHeaders()

getHeaderNames()

getIntHeader()

getDateHeader()

Demo Program to display all request headers information

Example11
Loading editor…

RequestHeaderDemoServlet.java

advapps1E

|-WEB-INF

|-classes

|-RequestHeaderDemoServlet.class

Example12
Loading editor…

Retrieving Client and Server information from the request

returns IP address of the client

Example13
Loading editor…

Retrieving Client and Server information from the request

returns the port number on which client is running

Example14
Loading editor…

Retrieving Client and Server information from the request

returns the server name to which request sent

Example15
Loading editor…

Retrieving Client and Server information from the request

returns port number at which server is running

Example16
Loading editor…

ClientServerInfoServlet.java

advapps1E

|-WEB-INF

|-classes

|-ClientServerInfoServlet.class

To Retrieve Form Parameters

Example17
Loading editor…

ClientServerInfoServlet.java

To Retrieve Request Headers

Example18
Loading editor…

ClientServerInfoServlet.java

Request5) getDateHeader()

Object

To Retrieve Cookies

Cookie() c = req.getCookies();

To Retrieve Client And Server Information

Example19
Loading editor…

ClientServerInfoServlet.java

Playing Games with Response Object

Objective:

By using HttpServletResponse interface,write code

  • To set Response headers
  • To set Content type of Response
  • To acquire Text Stream for response
  • To acquire Binary Stream for response
  • To redirect request to another url
  • To add cookies to the response
  • To set Response headers:

Http Response headers provides configuration information of the server and information about

the response like content-type,content-length etc

Browser will use these response headers to display response body properly to the end user.

HttpServletResponse interface defines the following methods to add headers to the response.

Example20
Loading editor…

ClientServerInfoServlet.java

If the specified header is already available then old value will be replaced with new value.

Example21
Loading editor…

ClientServerInfoServlet.java

If the specified header is already available then this new value also will be added to existing list

of values. In this case replacement won't be happend.

HttpServletResponse interface defines the following extra methods to add int and date headers.

Example22
Loading editor…

ClientServerInfoServlet.java

2.set content type of response:

ContentType header represents MIME type(multi purpose internet mail extension)of the

response.

Example23
Loading editor…

Demo Program to send HTML Response

Example24
Loading editor…

Demo Program to send Excel File as Response

Example25
Loading editor…

Demo Program to send Word File as Response

  • To acquire text stream for the response:

We can send text data as the response by using PrintWriter object.

We can get PrintWriter object by using getWriter() method of ServletResponse interface.

Eg:

PrintWriter out=resp.getWriter();

out.println("Hello this is text response from the servlet");

  • To acquire binary stream for the response:

We can send binary information(like video files,audio files,images etc..)as response by using

ServletOutputStream object.

We can create ServletOutputStream object by using getOutputStream() method of

ServletResponse interface.

Eg: ServletOutputStream os=resp.getOutputStream();

Example26
Loading editor…

BinaryStreamDemo1Servlet.java

advapps1G

|- sunny.jpg

|-WEB-INF

|-classes

|-BinaryStreamDemoServlet.class

Example27
Loading editor…

Demo Program to send Video file as Response

advapps1GA

|- dhoni.mp4

|-WEB-INF

|-classes

|-BinaryStreamDemoServlet.class

Note:

By using PrintWriter we can send text data as response but by using ServletOutputStream we can

send both text data and binary data as response.

Note:

Within the servlet we can get either PrintWriter or ServletOutputStream but not both

simultaneously.

If we are trying to get both then we will get RuntimeException saying IllegalStateException.

Eg:

public void doGet(..)...

{

PrintWriter out=resp.getWriter();

ServletOutputStream os = resp.getOutputStream();

}

RE: java.lang.IllegalStateException: getWriter() has already been called for this response

Example28
Loading editor…

FirstServlet.java

Example29
Loading editor…

SecondServlet.java

advapps1H

|-WEB-INF

|-classes

|-FirstServlet.class

|-SecondServlet.class

In the above example whenever we are sending the request to FirstServlet,SecondServlet will

provide required response b'z of redirection.

*Note:

After committing the response we are not allowed to perform redirection,otherwise we will get

RuntimeException saying IllegalStateException.(But this feature is not implemented by Tomcat)

Note: sendRedirection is happening at client side(browser side)

Eg of redirection:

Whenever we are sending the request to google.com, our request will be redirected to

google.co.in

Example30
Loading editor…

Adding Cookies to Response

To Set Content-Type of Response

resp.setContentType("text/html");

OR

resp.setHeader("Content-Type","text/html");

Response To Acquire Text Stream For Response

ObjectPrintWriter out = resp.getWriter();

To Acquire Binary Stream For Response

ServletOutputStream os =

resp.getOutputStream();

To Redirect Request to Another URL

resp.sendRedirect("/advapps1A/text");

OR

resp.setStatus(302);

resp.setHeader("Location", "/advapps1A/text ");

Example31
Loading editor…
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.