Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Java Servlet

  Java Servlets

Why server-side programming?


Though it is technically feasible to implement almost any business logic using client-side programs, logically or functionally it carries no ground when it comes to enterprise applications (e.g. banking, air ticketing, e-shopping, etc.). To further explain, going by the client-side programming logic; a bank having 10,000 customers would mean that each customer should have a copy of the program(s) in his or her PC which translates to 10,000 programs! In addition, there are issues like security, resource pooling, concurrent access, and manipulations to the database which simply cannot be handled by client-side programs. The answer to most of the issues cited above is – “Server Side Programming”. Figure 1 illustrates Server-side architecture in the simplest terms.


serversideprogramming

Advantages of Server Side Programs

The list below highlights some of the important advantages of Server Side programs.

  1. All programs reside in one machine called the Server. Any number of remote machines (called clients) can access the server program.

  2. New functionalities to existing programs can be added at the server side which the clients’ can advantage without having to change anything from their side.

  3. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about clients’ hardware or software capabilities.

  4. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by service side applications.

  5. They are portable and possess the capability to generate dynamic and user-based content (e.g. displaying transaction information of credit card or debit card depending on user’s choice). 


Types of Server Side Programs

  1. Active Server Pages (ASP)

  2. Java Servlets

  3. Java Server Pages (JSPs)

  4. Enterprise Java Beans (EJBs)

  5. PHP 

To summarize, the objective of server side programs is to centrally manage all programs relating to a particular application (e.g. Banking, Insurance, e-shopping, etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XP Professional, MS Internet Explorer and an internet connection) can experience the power and performance of a Server (e.g. IBM Mainframe, Unix Server, etc) from a remote location without having to compromise on security or speed. More importantly, server programs are not only portable but also possess the capability to generate dynamic responses based on user’s request. 

 

Servlet 

Servlet technology is used to create web application (resides at server side and generates dynamic web page).

Servet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology. We have discussed these disadvantages below.

There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.

What is a Servlet?

Servlet can be described in many ways, depending on the context.

  • Servlet is a technology i.e. used to create web application.

  • Servlet is an API that provides many interfaces and classes including documentations.

  • Servlet is an interface that must be implemented for creating any servlet.

  • Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.

  • Servlet is a web component that is deployed on the server to create dynamic web page.

servlet

What is web application?

A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request.

CGI(Commmon Gateway Interface)

CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.

problem in cgi and how servlet is better

Disadvantages of CGI

There are many problems in CGI technology:

  1. If number of clients increases, it takes more time for sending response.

  2. For each request, it starts a process and Web server is limited to start processes.

  3. It uses platform dependent language e.g. C, C++, perl.

Advantage of Servlet

advantage of servlet

There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lighweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:

  1. better performance: because it creates a thread for each request not process.

  2. Portability: because it uses java language.

  3. Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection etc.

  4. Secure: because it uses java language.

The basic terminology used in servlet are given below:

  1. HTTP

  2. HTTP Request Types

  3. Difference between Get and Post method

  4. Container

  5. Server and Difference between web server and application server

  6. Content Type

  7. Introduction of XML

  8. Deployment

HTTP (Hyper Text Transfer Protocol)

  1. Http is the protocol that allows web servers and browsers to exchange data over the web.

  2. It is a request response protocol.

  3. Http uses reliable TCP connections bydefault on TCP port 80.

  4. It is stateless means each request is considered as the new request. In other words, server doesn't recognize the user bydefault.

http protocol used in servlet

Http Request Methods

Every request has a header that tells the status of the client. There are many request methods. Get and Post requests are mostly used. The http request methods are:

  • GET

  • POST

  • HEAD

  • PUT

  • DELETE

  • OPTIONS

  • TRACE

HTTP Request

Description

GET

Asks to get the resource at the requested URL.

POST

Asks the server to accept the body info attached. It is like GET request with extra info sent with the request.

HEAD

