Saturday, 6 May 2017

Servlets Tutorial for Beginners

Introduction to SERVLETS:

  1. A servlet is a Java class that extends an application hosted on a web server.
  2. Servlet technology is used to create web application 
  3. Servlet Handles the HTTP request-response process.
  4. Often it thought of as an applet that runs on a server.
  5. Provides a component base architecture for web development, using the Java Platform
  6. Servlet technology is a technology which is robust and scalable only because of java language.
Java Servlets are basicallly the programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or others HTTP clients and databases or applications on the HTTP servers.
With the help of Servlets, you can easily collect input from the users through web page forms, present records from the database or any another source, and can create dynamic web pages.


Advantages of Servlets:
  1. Servlets are platform-independent because they are written in Java.
  2. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
  3. Performance is significantly better than CGI(Common Gateway Interface).
  4. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
  5. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms.
Servlet Architecture:
Servlet Architecture

Environment setup for servlet:

You need to set up tomcat server before running servlet.You can check my blog that is made on working of tomcat server by using below link.


After setting environment for tomcat you can easily make your first servlet.

Lifecycle of Servlet:

The javax.servlet.Servlet is a that interface defines the life cycle methods of servlet such as init(), service() and destroy(). The Web container is responsible for invoking the init(), service() and destroy() methods of a servlet during the life cycle.
  1.  The servlet is initialized by calling the init () method.
  2.  The servlet calls service() method for processing a client's request.
  3.  The servlet is terminated or destroyd by calling the destroy() method.
  4.  The servlet is garbage collected by the garbage collector of the JVM.

There are different methods that are used during the life cycle of a servlet.Those methods are defined as given below;

1.The init() Method:The init() method is called during the initialization phase of the servlet life cycle. The Web container first maps the requested URL to the corresponding servlet available in the Web container and then instantiates the servlet. The Web container creates an object of the ServletConfig interface, which contains the startup configuration information, such as the initialization parameters of the servlet. The Web container then calls the init() method of the servlet and passes the ServletConfig object to that.

The init() method throws a ServletException if the Web container cannot initialize the servlet resources. Following syntax shows the use of init() method:

public void init() throws ServletException 
{
 // Your Initialization code... 
}

2.The service() Method:The service() method is basically responsible for processing the client requests. Each time the Web container receives a client request, it invokes the service() method of the servlet. The service() method is invoked only after the initialization of the servlet is done or complete.The following code describes the use of service method 


public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException
{
}

The service() method always throws ServletException exception.The service() method throws IOException when an input or output exception occurs.
The service() method dispatches a client request to one of the request handler methods of the HttpServlet interface, such as the doGet(), doPost(), doHead() or doPut().The request handler methods then accepts the objects of the HttpServletRequest and HttpServletResponse as parameters from the service() method.


3.The doGet() Method:
The doGet() method processes client request, which is sent by the client, using the HTTP GET method. GET is a type of HTTP request method that is commonly used to retrieve static resources or the data. To handle client requests that are received using GET method, we need to override the doGet() method in the servlet class. In the doGet() method, we can retrieve the client information of the HttpServletRequest object. We can use the HttpServletResponse object to send the response back to the client. The following code snippet shows the doGet() method:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
}

4.The doPost() Method:
The doPost() method handles requests in a servlet, which is sent by the client, using the HTTP POST method. For example, if a client is doing registration in the form in an HTML form, the data can be sent using the POST method.The POST request sends the data as part of the HTTP request body that is not in case of GET method. As a result, the data sent does not appear as a part of URL.But in case of GET method the data which is entered by the user is attached as a part to the url.You can see your information attached to Url.
To handle requests in a servlet that is sent using the POST method,same we need to override the doPost() method as  we done in case of doGet() method. In the doPost() method, we can process the request and send the response back to the client. The following code describe the use of doPost() method.

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
}

5.The doHead() Method:
The doHead() method handles requests sent using the HTTP HEAD method. Similar in the case of GET method, the HEAD method also sends the requests to the server. The only difference between the GET and the HEAD method is that the HEAD method returns the header of the response, which contains information like as Content-Type, Content-Length, and Last-Modified. The HEAD method is mainly used to find whether a requested resource exists or not. It is also used to obtain information about the resource, such as type of the resource. This information is required before requesting for resource content. The use of doHead() method shown given below:


public void doHead(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
}

6.The doPut() Method:The doPut() method handles requests sent using the HTTP PUT method. The PUT method basically allows a client to store information on the server. The doPut() method usage can be defined as given below:

public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
}

