Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. 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.

















Servlet Architecture

 Servlets Architecture

Servlets perform the following major tasks:

 1. Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.


2.Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.


3. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.


4. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.


5. Send the implicit HTTP response to the clients (browsers).


6.This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.






Http Request and Http Response

 Differences between Servlet and CGI

Servlet

CGI

In    Servlets      each      request       is    handled       by lightweight Java Thread(Multi threaded)

In CGI each request is handled by heavy weight OS process.

Servlets are Platform Independent.

CGI is not Platform Independent.

Servlets are portable.

CGI is not portable.

Servlets can link directly to the Web server

CGI cannot directly link to Web server.

Servlets can handle cookies

CGI cannot handle cookies

Servlets can track sessions

CGI cannot track sessions

Servlets are inexpensive than CGI

CGI is more expensive than Servlets

Servlets are more secure than CGI

CGI programs can be more vulnerable to attacks than Servlets











CGI (Common Gateway Interface)

 CGI (Common Gateway Interface)

The common gateway interface (CGI) is a standard way for a Web server to pass a Web user's request to an application program and to receive data back to forward to the user. These programs allow a Web developer to deliver dynamic information (usually in the form of HTML) via the browser. A CGI program can be written in any language, including Java that can be executed by your Web server.

The performance issues in the platform-dependent CGI programs let to the introduction of Servlets. Servlets are platform-independent. The main purpose of a servlet is to collect the request from the client and generate the requested web page dynamically for a corresponding request and send it back to the client. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI).

Server has to create a new CGI process for every client request. For example, If 100 users are accessing the web application, and then the server has to create 100 CGI processes to handle the request made by them. Since a server has limited resources, creating new process every time for a new request is not a viable option, this imposed the limitation on server, due to that the server cannot handle more than a specified number of users at the same time. The CGI programs are memory intensive programs.

CGI Environmental Variables:

Environment variables are a series of hidden values that the web server sends to every CGI program you run.


Key

Value

HTTP_COOKIE

The visitor's cookie, if one is set

HTTP_HOST

The hostname of the page being attempted

HTTP_USER_AGENT

The browser type of the visitor

PATH

The system path your server is running under

REMOTE_ADDR

The IP address of the visitor

REMOTE_HOST

The hostname of the visitor

REMOTE_PORT

The port the visitor is connected to on the web server

REMOTE_USER

The visitor's username (for .htaccess-protected pages)

REQUEST_METHOD

GET or POST

SERVER_NAME

Your server's fully qualified domain name (e.g.

www.cgi101.com)

SERVER_PORT

The port number your server is listening on


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 =...