Asks for only the header part of whatever a GET would return. Just like GET but with no body.

TRACE

Asks for the loopback of the request message, for testing or troubleshooting.

PUT

Says to put the enclosed info (the body) at the requested URL.

DELETE

Says to delete the resource at the requested URL.

OPTIONS

Asks for a list of the HTTP methods to which the thing at the request URL can respond

What is the difference between Get and Post?

There are many differences between the Get and Post request. Let's see these differences:

GET

POST

1) In case of Get request, only limited amount of datacan be sent because data is sent in header.

In case of post request, large amount of data can be sent because data is sent in body.

2) Get request is not secured because data is exposed in URL bar.

Post request is secured because data is not exposed in URL bar.

3) Get request can be bookmarked

Post request cannot be bookmarked

4) Get request is idempotent. It means second request will be ignored until response of first request is delivered.

Post request is non-idempotent

5) Get request is more efficient and used more than Post

Post request is less efficient and used less than get.

Anatomy of Get Request

As we know that data is sent in request header in case of get request. It is the default request type. Let's see what informations are sent to the server. 

anatomy of Get Request

Anatomy of Post Request

As we know, in case of post request original data is sent in message body. Let's see how informations are passed to the server in case of post request. anatomy of Post Request

Container

It provides runtime environment for JavaEE (j2ee) applications.It performs many operations that are given below:

  1. Life Cycle Management

  2. Multithreaded support

  3. Object Pooling

  4. Security etc.

 

Server

It is a running program or software that provides services.There are two types of servers:

  1. Web Server

  2. Application Server

 

Web Server

Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB.  Example of Web Servers are: Apache Tomcat and Resin.

 

Application Server

Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc.

Example of Application Servers are:

  1. JBoss Open-source server from JBoss community.

  2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.

  3. Weblogic provided by Oracle. It more secured.

  4. Websphere provided by IBM.

 

Content Type

Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP header that provides the description about what are you sending to the browser.

There are many content types:

  • text/html

  • text/plain

  • application/msword

  • application/vnd.ms-excel

  • application/jar

  • application/pdf

  • application/octet-stream

  • application/x-zip

  • images/jpeg

  • video/quicktime etc.

 

Servlet API

  1. Interfaces in javax.servlet package

  2. Classes in javax.servlet package

  3. Interfaces in javax.servlet.http package

  4. Classes in javax.servlet.http package

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.

Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows:

  1. Servlet

  2. ServletRequest

  3. ServletResponse

  4. RequestDispatcher

  5. ServletConfig

  6. ServletContext

  7. SingleThreadModel

  8. Filter

  9. FilterConfig

  10. FilterChain

  11. ServletRequestListener

  12. ServletRequestAttributeListener

  13. ServletContextListener

  14. ServletContextAttributeListener

Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:

  1. GenericServlet

  2. ServletInputStream

  3. ServletOutputStream

  4. ServletRequestWrapper

  5. ServletResponseWrapper

  6. ServletRequestEvent

  7. ServletContextEvent

  8. ServletRequestAttributeEvent

  9. ServletContextAttributeEvent

  10. ServletException

  11. UnavailableException

Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:

  1. HttpServletRequest

  2. HttpServletResponse

  3. HttpSession

  4. HttpSessionListener

  5. HttpSessionAttributeListener

  6. HttpSessionBindingListener

  7. HttpSessionActivationListener

  8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

  1. HttpServlet

  2. Cookie

  3. HttpServletRequestWrapper

  4. HttpServletResponseWrapper

  5. HttpSessionEvent

  6. HttpSessionBindingEvent

  7. HttpUtils (deprecated now)

Servlet Interface

  1. Servlet Interface

  2. Methods of Servlet interface

Servlet interface provides common behaviour to all the servlets.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.

Method

Description

public void init(ServletConfig config)

initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.

public void service(ServletRequest request,ServletResponse response)

provides response for the incoming request. It is invoked at each request by the web container.