7.The destroy() Method:
The destroy() method denotes the end of the life cycle of a servlet. The Web container calls the destroy() method before removing a servlet instance from the service. The Web container calls the destroy() method when the time period specified for the given servlet has  been elapsed. The time period of a servlet is defined as the period in which the servlet is kept in the active state by the Web container to service the client request.The Web container needs to release servlet instances to conserve memory so that it can be used for further uses.
In the destroy() method we can write the code to release the resources occupied by the servlet. The destroy() method can also used to save any persistent information before the servlet instance is removed from the service.The following code shows the destroy() method working:

public void destroy();

Steps to create simple servlet in netbeans:


1.Open netbeans,click on new project.
2.Select java Web in categories and web application in projects.
3.Name your project.
4.Select server you want to use.
5.Finish.
6.Right click on project,select new then servlet.
7.Name your servlet,then next.
8.You can select add information to deployment descriptor.
9.Last finish

After you have created your first servlet it looks like:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author Bsb
 */
@WebServlet(urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet 
{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet NewServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    } 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 @Override
    public String getServletInfo() {
        return "Short description";
    }
}


An example to print hello javacoders:

import java.io.*;
import javax.servlet.*; 
import javax.servlet.http.*;
public class HelloJava extends HttpServlet
{
 private String message; 
 public void init() throws ServletException 
 {
 message = "Hello JavaCoders"; 
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 {
 response.setContentType("text/html"); 
 PrintWriter out = response.getWriter(); 
out.println("<h1>" + message + "</h1>"); 
 }
 public void destroy()
 { 
 } 

Web.xml file of your servlet: This the file that describes us about the servlet name and servlet mapping name and url pattern of your servlet.There is another tag that is used to describe which page will open first when u run your project and that tag is welcome-file list.

<servlet> 
<servlet-name>HelloWorld</servlet-name> 
<servlet-class>HelloWorld</servlet-class> 
</servlet> 

 <servlet-mapping> 
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern> 
</servlet-mapping>

Welcome-file-list:
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

There are different codes that tells us about the nature of servelt.Some of which are:

100- Continue
101-Switching protocols
200- Ok
201- Created
202- Updated
203- Non-authoritative Information
204- No content
205- Reset content
206- Partial content

Servlet Debugging:
Sometimes, when we make servlets, we  make mistakes.Debugging servlets can be tricky because you don’t execute them directly. Instead, you trigger their execution by means of an HTTP request, and they are executed by the Web server.So, this is difficult to handle.So, approaches to servlet debugging differ somewhat from those used in general development. Here are some strategies that can make your life easier,and you can easily debug your servlet. 

1.Using print statements: If you run the server on your desktop, a window pops up that displays standard output (i.e., System.out.println statements in console output).
So, with the help of this you can easily test your code wher is problem coming through.It basically tell us how our program is operating. The init method doesn’t seem to work? Insert a print statement, restart the server, and see if the print statement is displayed in the standard output window. Perhaps you declared init incorrectly.If you areGeting a NullPointerException, Insert a couple of print statements to find out which line of code generated the error and which object on that line was prinitng null. 

2.Use the log file:. The HttpServlet class has a method called log that helps you write information into a logging file on the server. Reading debugging messages from the log file is a bit easy or convenient than watching them directly from a window.
But it is a opiton when you are running your servlet on a remote server, in that situations, print statements are not much useful and only advanced IDEs support remote debugging.The log method has two variations: one that takes a String, and the other that takes a String and a Throwable (mother class of Exception). The exact location of the log file is server-specific, but is generally clearly documented or can be found in subdirectories of the server installation directory.

3.Use Apache Log4J: Another option of debugging your servlet is use of Log4J.Log4J is a package from the Apache Jakarta Project—the same project that manages Tomcat and Struts (it is an MVC framework).With Log4J, you semi-permanently insert debugging statements in your code and use an XML-based configuration file to control which are invoked at request time. Log4J is fast, flexible, convenient, and becoming more popular by the day. For more details you can go to below link.

http://jakarta.apache.org/log4j/.

4.Stop and restart the server: The last method is to stop and then start the server.
Servers are usually keept in memory between requests. However, most servers support a development mode in which servlets are supposed to be automatically reloaded whenever their associated class file changes. 
The init method is run only when a servlet is first loaded, the web.xml file is read only when a Web application is first loaded and particulat Web application listeners are triggered only when the server becomes first starts. Restarting the server will simplify debugging in all of those situations.

Oracle / PLSQL: FOR LOOP

set serveroutput on; declare a1 varchar2(100); begin select count(*) into a1 from employees; for i in 1..a1 loop dbms_output.put_line...