Showing posts with label Sevlet Architecture. Show all posts
Showing posts with label Sevlet Architecture. Show all posts

Tuesday, December 7, 2021

Deploying the Servlet

 Deploying the Servlet


1. Create A directory Structure:

The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client.
The Sun Microsystems defines a unique standard to be followed by all the server vendors.

2)Create a Servlet

There are three ways to create the servlet.

  • By implementing the Servlet interface
  • By inheriting the GenericServlet class
  • By inheriting the HttpServlet class
Note: The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.


  3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

1) servlet-api.jaràApache Tomcat

2) weblogic.jaràWeblogic

3) javaee.jaràGlassfish

4) javaee.jaràJboss

  Two ways to load the jar file

1. set classpath

2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-INF/classes directory.

4)Create the deployment descriptor (web.xml file)

  The deployment descriptor is an xml file, from which Web Container gets the information about the serlvet to be invoked.

  The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull.

  There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program

  There are many elements in the web.xml file. Here is the illustration of some elements that is used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5)Start the Server and deploy the project

  To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.

  One Time Configuration for Apache Tomcat Server

  You need to perform 2 tasks:

  set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).

  Change the port number of tomcat (optional). It is required if another server is running on same port (8080).

5) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat

6) How to access the servlet

Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. 

For example:

http://localhost:9999/demo/welcome

Example:
Step1: Create one folder name: Servlets
Step2: Under Servlets folder load below html file .

index.html

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

Enter Name:<input type="text" name="tf1"/><br>

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

</form>

Step3: under Servlets folder ,create another folder with name as "WEB-INF"

Step4: in WEB-INF folder, create one more file named as web.xml like this.

 web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>

Stpe5: under WEB-INF, create one more folder namely "classes".
Step6: in  "classes" folder , load below java file and name it as TestServlet.java.
TestServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out= res.getWriter();
String s1=req.getParameter("tf1");
out.print("<h1> Welcome"+s1+"</h1>");
out.close();
}
}
Step7: copy this Servlet folder into "C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps".
Step8: Execute the java file from webapps folder
Step9: Start the tomcat server by typing localhost:8080 in your browser's URL.
Step10: after starting of tomcat server, deploy your servlet using localhost:8080/'folder-name'


Life Cycle of Servlet

 Life Cycle of Servlet

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

 The servlet is initialized by calling the init() method.

The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method.

Finally, servlet is garbage collected by the garbage collector of the JVM. Now let us discuss the life cycle methods in details.



The init() method:

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

 The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

 The init method definition looks like this:

public void init() throws ServletException

{

// Initialization code...

}

The service() method:

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service.

 The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse  response) Throws ServletException, IOException

{

}

 The service() method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

 

The doGet() and doPost() are most frequently used methods within each service request. Here is the signature of these two methods.

 

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet()method.

 public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{// Servlet code

}

 The doPost() Method: A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.

 public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{

// Servlet code

}

 The destroy() method:The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:

 public void destroy()

{

// Finalization code...

}

 

 

 HTTP Request and HTTP Response

In HTTP Request, the first line is called as Request line. It consist of 3 Parts, They are

 1. Method     2.URL     3.Version

In HTTP Response, the first line is called as Status line. It consist of 3 Parts, They are

 1.    Version     2.Status Code      3.Phrase (Description of Status code)

 

MIME Headers: MIME (Multi-Purpose Internet Mail Extensions) is an extension of the original Internet e-mail  protocol that lets people use the protocol to exchange different kinds of data files on the Internet: audio, video, images, application programs, and other kinds.

 


                         HTTP Request Message Example

HTTP Response Message Example

The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role. There are 5 values for the first digit:

1xx: Informational Responses - Request received, continuing process

2xx: Success - The action was successfully received, understood, and accepted

3xx: Redirection - Further action must be taken in order to complete the request

4xx: Client Errors - The request contains bad syntax or cannot be fulfilled

5xx: Server Errors - The server failed to fulfil an apparently valid request.

















A simple Java program to find the inverse of a given matrix

  import java.util.Scanner; public class MatrixInverse { public static void main (String[] args) { Scanner scanner =...