Servlet Interfaces by R4R Team

Interfaces in javax.servlet package:
There are many interfaces in javax.servlet package. They are given below:

1)Servlet
2)ServletRequest
3)ServletResponse
4)RequestDispatcher
5)ServletConfig
6)ServletContext
7)SingleThreadModel
8)Filter
9)FilterConfig
10)FilterChain
11)ServletRequestListener
12)ServletRequestAttributeListener
13)ServletContextListener
14)ServletContextAttributeListener

1)Servlet interface:

Interface javax.servlet.Servlet is that interface which defines the ServletLife Cycle methods. So, all servlets must implement this interface, either directly or by extending a class which implements this interface. Instead of directly implementing the Servlet Interface, a servlet can also extend Class GenericServlet (which implements Servlet Interface), or can extend HttpServlet Class (which extends the GenericServlet class).

Methods of Interface Servlet:
init(ServletConfig config) : Called by the Web Container to initialize a servlet. Here, config is a ServletConfig object containing the servlet's configuration and initialization parameters

service(ServletRequest req, ServletResponse res) : Called by the Web Container to allow a servlet to respond to a request. Here, req is the ServletRequest object that contains the client's request and res is the ServletResponse object that contains the servlet's response.

destroy() : Called by the Web Container to clean up a servlet’s service.

getServletConfig() : Return a ServletConfig object, which contain the initialization parameter and startup configuration of a servlet.

getServletInfo() : Returns a string containing the details of a servlet, like author, version .

Example:  Servlet interface implementation:

import java.io.*;

import javax.servlet.*;

public class First implements Servlet{

ServletConfig config=null;

public void init(ServletConfig config){

this.config=config;

System.out.println("servlet is initialized");

}

public void service(ServletRequest req,ServletResponse res)

throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();

out.print("<html><body>");

out.print("<b>hello servlet</b>");

out.print("</body></html>");

}

public void destroy(){System.out.println("servlet is destroyed");}

public ServletConfig getServletConfig(){return config;}

public String getServletInfo(){return "r4r";}

}

2)ServletRequest:

The job of a servlet is to handle client request. Servlet API provides two important interface javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest to encapsulate client request. Implementation of these interface provide important information about client request to a servlet.
An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface:

There are many methods defined in the ServletRequest interface. Some of them are as given below:

                   Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.
public String[] getParameterValues(String name)  returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box.
java.util.Enumeration getParameterNames() returns an enumeration of all of the request parameter names.
public int getContentLength()  Returns the size of the request entity data, or -1 if not known.
public String getCharacterEncoding() Returns the character set encoding for the input of this request.
public String getContentType()  Returns the Internet Media Type of the request entity data, or null if not known.
public ServletInputStream getInputStream()  throws IOException Returns an input stream for reading binary data in the request body.
public abstract String getServerName() Returns the host name of the server that received the request.
public int getServerPort() Returns the port number on which this request was received

Example:

In this example, we will show how a parameter is passed to a servlet in request object from html page.

index.html

<form method="post" action="check">

Name <input type="text" name="user" >

<input type="submit" value="submit">

</form>

web.xml
 

<servlet>

<servlet-name>check</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>check</servlet-name>

<url-pattern>/check</url-pattern>

</servlet-mapping>

MyServlet.java:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

String user=request.getParameter("user");

out.println("<h2> Welcome "+user+"</h2>");

} finally {

out.close();

}}}

3)ServletResponse:

The ServletResponse interface contains various methods that enable a servlet to respond to the client requests. A servlet can send the response either as character or binary data. The PrintWriter stream can be used to send character data as servlet response, and ServletOutputStream stream to send binary data as servlet response. Here are the methods of ServletResponse interface:

1) java.lang.String getCharacterEncoding(): It returns the name of the MIME charset used in the response sent to the client.
2) java.lang.String getContentType(): It returns the response content type. e.g. text, html etc.
3) ServletOutputStream getOutputStream(): Returns a ServletOutputStream suitable for writing binary data in the response.
4) java.io.PrintWriter getWriter(): Returns the PrintWriter object.
5) void setCharacterEncoding(java.lang.String charset): Set the MIME charset (character encoding) of the response.
6) void setContentLength(int len): It sets the length of the response body.
7) void setContentType(java.lang.String type): Sets the type of the response data.
8) void setBufferSize(int size): Sets the buffer size.
9) int getBufferSize(): Returns the buffer size.
10) void flushBuffer(): Forces any content in the buffer to be written to the client.
11) boolean isCommitted(): Returns a boolean indicating if the response has been committed.
12) void reset(): Clears the data of the buffer along with the headers and status code.

Example:
In the below example, we have used setContentType() and getWriter() methods of ServletResponse interface.

index.html

<form action="mydetails" method="get">

User name: <input type="text" name="uname">

<input type="submit" value="login">

</form>

MyServletDemo.java

 

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class MyServletDemo extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException

{

res.setContentType("text/html");

PrintWriter pwriter=res.getWriter();

String name=req.getParameter("uname");

pwriter.println("User Details Page:");

pwriter.println("Hello "+name);

pwriter.close();

}}

web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>MyServletDemo</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>

<url-pattern>/mydetails</url-pattern>

</servlet-mapping>

</web-app>

Leave a Comment:
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!