Advanced Java Programming (J2Ee) : Bca/Bscit Sem 5
Advanced Java Programming (J2Ee) : Bca/Bscit Sem 5
UNIT 2
SERVLET, RMI
1 1
31-07-2024
SERVLET INTRODUCTION
ARCHITECTURE OF A SERVLET
Servlets are grouped under the Advanced Java tree that is used to create dynamic
web applications. Servlets are used in developing server-side applications.
1 2
31-07-2024
Servlet Architecture contains the business logic to process all the requests made by
client. Below is the high-level architecture diagram of servlet.
1. Client
The client shown in the architecture above is the web browser and it primarily works
as a medium that sends out HTTP requests over to the web server and the web
server generates a response based on some processing in the servlet and the client
further processes the response.
2. Web Server
Primary job of a web server is to process the requests and responses that a user
sends over time and maintain how a web user would be able to access the files that
has been hosted over the server.
3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web container
are: Managing the servlet lifecycle and URL mapping.
1 3
31-07-2024
Advantages
• Servlets are server independent, as they are compatible with any web server.
Compared to server-side web technologies like ASP and JavaScript, these are
server-specific.
• Servlets are protocol-independent, i.e., it supports FTP, SMTP, etc. Mainly it
provides extended support to HTTP protocol functionality.
• Servlets are portable; since they are written in java, they are portable and support
any web server.
Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the webserver,
process the request, produce the response, then send a response back to the
webserver.
A package in servlets contains numerous classes and interfaces.
Types of Packages
There are two types of packages in Java Servlet that are providing various functioning
features to servlet Applications. The two packages are as follows:
javax.servlet package
javax.servlet.http package
1 4
31-07-2024
2: javax.servlet.http package:
This package of servlet contains more interfaces and classes which can handle any
specified http types of protocols on the servlet.
The javax.servlet.http packages have provided these feature classes that are unique
to handling these HTTP requests allowing from it.
1 5
31-07-2024
Interfaces in javax.servlet.http
HttpServletRequest : The HttpServletRequest interface enables a servlet to obtain
information about a client request.
HttpServletResponse : The HttpServletResponse interface enables a servlet to
formulate an HTTP response to a client.
HttpSession : The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session.
1 6
31-07-2024
2. Initializing a Servlet: After the Servlet is loading successfully, the Servlet container
initializes the Servlet object. The container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig object reference
as parameter. If the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.
3. Handling request: After initialization, the Servlet instance is ready to serve the
client requests. It creates the ServletRequest and ServletResponse objects.
In this case, if this is a HTTP request, then the Web container creates
HttpServletRequest and HttpServletResponse objects.
1 7
31-07-2024
The deployment descriptor can also specify other, optional configurations, including:
• Specifying where component state is saved
• Encrypting state saved on the client
• Compressing state saved on the client
• Restricting access to pages containing JavaServer Faces tags
• Turning on XML validation
• Verifying custom objects
1 8
31-07-2024
A web application's deployment descriptor maps the http request with the servlets.
When the web server receives a request for the application, it uses the deployment
descriptor to map the URL of the request to the code that ought to handle the request.
The deployment descriptor should be named as web.xml.
Root element of web.xml should be <web-app>. <servlet> element map a URL to a servlet
using <servlet-mapping> element.
To map a URL to a servlet, you declare the servlet with the <servlet> element, then define
a mapping from a URL path to a servlet declaration with the <servlet-mapping> element.
The <servlet> element declares the servlet class and a logical name used to refer to the
servlet by other elements in the file.
1 9
31-07-2024
The mostly used approach is by extending HttpServlet because it provides http request
specific method such as doGet(), doPost(), doHead() etc.
Create a Servlet:
The HttpServlet class is widely used to create the servlet because it provides methods
to handle http requests such as doGet(), doPost, doHead() etc.
Example:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
1 10
31-07-2024
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();
}
}
Put the java file in any folder. After compiling the java file, paste the class file of servlet
in src directory.
1 11
31-07-2024
Example: web.xml
<web-app>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
For example:
http://localhost:9999/demo/welcome
1 12
31-07-2024
The HTML source code for index.html defines a form that contains a select element and a
submit button. Notice that the action parameter of the form tag specifies a URL. The URL
identifies a servlet to process the HTTP GET request.
index.html
<html>
<body>
<center>
<form name="Form1" action="http://localhost:8080/ColorGetDemo/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1"> <option value="Red">Red</option> <option
value="Green">Green</option>
<option value="Blue">Blue</option> </select>
<br><br>
<input type=submit value="Submit"> </form>
</body>
</html>
1 13
31-07-2024
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
index.html
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/ColorPostDemo/ColorPostServlet">
<B>Color:</B>
1 14
31-07-2024
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
ColorPostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
1 15
31-07-2024
Most of the time, data (Ex: admin email, database username and password etc.) need to
be provided in the production mode (client choice). Initialization parameters can reduce
the complexity and maintenance.
Initialization parameters are specified in the web.xml file as follows:
<servlet>
<servlet-name>Name of servlet</servlet-name>
<servlet-class>Servlet class</servlet-class>
<init-param>
<param-name>admin</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
Initialization parameters are stored as key value pairs. They are included in web.xml file
inside init-param tags. The key is specified using the param-name tags and value is
specified using the param-value tags.
Servlet initialization parameters are retrieved by using the ServletConfig object. Following
methods in ServletConfig interface can be used to retrieve the initialization parameters:
Example: index.html
<form action="welcome" method="post">
Username: <input type="text" name="user" /><br/>
Password: <input type="password" name="pass" /><br/>
<input type="submit" value="Submit" />
</form>
1 16
31-07-2024
web.xml
<web-app>
<servlet>
<servlet-name>ValidAdmin</servlet-name>
<servlet-class>ValidAdmin</servlet-class>
<init-param>
<param-name>admin</param-name>
<param-value>sarvodya college</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ValidAdmin</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
ValidAdmin.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
1 17
31-07-2024
Cookies
Hidden Form Field
URL Rewriting
HttpSession
1. Cookies in Servlet
A cookie is a small piece of information that can be a name, a single value, and a version
number etc.
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or sign-out.
1 18
31-07-2024
Cookie class
For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
Example:
In this example, we are storing the name of the user in the cookie object and accessing it
in another servlet.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.http.*;
1 19
31-07-2024
try{
response.setContentType("text/html");
PrintWriter out;
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='servlet2' method='post'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(IOException e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.http.*;
1 20
31-07-2024
web.xml
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
1 21
31-07-2024
Example:
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="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
1 22
31-07-2024
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
1 23
31-07-2024
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
1 24
31-07-2024
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
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.
1 25
31-07-2024
Example:
index.html
<form action="servlet1">
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.*;
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='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
1 26
31-07-2024
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpSession interface
In such case, container creates a session id for each user.
The container uses this id to identify the 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.
public HttpSession getSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
1 27
31-07-2024
public long getCreationTime():Returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970, GMT.
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.
public void invalidate():Invalidates this session then unbinds any objects bound to it.
Example:
index.html
<form action="servlet1">
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.*;
1 28
31-07-2024
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='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
1 29
31-07-2024
RMI OVERVIEW
RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between
Java programs. It is provided in the package java.rmi.
Inside the server program, a remote object is created, and reference of that object is made
available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke its
methods.
1 30
31-07-2024
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests
are routed through it. It resides at the client side and represents the remote object.
When the caller invokes method on the stub object, it does the following tasks:
skeleton
The skeleton is an object, acts as a gateway for the server-side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it
does the following tasks:
1 31
31-07-2024
RMI Example
HelloInterface.java
import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}
1 32
31-07-2024
Hello.java
import java.rmi.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject
implements HelloInterface {
private String message;
public Hello(String msg) throws RemoteException {
message = msg;
}
public String say() throws RemoteException {
return message;
}
}
HelloServer.java
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
public class HelloServer {
public static void main(String[] args) {
try {
Registry r = java.rmi.registry.LocateRegistry.createRegistry(1099);
//1099 is the port number
1 33
31-07-2024
HelloClient.java
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class HelloClient {
public static void main(String[] argv) {
try {
HelloInterface hello = (HelloInterface) Naming.lookup("//localhost/Hello");
System.out.println(hello.say());
} catch (MalformedURLException | NotBoundException | RemoteException e) {
System.out.println("HelloClient exception: " + e);
}
}
}
1 34
31-07-2024
END OF UNIT 2
1 35