Skip to main content

HttpServletRequest and HttpServletResponse object

HttpServletRequest

  • HttpServletRequest is an Interface in java which extends another interface javax.servlet.ServletRequest.
  • There are two method present in ServletRequest interface and it is used get information from request object.
  1. getparameter();
  2. getparametervalues()
  • getparameter() return String and getparametervalues() return String Array.
  • These both methods return null  if parameter name does not exist.
  • It is called Request object and it provides information about request.

HttpServletResponse

  • HttpServletResponse is an Interface in java which extends another interface javax.servlet.ServletResponse.
  • setContentType() is a  method of ServletResponse.
  • This method help us to provide content type information in response.
  • This HttpServletResponse object is used to send response information.

How to provide Content Information

  • To provide content information We should get Printwriter object from Response object by invoking a method getwriter()
  • Printwriter has method by name Print() and Println() which help us to add actual content to response object.
  • See below Example
Servlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.spy.javaforlearn;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
public class FirstServlet extends HttpServlet 
 
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		         throws ServletException, IOException 
     {
 
         response.setContentType("text/html");
 
    	 PrintWriter out= response.getWriter();</span>
 
    	 out.println("<h1>Welcome to javaforlearn.com<h1>");
 
     }
}