public void destroy()

is invoked only once and indicates that servlet is being destroyed.

public ServletConfig getServletConfig()

returns the object of ServletConfig.

public String getServletInfo()

returns information about servlet such as writer, copyright, version etc.

Servlet Example by implementing Servlet interface

File: First.java

import java.io.*;  

import javax.servlet.*;  


public class First implements Servlet{  

ServletConfig config=null;  

public void init(ServletConfig config){  

this.config=config;  

System.out.println("servlet is initialized");  

}  

public void service(ServletRequest req,ServletResponse res)  

throws IOException,ServletException{  

res.setContentType("text/html");  

PrintWriter out=res.getWriter();  

out.print("<html><body>");  

out.print("<b>hello simple servlet</b>");  

out.print("</body></html>");  

}  

public void destroy(){System.out.println("servlet is destroyed");}  

public ServletConfig getServletConfig(){return config;}  

public String getServletInfo(){return "copyright 2022-23";}  

}  

GenericServlet class

GenericServlet class implements Servlet,ServletConfig and Serializable interfaces. It provides the implementaion of all the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.

 

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

  1. public void init(ServletConfig config) is used to initialize the servlet.

  2. public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.

  3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.

  4. public ServletConfig getServletConfig() returns the object of ServletConfig.

  5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.

  6. public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)

  7. public ServletContext getServletContext() returns the object of ServletContext.

  8. public String getInitParameter(String name) returns the parameter value for the given parameter name.

  9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.

  10. public String getServletName() returns the name of the servlet object.

  11. public void log(String msg) writes the given message in the servlet log file.

  12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace.

Servlet Example by inheriting the GenericServlet class

File: First.java

import java.io.*;  

import javax.servlet.*;  

public class First extends GenericServlet{  

public void service(ServletRequest req,ServletResponse res)  

throws IOException,ServletException{  

res.setContentType("text/html");  

PrintWriter out=res.getWriter();  

out.print("<html><body>");  

out.print("<b>hello generic servlet</b>");  

out.print("</body></html>");  

}  }  

HttpServlet class

  1. HttpServlet class

  2. Methods of HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

  1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.

  2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.

  3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.

  4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.

  5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.

  6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.

  7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.

  8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.

  9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container.

  10. protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT.

DemoServlet.java

import javax.servlet.http.*;  

import javax.servlet.*;  

import java.io.*;  

public class DemoServlet extends HttpServlet{  

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

{  

res.setContentType("text/html");//setting the content type  

PrintWriter pw=res.getWriter();//get the stream to write the data  

pw.println("<html><body>");  

pw.println("Welcome to servlet");  

pw.println("</body></html>");  

pw.close();

}}  

Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

  1. Servlet class is loaded.

  2. Servlet instance is created.

  3. init method is invoked.

  4. service method is invoked.

  5. destroy method is invoked.

Life cycle of a servlet

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:

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

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:

public void destroy()

 

 

 

How Servlet works?

It is important to learn how servlet works for understanding the servlet well. Here, we are going to get the internal detail about the first servlet program.

The server checks if the servlet is requested for the first time.

If yes, web container does the following tasks:

  • loads the servlet class.

  • instantiates the servlet class.

  • calls the init method passing the ServletConfig object

else

  • calls the service method passing request and response objects

The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project.

How web container handles the servlet request?

The web container is responsible to handle the request. Let's see how it handles the request.

  • maps the request with the servlet in the web.xml file.

  • creates request and response objects for this request

  • calls the service method on the thread

  • The public service method internally calls the protected service method

  • The protected service method calls the doGet method depending on the type of request.

  • The doGet method generates the response and it is passed to the client.

  • After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.

 

ServletRequest Interface

An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:

Method

Description

public String getParameter(String name)

is used to obtain the value of a parameter by name.

public String[] getParameterValues(String name)

returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box.

java.util.Enumeration getParameterNames()

