First Servlet Example Login Screen Validation

First Servlet Example Login Screen Validation


After going through the introduction and architecture of servlets, let us write a simple Login Validation program. As you have seen in the architecture, there will be two programs – one running on client machine and the other on server.

Servlet Example explained in 10 steps

First let us write the client-side program.

I. Client Program – UserPass.html

<form method="get" action="http://localhost:8888/india/roses">

  • localhost: It is the system where Tomcat server is running. Here, localhost is treated as the server. In realtime, actual name of server comes.
  • 8888: It is the port number on which Tomcat is running.
  • india: It is the name of the folder you created and placed in web-app folder.
  • roses: It is the alias name of the Validation servlet given web.xml file.

Above steps are clearly explained in Step-by-Step Execution of Servlet in Tomcat.

II. Servlet program – Validation.java

Being the first Servlet Example, let us have a detailed discussion on each line.

1. import javax.servlet.*;

The above package is imported for the sake of class ServletException.

2. import javax.servlet.http.*;

The above package is imported for the abstract class
HttpServlet and interfaces HttpServletRequest and HttpServletResponse.

3. import java.io.*;

java.io package is needed for PrintWriter and IOException.

4. public class Validation extends HttpServlet

To write a servlet, it is required to extend the abstract class HttpServlet, like Applet is required to extend to write an applet.

Let us see the hierarchy of HttpServlet.

Servlet Example

From the above hierarchy, it can be understood that to develop a servlet there are three styles.

a) by implementing Servlet interface
b) by extending GenericServlet
c) by extending HttpServlet

The disadvantage of first style is, it is required to override all the abstract methods of the interface Servlet eventhough we are not interested (like the interface WindowListener to close a frame) in a few. The better approach is extending GenericServlet (like WindowAdapter to close the frame) which contains only one abstract method service(). It is enough to the programmer to override only this method. It is a callback method. GenericServlet was used by the programmers when HTTP protocol was not standardized for the Web. When the HTTP became a defacto standard for Web, HttpServlet was designed to suit more for HTTP protocol. HttpServlet is an abstact class but without any abstract methods (all are non-abstract methods). Even the service() method is non-abstract and infact with HttpServlet, the service() method can be replaced by the methods doGet() or doPost(). This we will see later.

The above code works fine even if GenericServlet is extended instead of HttpServlet.

5. public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

service() method is a callback method called automatically when the container loads the servlet for execution when the client request comes. The method takes two parameters – an object of interface HttpServletRequest and an object of interface HttpServletResponse and let us see what these interfaces meant to servlet.

a) HttpServletRequest interface

Following is the hierarchy.

Servlet Example

The first parameter can be either of ServletRequest or its sub-interface HttpServletRequest. We use ServletRequest as parameter when we extend GenericServlet and HttpServletRequest when HttpServlet is extended. The data send by the client (through HTML) finally reaches HttpServletRequest object after travelling intermittent stages. That is, req object of HttpServletRequest receives data sent by client. From this object, the servlet programmer can extract the data and can use for validation or other purposes as hereunder.

b) HttpServletResponse interface

Servlet Example

The second parameter can be either of ServletResponse or its sub-interface HttpServletResponse. We use ServletResponse as parameter when we extend GenericServlet and HttpServletResponse when HttpServlet is extended. The responsibility of the data to be sent (like valid or invalid etc.) to the client is taken care by HttpServletResponse. The programmer job is simply to pass the response messages (to be reached to client) to HttpServletResponse and actual sending is taken care by the container.

c) The service() method throws two checked exceptions of javax.servlet.ServletException and java.io.IOException.

6. res.setContentType("text/html");

setContentType(String) is a method of ServletResponse inherited by HttpServletResponse and its job is sending the information to client’s browser of how the response sent by the servlet is to be formatted. It is here is text or HTML. That is, the data sent to the client is either in text format (as in ("VALID")) or HTML format (as in (<b>INVALID</b>)). The difference is HTML <b> tag. This is more called as setting the MIME (Multipurpose Internet Mail Extension) type. The other types can be of image/gif etc. which we use later.

7. PrintWriter out = res.getWriter();
8. out.println("VALID");

We know earlier the HttpServletResponse is meant to send data (known as response) to client. Being an interface, it cannot be used directly. As a convenience, the getWriter() method of ServletResponse (inherited by HttpServletResponse) returns an object of PrintWriter. println() is a method of PrintWriter used to attach a message, here, as a string parameter. This string message (here, VALID OR INVALID) is ultimately sent to client by the HttpServletResponse.

9. String str1 = req.getParameter("t1");

We know the data sent by client (known as request) finally reaches HttpServletRequest. getParameter(String) method of ServletRequest (inherited by HttpServletRequest) takes a string parameter and returns a string. The parameter is nothing but the <FORM> field name (here, t1) and the returned string value is what user entered in field t1. Using getParameter() method, the programmer extracts all the data sent by the client. The other way is getParameterNames() where all the data is extracted in a single stretch in a for loop.

10. out.close();

When the job is over, it is customary to close the streams as you have done in file copying.

image

image

Pass your comments to improve the tutorial First "Servlet Example Login Screen Validation".

22 thoughts on “First Servlet Example Login Screen Validation

  1. Ankush

    Respected Sir,
    public void service(HttpServletRequest req, HttpServletResponse res);
    In above line HttpServletResponse is an interface and the object of this interface is created by the web container.
    PrintWriter out = res.getWriter();
    Now getwriter() is method of HttpServletResponse that returns the object of printWriter(). Now the qus is ,who give the definion to this getWriter() method i think it may be a subclass that implements HttpServletResponse interface.

  2. phani

    Good morning sir, I did Validation program but it is showing status : 404 the required resource is not availble.i checked all the mapping, html but cant identify my mistake please help me.

  3. vivek

    Sir,
    what is ‘x’ in
    import javax.servlet.*;
    import javax.servlet.http.*;
    Actually we are using package called java. – . – ;
    why we need to write ‘x’ in that package javax. – . – ??

  4. Sandhya

    Respected sir,
    I have tried my best to execute above Servlet program as my first servlet program in Netbeans but only html program is executing and then it returns status code as 404(error).How to troubleshoot it?
    Thank you sir.

  5. Sandhya

    Respected sir,
    Sorry,I have not seen that you have already mentioned in your First servlet program about a point that service() is a non-abstract method in HttpServlet and it can be replaced by doGet() or doPost() methods.

  6. Sandhya

    Respected sir,
    Sorry,because I did not see that you have written in your blog that service() is non-abstract method in HttpServlet and can be replaced by 2 non-abstract methods doPost() and doGet().

  7. Sandhya

    Respected sir,
    In this servlet program ( Validation.java ),you have written abstract method service() by extending HttpServlet abstract class.
    Can we write like this?
    I am asked this because you have written in explanation that abstract class
    GenericServlet has only abstract method service().And abstract class HttpServlet has 2 non-abstract methods doGet() and doPost() but not service().
    Thank you sir.

      1. Sandhya

        Respected sir,
        service() is an non-abstract method in HttpServlet and it is abstract method in GenericServlet
        Thank you for clearing my doubt.
        God bless you sir.

Leave a Reply

Your email address will not be published. Required fields are marked *