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.
Advantages of Server Side Programs
The list below highlights some of the important advantages of Server Side programs.
All programs reside in one machine called the Server. Any number of remote machines (called clients) can access the server program.
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.
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.
Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by service side applications.
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
Active Server Pages (ASP)
Java Servlets
Java Server Pages (JSPs)
Enterprise Java Beans (EJBs)
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?
What is web application?
CGI(Commmon Gateway Interface)
Disadvantages of CGI
There are many problems in CGI technology:
If number of clients increases, it takes more time for sending response.
For each request, it starts a process and Web server is limited to start processes.
It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet
HTTP (Hyper Text Transfer Protocol)
Http is the protocol that allows web servers and browsers to exchange data over the web.
It is a request response protocol.
Http uses reliable TCP connections bydefault on TCP port 80.
It is stateless means each request is considered as the new request. In other words, server doesn't recognize the user bydefault.
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
What is the difference between Get and Post?
There are many differences between the Get and Post request. Let's see these differences:
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 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.
Container
It provides runtime environment for JavaEE (j2ee) applications.It performs many operations that are given below:
Life Cycle Management
Multithreaded support
Object Pooling
Security etc.
Server
It is a running program or software that provides services.There are two types of servers:
Web Server
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:
JBoss Open-source server from JBoss community.
Glassfish provided by Sun Microsystem. Now acquired by Oracle.
Weblogic provided by Oracle. It more secured.
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
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
Classes in javax.servlet package
Interfaces in javax.servlet.http package
Classes in javax.servlet.http package
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.
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
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
Methods of HttpServlet class
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)
1) Servlet class is loaded
2) Servlet instance is created
3) init method is invoked
public void init(ServletConfig config) throws ServletException
4) service method is invoked
public void service(ServletRequest req, ServletResponse res)throws ServletException,IOException
5) destroy method is invoked
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
Methods of ServletRequest interface
There are many methods defined in the ServletRequest interface. Some of them are as follows:
Example of ServletRequest to display the name of the user
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
How to get the object of RequestDispatcher
public RequestDispatcher getRequestDispatcher(String resource);
Example of 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:
Syntax of sendRedirect() method
public void sendRedirect(String URL)throws IOException;
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();
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
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
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:
The object of ServletContext provides an interface between the container and servlet.
The ServletContext object can be used to get configuration information from the web.xml file.
The ServletContext object can be used to set, get or remove attribute from the web.xml file.
The ServletContext object can be used to provide inter-application communication.
Commonly used methods of ServletContext interface
How to get the object of ServletContext interface
getServletContext() method of ServletConfig interface returns the object of ServletContext.
getServletContext() method of GenericServlet class returns the object of ServletContext.
Syntax:
public ServletContext getServletContext()
Syntax to provide the initialization parameter in Context scope
Example of ServletContext to get the initialization parameter
Attribute in Servlet
Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
Example of ServletContext to set and get attribute
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
Session Tracking
Why use Session Tracking?
Session Tracking Techniques
1) Cookies
Constructor of Cookie class
Commonly used methods of Cookie class
Advantage of Cookies
Disadvantage of Cookies
Example of using Cookies
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
Advantage of Hidden Form Field
Disadvantage of Hidden Form Field:
Example of using Hidden Form Field
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.
Advantage of URL Rewriting
Disadvantage of URL Rewriting
Example of using URL Rewriting
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
How to get the HttpSession object ?
Commonly used methods of HttpSession interface
Example of using HttpSession
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);}
} }
Really very informative blog keep it up
ReplyDelete