returns an enumeration of all of the request parameter names.

public int getContentLength()

Returns the size of the request entity data, or -1 if not known.

public String getCharacterEncoding()

Returns the character set encoding for the input of this request.

public String getContentType()

Returns the Internet Media Type of the request entity data, or null if not known.

public ServletInputStream getInputStream() throws IOException

Returns an input stream for reading binary data in the request body.

public abstract String getServerName()

Returns the host name of the server that received the request.

public int getServerPort()

Returns the port number on which this request was received.

Example of ServletRequest to display the name of the user

In this example, we are displaying the name of the user in the servlet. For this purpose, we have used the getParameter method that returns the value for the given request parameter name.


index.html

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

Enter your name<input type="text" name="name"><br>

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

</form>
DemoServ.java

import javax.servlet.http.*;  

import javax.servlet.*;  

import java.io.*;  

public class DemoServ extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

throws ServletException,IOException  

{  

res.setContentType("text/html");  

PrintWriter pw=res.getWriter();  

String name=req.getParameter("name");//will return value  

pw.println("Welcome "+name);  

pw.close();  

}}  

READING FORM DATA FROM SERVLETS

Reading Single Values: getParameter 

To read a request (form) parameter, you simply call the getParameter method of HttpServletRequest, supplying the casesensitive parameter name as an argument. You supply the parameter name exactly as it appeared in the HTML source code, and you get the result exactly as the end user entered it; any

necessary URL-decoding is done automatically. An empty String is returned if the parameter exists but has no value (i.e., the user left the corresponding textfield empty when submitting the form), and

null is returned if there was no such parameter. Parameter names are case sensitive so, for example, request. Get Parameter ("Param1") and request. get Parameter ("param1") are not interchangeable.



Reading Multiple Values: getParameterValues

If the same parameter name might appear in the form data more than once, you should call getParameterValues (which returns an array of strings) instead of getParameter (which returns

a single string corresponding to the first occurrence of the parameter). The return value of  getParameterValues is null for nonexistent parameter names and is a one element array when the

parameter has only a single value. Now, if you are the author of the HTML form, it is usually best to ensure that each textfield, checkbox, or other user interface element has a unique name. That way, you can just stick with the simpler getParameter method and avoid getParameterValues altogether. Besides, multiselectable list boxes repeat the parameter name for each selected element in the list. So, you cannot always avoid multiple values.

Looking Up Parameter Names: getParameterNames

Use getParameterNames to get this list in the form of an Enumeration, each entry of which can be cast to a String and used in a getParameter or getParameterValues call. If there are no parameters in the current request, getParameterNames returns an empty Enumeration (not null). Note that Enumeration is an interface that merely guarantees that the actual class will have hasMoreElements and nextElement methods: there is no guarantee that any particular underlying data structure will be used. And, since

some common data structures (hash tables, in particular) scramble the order of the elements, you should not count on getParameterNames returning the parameters in the order in which they appeared in the HTML form. 


RequestDispatcher Interface

The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.This interface can also be used to include the content of antoher resource also. It is one of the way of servlet collaboration.There are two methods defined in the RequestDispatcher interface.


Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

  1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

  2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

forward() method of RequestDispatcher interface

As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.

include() method of RequestDispatcher interface

As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.

How to get the object of RequestDispatcher

The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax:

public RequestDispatcher getRequestDispatcher(String resource);

 

Example of RequestDispatcher interface

In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this example, we have created following files:

  • index.html file: for getting input from the user.

  • Login.java file: a servlet class for processing the response. If password is secret, it will forward the request to the welcome servlet.

  • WelcomeServlet.java file: a servlet class for displaying the welcome message.

  • web.xml file: a deployment descriptor file that contains the information about the servlet.

RequestDispatcher interface


index.html

<form action="Login" method="post">

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

Password:<input type="password" name="userPass"/><br/>

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

Login.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class Login extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response)  

