Architecture of Java Servlet, Java Servlet example explained

Leave a Comment

Here is simple Servlet which can be written in Notepad and saved using .java extension.

Java program [FirstServlet.java]

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
  response.setContentType("text/html");
  PrintWriter out= response.getWriter();
  out.println("<html>");
  out.println("<head>");
  out.println("<title>My First Servlet</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h1>Hello How are U?</h1>");
  out.println("<h2>I am enjoying this Servlet Application</h2>");
  out.println("<h3>See You later!</h3>");
  out.println("</body>");
  out.println("</html>");
}
}

In the above program, we have imported following files,
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

Out of these files java.io package is useful for taking care of I/O operations. The javax.servlet and javax.servlet.http are impotant packages containing the classes and interfaces that are required for the operation of servlets. The most commonly used interface from javax.servlet package is Servlet. Similarly most commonly used class in this package is GenericServlet. The ServletRequest and ServletResponse are another two commonly used interfaces defined in javax.servlet package.

In the javax.servlet.http package HttpServletRequest and HttpServletResponse are two commonly used interfaces. The HttpServletRequest enables the servlet to read data HTTp response. The cookie and HttpServlet are two commonly used classes that are defined in this package.

We have given class name FirstServlet which should be derived from the class httpServlet. (Sometimes we can derive our class from GenericServlet).

Then we have defined doGet method to which the HTTP request and response are passed as parameters. The commonly used basic exceptions for the servlets are IOException and ServletException.

The MIME type is specified as using the setContentType() method. This method sets the content type for the HTTP response to type. In this method "text/html" is specified as the MIME type. This means that the browser should interpret the contents as the HTMl source code.

Then an output stream is created the output stream is created using PrintWriter(). The getWriter() method is used for obtaining the output stream. Anything written to this stream is sent to the client as a response. Hence using the object of output stream 'out', we can write the HTML source code in println metod as HTTP response.

0 comments:

Post a Comment