Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Servlets in Java

In this article we will talk about the servlets in java. We will see its operations and implementations.

The servlet is a server side program written in the java programming language.Servlet is a java class and is able to give the response to different kinds of requests because it runs in server side and it is also used in order to extend the applications which are usually hosted by different web servers.

Servlets give the response to the requests made by clients. It basically implements an interface known as a servlet interface and the functionality of web server is extended with the help of servlets. It runs on the server and is present in between the client and server. It is able to receive the requests from client side and response back being a server-sided program.The types of java servlets include HTTP servlets and generic or basic servlets.

The servlets are able to get the request from the client and after processing it can send the response to client from the server side back to the client.The life cycle of a servlet consists of three steps which includes init, service and destroy and the methods are init(), service() and destroy(). This is the life cycle of servlet and the methods present in it works in the following way; the init method is called by the container when the instance of servlet has been created successfully, when the request from a client has been received at the server side, the service method of servlet is called respectively and this service method invokes the methods of HTTP protocol including doGet() and doPost() depending on the requirements which are needed at the particular point in time and the life of the available servlet ends when the container calls the destroy method in order to finish the functionality and the services of the servlet.

The process of client and server is done in the following way; first the client initializes the request and this request is sent to server, the server sends this information of request to the servlet, the servlet first builds the response then pass the same to server respectively and this response is built in a dynamic form depending on the type of request made by the particular client and there is a possibility that the resources from external side like JDBC can be used and when this work of response is finalized then the server sends this same generated response back to client in order to finish the process.

The HTTP requests are handled and the response is sent to the client by the objects present in the servlet including request and response.The HTTP servlets can service get and post requests in a successful manner. The methods available in the HTTP servlets are present with respect to the HTTP protocol which includes the get, post, delete and others. The respective methods are called from the HTTP requests.Servlet API is available in the package of java and these javax.servlet.* and javax.servlet.http.* contains all classes of servlet and these are required to be imported in order to access all the related resources of a servlet. In simple words, the servlet is that in which HTML is required to be written inside the code of Java. The interface of servlet defines the methods which manage the servlets and the respective communication with clients.

There is no main method present in servlet. As the servlet is a java class so in order to be a servlet the respective class should extend HTTPServlet. There are separate methods for request and response and known as doGET and doPOST. Both of these request as well as the response methods takes two arguments known as HTTPServletRequest and HTTPServletResponse. The work is done by writing the println statements and these basically help in generating the required HTML webpage.

There is a configuration file and the name of this file is web.xml. The calls to the classes are inserted in this file so that when the web application runs it gets to know that which servlet class should be executed first and the information in the form of xml is inserted in it and after that what is required to be done including all the related details are provided in this configuration file.The request of each client is handled by a new thread from servlet side. The web server is responsible for the creation of new threads in order to handle the requests in a proper manner and this web server also helps to refresh the servlets. The @WebServlet annotation is used in order to define a servlet when the web application is created.

Importance of Servlets

Servlets are basically used in order to store data and apply processing on this stored data and this java class is also used in order to manage properly the information regarding state because HTTP is a stateless protocol. Servlet being a java class in J2EE has the ability to handle and communicate on different protocols of client-server but it is normally used with the protocol of HTTP and this is the reason it is also known as HTTP servlet. The dynamic content can be added by the developer to the web server in order to provide the functionality to process the requests and generate response. Servlets are able to maintain the state across different server functionalities and transactions and session variables are used in order to maintain the required state.

Web container or servlet container which basically deals with servlets and is actually the component of web server that is used in order to successfully run and deploy the servlet.The logic related to business application which is complex in its form can be implemented by the servlets which have an access to many APIs of Java.The developers are able to create the fast, interactive and efficient server side web applications with the use of servlets in an easy manner.

Screenshots:

Following are some of the screens which help in understanding the work of servlets:

Start of Servlet

Figure 1: Start of Servlet

This Figure 1 shows the current time and data of the system when the web application named in this case Servlets_Work runs successfully and displays the result in the browser.

Form work added to Servlet

Figure 2: Form work added to Servlet

The Figure 2 shows the form work added to the servlet of Figure-01 and it display the three labels, three textboxes and a button.

Entered Input by user

Figure 3: Entered Input by user

The Figue 3 shows the input entered by the user and values are saved in the strings in the web application and after the click of button “Enter Information of Person”, these values are retrieved and shown as above.

The Figure 4 below shows the successful output from the running web application. The values when the user has not entered, it appears null and after the values are entered and the button is clicked then these values are saved in different Strings and displayed in the console as well as the browser. These values can be inserted in the table of database system by establishing the connection with the available database system if the user wants.

Successful Output of Web Application (Servlets)

Figure 4: Successful Output of Web Application (Servlets)

Implementation & Codes:

The code given below contains the code of servlet class and the configuration file.

Listing 1: Customer_Servlet.java

packagecom.servlet.work;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Date;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class Customer_Servlet extends HttpServlet {
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
* <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
        Date d=new Date();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title style=\"background-color: green;\">Servlet Customer_Servlet</title>");            
out.println("</head>");
out.println("<body>");
out.println("<h1 style=\"background-color: green;\" >Servlet Customer_Servlet at " + request.getContextPath() + "</h1>");            
out.println("<h2>This servlet is responsible to display the current date and time of the system</h2>");
out.println("<p style=\"color:red; margin-right:100px;\">" + "Date and Time: "+ d.toString()+"</p>");
out.println("<form>");
out.println("Person_ID:<input type=text name=id><br>");
out.println("Person_Name:<input type=text name=personName><br>");
out.println("Person_Address:<input type=text name=personAddr><br>");
out.println("<input type=\"submit\" value=\"Enter Information of Person\">");
            String val=request.getParameter("id");
            String pname=request.getParameter("personName");
            String paddr=request.getParameter("personAddr");
out.println("<p>"+"You entered ID = "+val+"</p>");
out.println("<p>"+"You entered Name = "+pname+"</p>");
out.println("<p>"+"You entered Address = "+paddr+"</p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
System.out.println("ID: "+val+"\t"+"Name: "+"\t"+"Address: "+paddr);
        } finally {            
out.close();
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
* <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
processRequest(request, response);
    }
    /**
     * Handles the HTTP
* <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
processRequest(request, response);
    }
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
public String getServletInfo() {
return "Short description";
    }// </editor-fold>
}

The servlet code contains the work as presented in the screenshots above. The code in this class of servlet works and the function of processRequest is responsible to give the expected output and get the input from the form entered by the user.

Listing 2: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
<welcome-file>
Customer_Servlet
</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Customer_Servlet</servlet-name>
<servlet-class>com.servlet.work.Customer_Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Customer_Servlet</servlet-name>
<url-pattern>/Customer_Servlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
            50
</session-timeout>
</session-config>
</web-app>

The web.xml is a configuration file and contains the related information about the web application.

Hope you liked it. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login