throws ServletException, IOException {  

response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  

 

    String n=request.getParameter("userName");  

    String p=request.getParameter("userPass");  

 

if(p.equals("secret"){  

        RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");  

rd.forward(request, response);  

    }  

else{

out.print("Sorry UserName or Password Error!");  

        RequestDispatcher rd=request.getRequestDispatcher("/index.html");  

rd.include(request, response);                        

        }  

    }  

  }  

 

 

WelcomeServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class WelcomeServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response)  

throws ServletException, IOException {  

 

response.setContentType("text/html");  

    PrintWriter out = response.getWriter();     

    String n=request.getParameter("userName");  

out.print("Welcome "+n);  

    }  }  

SendRedirect in servlet

The sendRedirect() method ofHttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

 

Difference between forward() and sendRedirect() method

There are many differences between the forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse interface. They are given below:

forward() method

sendRedirect() method

The forward() method works at server side.

The sendRedirect() method works at client side.

It sends the same request and response objects to another servlet.

It always sends a new request.

It can work within the server only.

It can be used within and outside the server.

Example: request.getRequestDispacher("servlet2").forward(request,response);

Example: response.sendRedirect("servlet2");

Syntax of sendRedirect() method

  1. public void sendRedirect(String URL)throws IOException;  

Example:

In this example, we are redirecting the request to the google server. Notice that sendRedirect method works at client side, that is why we can our request to anywhere. We can send our request within and outside the server.

DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class DemoServlet extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

throws ServletException,IOException  

{  

res.setContentType("text/html");  

PrintWriter pw=res.getWriter();  

response.sendRedirect("http://www.google.com");  

pw.close();  

}}  


Creating custom google search using sendRedirect

In this example, we are using sendRedirect method to send request to google server with the request data.

index.html

<html><head>

<title>sendRedirect example</title>

</head><body>

<form action="MySearcher">

<input type="text" name="name">

<input type="submit" value="Google Search">

</form></body></html>


MySearcher.java

import java.io.IOException;  

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServlet;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  


public class MySearcher extends HttpServlet {  

protected void doGet(HttpServletRequest request, HttpServletResponse response)  

throws ServletException, IOException {  


        String name=request.getParameter("name");  

response.sendRedirect("https://www.google.co.in/#q="+name);  

    }  

}  

ServletConfig Interface

An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.

If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.

Advantage of ServletConfig

The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml file.

Methods of ServletConfig interface

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.

  2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.

  3. public String getServletName():Returns the name of the servlet.

  4. public ServletContext getServletContext():Returns an object of ServletContext.

Syntax:

public ServletConfig getServletConfig();

 

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

<web-app>

<servlet>

    ......  


<init-param>

<param-name>parametername</param-name>

<param-value>parametervalue</param-value>

</init-param>

    ......  

</servlet>

</web-app>

Example of ServletConfig to get initialization parameter

In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet.

DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class DemoServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

    throws ServletException, IOException {  

    response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  

    ServletConfig config=getServletConfig();  

    String driver=config.getInitParameter("driver");  

    out.print("Driver is: "+driver);  

    out.close();      }  }  

web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>DemoServlet</servlet-class>

<init-param>

<param-name>driver</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

</web-app>


Example of ServletConfig to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.


DemoServlet.java

import java.io.IOException;  

import java.io.PrintWriter;  

import java.util.Enumeration;  

import javax.servlet.ServletConfig;  

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServlet;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  


public class DemoServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

        throws ServletException, IOException {  

    response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  

    ServletConfig config=getServletConfig();  

    Enumeration<string> e=config.getInitParameterNames();  

    String str="";  

    while(e.hasMoreElements()){  

    str=e.nextElement();  

    out.print("<br>Name: "+str);  

    out.print(" value: "+config.getInitParameter(str));  

    }  

   out.close();  

}  }  



web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>DemoServlet</servlet-class>

<init-param>

<param-name>username</param-name>

