Wednesday, December 8, 2021

Servlet Packages & Servlet API

 Servlet Packages

Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Class path, you can compile servlets with the JDK's Java compiler or any other current compiler.

Servlet API:   There are two packages that are required to build servlets.

1. javax.servlet         2.javax.servlet.http.

In general javax.servlet package has all the classes/interfaces not directly tied to HTTP, and javax.servlet.http package has the classes/interfaces that deal with the http protocol.

 1. javax.servlet package:

There are number of interfaces and classes present in this package, they are described below.

Interfaces:

Servlet: Declares life cycle methods for a servlet ServletConfig: Allows servlets to get initialization parameters ServletContext: Enables servlets to log events ServletRequest: Used to read data from a 


Classs:

     GenericServlet: Implements the Servlet and ServletConfig

ServletInputStream: Provides an input stream for reading requests from a client ServletOutputStream: Provides an output stream for writing responses to a client. ServletException: Indicates that a servlet error occurred.


Following are the interfaces and their methods:

Servlet Interface:

void init(): Called when the servlet is initialized

void service(): Called to process a request from a client void destroy(): Called when the servlet is unloaded

ServletConfig getServletConfig(): Returns a ServletConfig object that contains any initialization parameters

String getServletInfo: Returns a string describing the servlet

ServletConfig Interface:

ServletContext getServletContext: Returns the context for this servlet.

String getInitParmeter(String param): Returns the value of the initialization parameter name param.

getInitParameterNames(): Returns all initialization parameter names

 ServletContext interface:

getAtrribute(String attr): Returns the value of the server attribute named attr. String 

getServiceInfo(): Returns information about the server.

Servlet getServlet(String sname): Returns the servlet named sname. getServletNames(): Returns the names of servlets in the server

 ServletRequest Interface:

String getParameter(String pname): Returns the value of the parameter named pname getParameterNames(): Returns the parameter names for this request

String[ ] getParameterValues(): Returns the parameter values for this request String getProtocol(): Returns a description of the protocol

String getServerName(): Returns the name of the serverIntgetServerPort():Returns the port number.

 

ServletResponse Interface:

PrinterWriter getWriter(): Returns a PrintWriter that can be used to write character data to the response.

ServletOutputStream getOutputStream(): Returns a ServletOutputStream that can be used to write binary data to the response.

 Following are the classes and their methods:

GenericServlet class implements Servlet and ServletConfig interface.

Methods: public void init(), public void destroy(), public abstract void service()

 

ServletInputStream class extends InputStream. It is implemented by the server and provides an input stream that a servlet developer can use to read the data from a client request. In addition to this, one more method is added which returns the actual number of bytes read Int readLine(byte[ ] buffer, int offset, int size)

 

ServletOutputStream class extends OutputStream. It defines the print() and println() methods, which output data to the stream.

 

ServletException class indicates that a servlet problem has occurred.

The class has the following contructor ServletException( ) & ServletException(String s)


 

2. javax.servlet.http package:

There are number of classes and interfaces present in this package, they are as follows:

 

Interface

HttpServletRequest: Enables servlets to read data from an HTTP request HttpServletResponse: Enables servlets to write data to an HTTP response. HttpSession: Allows session data to be read and written HttpSessionContext: Allows sessions to be managed

 

Class

HttpServlet: Provides methods to handle HTTP requests and responses Cookie: Allows state information to be stored on a client machine

Following are the interfaces and their methods description HttpServletRequest Interface

Cookie[ ] getCookies: Returns an array of the cookies in this request

String getMethod(): Returns the HTTP method for this request String getQueryString(): Returns any query string in the URL

String getRemoteUser(): Returns the name of the user who issued this request. String getRequestedSessionId(): Returns the ID of the session

String getServletPath(): Returns the part of the URL that identifies the servlet

 

HttpServletResponse Interface

Void addCookie(Cookie cookie): Adds cookie to the HTTP response. Void sendError(int c): Send the error code c to the client

Void sendError(int c , String s): Send the error code c and the message s Void sendRedirect(String url): Redirects the client to url

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.






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