<param-value>system</param-value>

</init-param>

<init-param>

<param-name>password</param-name>

<param-value>oracle</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

</web-app>

ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.If any information is shared to many servlet, it is better to provide it from the web.xml file using the<context-param> element.

 

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem.

 

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

  1. The object of ServletContext provides an interface between the container and servlet.

  2. The ServletContext object can be used to get configuration information from the web.xml file.

  3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.

  4. The ServletContext object can be used to provide inter-application communication.

ServletContext interface

Commonly used methods of ServletContext interface

There is given some commonly used methods of ServletContext interface.

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.

  2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters.

  3. public void setAttribute(String name,Object object):sets the given object in the application scope.

  4. public Object getAttribute(String name):Returns the attribute for the specified name.

  5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.

  6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

How to get the object of ServletContext interface

  1. getServletContext() method of ServletConfig interface returns the object of ServletContext.

  2. getServletContext() method of GenericServlet class returns the object of ServletContext.

Syntax:

public ServletContext getServletContext()

Syntax to provide the initialization parameter in Context scope

The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and and param-value defines its value.

<web-app>

 ......  


<context-param>

<param-name>parametername</param-name>

<param-value>parametervalue</param-value>

</context-param>

 ......  

</web-app>

Example of ServletContext to get the initialization parameter

In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let's see the simple example:


DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class DemoServlet extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

throws ServletException,IOException  

{  

res.setContentType("text/html");  

PrintWriter pw=res.getWriter();  

//creating ServletContext object  

ServletContext context=getServletContext();  

//Getting the value of the initialization parameter and printing it  

String driverName=context.getInitParameter("dname");  

pw.println("driver name is="+driverName);  

pw.close();  

 }}  

web.xml

<web-app>

<servlet>

<servlet-name>servlet1</servlet-name>

<servlet-class>DemoServlet</servlet-class>

</servlet>

<context-param>

<param-name>dname</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</context-param>

<servlet-mapping>

<servlet-name>servlet1</servlet-name>

<url-pattern>/context</url-pattern>

</servlet-mapping>

</web-app>


Example of ServletContext to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class.


DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  


public class DemoServlet extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

throws ServletException,IOException  

{  

res.setContentType("text/html");  

PrintWriter out=res.getWriter();  

ServletContext context=getServletContext();  

Enumeration<string> e=context.getInitParameterNames();  

String str="";  

while(e.hasMoreElements()){  

    str=e.nextElement();  

    out.print("<br> "+context.getInitParameter(str));  

}  }}  

web.xml

<web-app>

<servlet>

<servlet-name>servlet1</servlet-name>

<servlet-class>DemoServlet</servlet-class>

</servlet>

<context-param>

<param-name>dname</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</context-param>


<context-param>

<param-name>username</param-name>

<param-value>system</param-value>

</context-param>


<context-param>

<param-name>password</param-name>

<param-value>oracle</param-value>

</context-param>


<servlet-mapping>

<servlet-name> servlet1</servlet-name>

<url-pattern>/context</url-pattern>

</servlet-mapping>


</web-app>

Attribute in Servlet

An attribute is an object that can be set, get or removed from one of the following scopes:

  1. request scope

  2. session scope

  3. application scope

The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext interface

There are following 4 attribute specific methods. They are as follows:

  1. public void setAttribute(String name,Object object):sets the given object in the application scope.

  2. public Object getAttribute(String name):Returns the attribute for the specified name.

  3. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.

  4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

Example of ServletContext to set and get attribute

In this example, we are setting the attribute in the application scope and getting that value from another servlet.


DemoServlet1.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  


public class DemoServlet1 extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

{  

try{  

res.setContentType("text/html");  

PrintWriter out=res.getWriter();  


ServletContext context=getServletContext();  

context.setAttribute("company","IBM");  


out.println("Welcome to first servlet");  

out.println("<a href='servlet2'>visit</a>");  

out.close();  


}catch(Exception e){out.println(e);}  

}}  

DemoServlet2.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  



public class DemoServlet2 extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

{  

try{  

res.setContentType("text/html");  

PrintWriter out=res.getWriter();  


ServletContext context=getServletContext();  

String n=(String)context.getAttribute("company");  

out.println("Welcome to "+n);  

out.close();  

}catch(Exception e){out.println(e);}  

}}  

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>DemoServlet1</servlet-class>

</servlet>


<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>DemoServlet2</servlet-class>

</servlet>


<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

Difference between ServletConfig and ServletContext:

ServletConfig

  • ServletConfig available in javax.servlet.*; package

  • ServletConfig object is one per servlet class

  • Object of ServletConfig will be created during initialization process of the servlet

  • This Config object is public to a particular servlet only

  • Scope: As long as a servlet is executing, ServletConfig object will be available, it will be destroyed once the servlet execution is completed.

  • We should give request explicitly, in order to create ServletConfig object for the first time

  • In web.xml – <init-param> tag will be appear under <servlet-class> tag

ServletContext

  • ServletContext available in javax.servlet.*; package

  • ServletContext object is global to entire web application

  • Object of ServletContext will be created at the time of web application deployment

  • Scope: As long as web application is executing, ServletContext object will be available, and it will be destroyed once the application is removed from the server.

  • ServletContext object will be available even before giving the first request

  • In web.xml – <context-param> tag will be appear under <web-app> tag

So finally…….

No. of web applications  =  That many number of ServletContext objects [ 1 per web application ]
No. of servlet classes = That many number of ServletConfig objects

 


Cookies in Session Tracking

Cookie is a mechanism to maintain the state of an user. Before cookie, let's see what is sesion tracking and what are ways to perform session tracking.

Session Tracking

Session simply means a particular interval of time.

Session Tracking is a way to maintain state of an user. Http protocol is a stateless protocol. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.

session tracking

Why use Session Tracking?

To recognize the user.

Session Tracking Techniques

There are four techniques used in Session tracking:

  1. Cookies

  2. Hidden Form Field

  3. URL Rewriting

  4. HttpSession

1) Cookies

A cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

cookies in session tracking

javax.servlet.http.Cookie class provides the functionality of using cookies.

Constructor of Cookie class

Cookie(String name, String value): Constructs a cookie with a specified name and value.

Commonly used methods of Cookie class

There are given some commonly used methods of the Cookie class.

  1. public void setMaxAge(int expiry):Sets the maximum age of the cookie in seconds.

  2. public String getName():Returns the name of the cookie. The name cannot be changed after creation.

  3. public String getValue():Returns the value of the cookie.

  4. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.

  5. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.


Advantage of Cookies

  1. Simplest technique of maintaining the state.

  2. Cookies are maintained at client side.

Disadvantage of Cookies

  1. It will not work if cookie is disabled from the browser.

  2. Only textual information can be set in Cookie object.

Example of using Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value.

cookies in session tracking

index.html

<form action="FirstServlet" method="post">

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

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

FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  


public class FirstServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response){  

try{


response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  


    String n=request.getParameter("userName");  

out.print("Welcome "+n);  


    Cookie ck=new Cookie("uname",n);//creating cookie object  

response.addCookie(ck);//adding cookie in the response  


    //creating submit button  

out.print("<form action=' SecondServlet'>");  

out.print("<input type='submit' value='go'>");  

out.print("</form>");  

out.close();    

}catch(Exception e){System.out.println(e);}  

  }  }  

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class SecondServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response){  

try{

response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  


    Cookie ck[]=request.getCookies();  

out.print("Hello "+ck[0].getValue());  

out.close();  

}catch(Exception e){System.out.println(e);}  

    }   }  

2)Hidden Form Field

In case of Hidden Form Field an invisible textfield is used for maintaing the state of an user. In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.

Hidden Form Field in session tracking

Advantage of Hidden Form Field

  1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

  1. It is maintained at server side.

  2. Extra form submission is required on each pages.

  3. Only textual information can be used.

Example of using Hidden Form Field

In this example, we are storing the name of the user in a hidden textfield and getting that value from another servlet.


index.html

<form action="FirstServlet">

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

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


FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  



public class FirstServlet extends HttpServlet {  


public void doGet(HttpServletRequest request, HttpServletResponse response){  

try{


response.setContentType("text/html");  

        PrintWriter out = response.getWriter();  


        String n=request.getParameter("userName");  

out.print("Welcome "+n);  


        //creating form that have invisible textfield  

out.print("<form action='SecondServlet'>");  

out.print("<input type='hidden' name="uname" value='"+n+"'>");  

out.print("<input type='submit' value='go'>");  

out.print("</form>");  

out.close();   

}catch(Exception e){System.out.println(e);}  

    }  }  

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  


public class SecondServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

try{


response.setContentType("text/html");  

        PrintWriter out = response.getWriter();  


        //Getting the value from the hidden field  

        String n=request.getParameter("uname");  

out.print("Hello "+n);  

out.close();  

}catch(Exception e){System.out.println(e);}  

    }  

}  

3)URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

http://www.javatpoint.com/images/url.JPG

Advantage of URL Rewriting

  1. It will always work whether cookie is disabled or not (browser independent).

  2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

  1. It will work only with links.

  2. It can send Only textual information.

Example of using URL Rewriting

In this example, we are maintaning the state of the user using link. For this purpose, we are appending the name of the user in the query string and getting the value from the query string in another page.

index.html

<form action="FirsrServlet">

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

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

FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class FirstServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response){  

try{

 

response.setContentType("text/html");  

        PrintWriter out = response.getWriter();  

 

        String n=request.getParameter("userName");  

out.print("Welcome "+n);  

 

        //appending the username in the query string  

out.print("<a href='SecondServlet?uname="+n+"'>visit</a>");  

 

out.close();  

}catch(Exception e){System.out.println(e);}  

    }  }  

 

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class SecondServlet extends HttpServlet {  

 

public void doGet(HttpServletRequest request, HttpServletResponse response)  

try{

 

response.setContentType("text/html");  

        PrintWriter out = response.getWriter();  

 

        //getting value from the query string  

        String n=request.getParameter("uname");  

out.print("Hello "+n);  

out.close();  

 

}catch(Exception e){System.out.println(e);}  

    }  }  

4) HttpSession interface

In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks:

  1. bind objects

  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.

http://www.javatpoint.com/images/httpsession.JPG

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

  1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.

  2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface

  1. public String getId():Returns a string containing the unique identifier value.

  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.

  4. public void invalidate():Invalidates this session then unbinds any objects bound to it.


Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value from the session scope in another servlet. To set the attribute in the session scope, we have used the setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute method.

index.html

<form action="FirstServlet">

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

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

</form>

FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class FirstServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response){  

try{

response.setContentType("text/html");  

        PrintWriter out = response.getWriter();  

 

        String n=request.getParameter("userName");  

out.print("Welcome "+n);  

 

        HttpSession session=request.getSession();  

session.setAttribute("uname",n);  

 

out.print("<a href='SecondServlet'>visit</a>");  

 

out.close();  

}catch(Exception e){System.out.println(e);}  

    }  }  

 

 

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class SecondServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

try{

response.setContentType("text/html");  

        PrintWriter out = response.getWriter();  

 

        HttpSession session=request.getSession(false);  

        String n=(String)session.getAttribute("uname");  

out.print("Hello "+n);  

out.close();  

 

}catch(Exception e){System.out.println(e);}  

    }  }  


Java Servlet Java Servlet Reviewed by Asst. Prof. Sunita Rai on January 28, 2024 Rating: 5

1 comment:

Powered by Blogger.