Professional Documents
Culture Documents
RMI overview
RMI architecture
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.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's understand
the stub and skeleton objects:
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:
Unit – 2 CS-25 - Advance Java Programming (J2ee)
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
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:
Transport Layer − This layer connects the client and the server. It manages
the existing connection and also sets up new connections.
Class Naming
java.lang.Object
java.rmi.Naming
The Naming class provides methods for storing and obtaining references to remote objects in a remote object
registry. Each method of the Naming class takes as one of its arguments a name that is a java.lang
Unit – 2 CS-25 - Advance Java Programming (J2ee)
lookup
public static Remote lookup(String name)
throws NotBoundException,
MalformedURLException,
RemoteException
Returns a reference, a stub, for the remote object associated with the specified name. It is basically looking for an
object in the server object pool registered with a name //localhost/Hello
Parameters:
Returns:
a reference for a remote object
Throws:
rebind
public static void rebind(String name,
Remote obj)
throws RemoteException,
MalformedURLException
Rebinds the specified name to a new remote object. Any existing binding for the name is replaced. The rebind
method always binds the name to the object even if the name is already bound. The old binding is lost.
Parameters:
extends RemoteServer
3. Compile the implementation class and create the stub and skeleton objects using the
rmic tool
4. Start the registry service by rmiregistry tool
• The remote interface must be declared public or the client will get an error when it tries to load a
remote object that implements the remote interface.
• The remote interface must extend the java.rmi.Remote interface.
• Each method must throw a java.rmi.RemoteException (or a superclass of RemoteException)
• If the remote methods have any remote objects as parameters or return types, they must be interface
types not the implementation classes.
The implementing class is the actual class that provides the implementation for methods defined in the
remote interface. The java.rmi.server.RemoteObject extends the functionality provided by the
java.lang.Object class into the remote domain by overriding the equals(), hashcode() and toString()
methods. The generic java.rmi.server.RemoteObject is an abstract class and describes the behavior of
remote objects.
The abstract subclass java.rmi.server.RemoteServer describes the behavior associated with the server
implementation and provides the basic semantics to support remote references.
• java.rmi.server.UnicastRemoteObject
It designs a non-replicated remote object whose reference is valid only when the server is alive.
• java.rmi.activation.Activatable
It is the concrete class that defines behavior for on demand instantiation of remote objects.
In addition to one of the above classes, the class corresponding to the remote interface must implement
one or more interfaces that define the remote methods. A remote class can define any methods but
only methods in the remote interface can be invoked remotely.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Note: It is worth keeping in mind that while starting the registry all classes and stubs must be available
in the classpath or the classpath should not be set at all, to support dynamic loading.
1. Start RMI Registry: Ensure that the following classes are present in the current folder or the
classpath:
• HelloInterface.class
• HelloServer_Stub.class
2. Start Server: Ensure that the following classes are in the current folder or the classpath:
• HelloInterface.class
• HelloServer.class
• HelloServer_Stub.class
• MyRMI.class
3. Run Client: Ensure that the following classes are in the current folder or the classpath:
• HelloInterface.class
• HelloServer_Stub.class
• HelloClient.class
Architecture of a Servlet
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Servlets Tasks
Servlets perform the following major tasks −
Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
Process the data and generate the results. This process may require talking to a database,
executing an RMI , invoking a Web service, or computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.
Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the
JDK's Java compiler or any other current compiler.
Servlet API
1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. 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.
Interface Summary
A filter is an object that performs filtering tasks on either the request
Filter to a resource (a servlet or static content), or on the response from a
resource, or both.
Defines an object that receives requests from the client and sends
RequestDispatcher them to any resource (such as a servlet, HTML file, or JSP file) on the
server.
This is the event class for notifications about changes to the attributes
ServletContextAttributeEvent
of the servlet context of a web application.
This is the event class for notifications about changes to the servlet
ServletContextEvent
context of a web application.
Provides an input stream for reading binary data from a client request,
ServletInputStream including an efficient readLine method for reading data one line at a
time.
ServletOutputStream Provides an output stream for sending binary data to the client.
from a Servlet.
Exception Summary
ServletException Defines a general exception a servlet can throw when it encounters difficulty.
Interface Summary
Extends the ServletRequest interface to provide request information
HttpServletRequest
for HTTP servlets.
Provides a way to identify a user across more than one page request or
HttpSession
visit to a Web site and to store information about that user.
Class Summary
Creates a cookie, a small amount of information sent by a servlet to a
Cookie
Web browser, saved by the browser, and later sent back to the server.
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
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.
The class loader 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.
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.
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
There are given 6 steps to create a servlet example. These steps are required for all the servers.
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.
The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's
see the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml file must be
under the WEB-INF folder.
2)Create a Servlet
There are three ways to create the 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.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we
Unit – 2 CS-25 - Advance Java Programming (J2ee)
are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice
that get request is the default request.
DemoServlet.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
1. set classpath
Unit – 2 CS-25 - Advance Java Programming (J2ee)
2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet in
WEB-INF/classes directory.
The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>
There are too many elements in the web.xml file. Here is the illustration of some elements that is
used in the above web.xml file. The elements are as follows:
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.
To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.
To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment
variables.
Go to My Computer properties -> Click on advanced tab then environment variables -> Click on
the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk
folder in variable value -> ok -> ok -> ok.
Go to My Computer properties:
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:
Unit – 2 CS-25 - Advance Java Programming (J2ee)
After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.
Changing the port number is required if there is another server running on the same system with
same port number.Suppose you have installed oracle, you need to change the port number of
apache tomcat because both have the default port number 8080.
Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change
the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us
replace it by 9999 and save this file.
Copy the project and paste it in the webapps folder under apache tomcat.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
But there are several ways to deploy the project. They are as follows:
You can also create war file, and paste it inside the webapps directory. To do so, you need to use
jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write:
Creating war file has an advantage that moving the project from one location to another takes
less time.
1. http://localhost:9999/demo/welcome
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Following is a summary of the most useful HTTP 1.1 response headers which go back to the
browser from web server side and you would use them very frequently in web programming −
Allow
1
This header specifies the request methods (GET, POST, etc.) that the server supports.
Cache-Control
2 This header specifies the circumstances in which the response document can safely be
cached. It can have values public, private or no-cache etc. Public means document is
cacheable, Private means document is for a single user and can only be stored in private
(non-shared) caches and nocache means document should never be cached.
Connection
3
This header instructs the browser whether to use persistent in HTTP connections or not. A
value of close instructs the browser not to use persistent HTTP connections and keepalive
means using persistent connections.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Content-Disposition
4
This header lets you request that the browser ask the user to save the response to disk in a
file of the given name.
Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.
Content-Language
6
This header signifies the language in which the document is written. For example en, en-
us, ru, etc
Content-Length
7
This header indicates the number of bytes in the response. This information is needed only
if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
8
This header gives the MIME (Multipurpose Internet Mail Extension) type of the response
document.
Expires
9
This header specifies the time at which the content should be considered out-of-date and
thus no longer be cached.
Last-Modified
10
This header indicates when the document was last changed. The client can then cache the
document and supply a date by an If-Modified-Since request header in later requests.
Location
11
This header should be included with all responses that have a status code in the 300s. This
notifies the browser of the document address. The browser automatically reconnects to
this location and retrieves the new document.
Refresh
12
This header specifies how soon the browser should ask for an updated page. You can
specify time in number of seconds after which a page would be refreshed.
Retry-After
13
This header can be used in conjunction with a 503 (Service Unavailable) response to tell
the client how soon it can repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
String a_p;
if(am_pm==0)
a_p="AM";
else
a_p="PM";
Following is the important header information which comes from browser side and you would
use very frequently in web programming −
Accept
1
This header specifies the MIME types that the browser or other clients can handle. Values
of image/png or image/jpeg are the two most common possibilities.
Accept-Charset
2
This header specifies the character sets the browser can use to display the information. For
example ISO-8859-1.
Accept-Encoding
3
This header specifies the types of encodings that the browser knows how to handle.
Values of gzip or compress are the two most common possibilities.
Accept-Language
4
This header specifies the client's preferred languages in case the servlet can produce
results in more than one language. For example en, en-us, ru, etc
Authorization
5
This header is used by clients to identify themselves when accessing password-protected
Web pages.
Connection
6
This header indicates whether the client can handle persistent HTTP connections.
Persistent connections permit the client or other browser to retrieve multiple files with a
single request. A value of Keep-Alive means that persistent connections should be used.
Content-Length
7
This header is applicable only to POST requests and gives the size of the POST data in
bytes.
Cookie
8
This header returns cookies to servers that previously sent them to the browser.
Host
9
This header specifies the host and port as given in the original URL.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Referer
10
This header indicates the URL of the referring Web page. For example, if you are at Web
page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the
Referrer header when the browser requests Web page 2.
User-Agent
11
This header identifies the browser or other client making the request and can be used to
return different content to different types of browsers.
Exapmle
Header Name Header Value(s)
Host localhost:8084
user-agent Mozilla/5.0 (Windows NT 6.1; rv:47.0) Gecko/20100101 Firefox/47.0
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language en-US,en;q=0.5
accept-encoding gzip, deflate
Referrer http://localhost:8084/ServletLifeCycle/
connection keep-alive
content-type application/x-www-form-urlencoded
content-length 8
Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this request.
2 Enumeration getAttributeNames()
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Returns an Enumeration containing the names of the attributes available to this request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4
Returns an Enumeration of String objects containing the names of the parameters
contained in this request
HttpSession getSession()
5
Returns the current session associated with this request, or if the request does not have a
session, creates one.
String getAuthType()
6
Returns the name of the authentication scheme used to protect the servlet, for example,
"BASIC" or "SSL," or null if the JSP was not protected.
String getCharacterEncoding()
7
Returns the name of the character encoding used in the body of this request.
String getContentType()
8
Returns the MIME type of the body of the request, or null if the type is not known.
String getHeader(String name)
9
Returns the value of the specified request header as a String.
String getMethod()
10
Returns the name of the HTTP method with which this request was made, for example,
GET, POST, or PUT.
String getParameter(String name)
11
Returns the value of a request parameter as a String, or null if the parameter does not
exist.
String getPathInfo()
12
Returns any extra path information associated with the URL the client sent when it made
this request
String getProtocol()
13
Returns the name and version of the protocol the request.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
String getQueryString()
14
Returns the query string that is contained in the request URL after the path.
String getServletPath()
15
Returns the part of this request's URL that calls the JSP.
String[] getParameterValues(String name)
16
Returns an array of String objects containing all of the values the given request parameter
has, or null if the parameter does not exist.
boolean isSecure()
17
Returns a Boolean indicating whether this request was made using a secure channel, such
as HTTPS.
int getContentLength()
18
Returns the length, in bytes, of the request body and made available by the input stream,
or -1 if the length is not known.
int getServerPort()
19
Returns the port number on which this request was received.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method to
get each parameter name
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
Unit – 2 CS-25 - Advance Java Programming (J2ee)
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
The servlet container provides the initialization parameters for a servlet or filter within the
configuration object the container passes to the init method. The configuration object provides
a getInitParameter() function that takes a std::string name and returns the contents of
the initialization parameter by that name. A filter uses the configuration object to access
initialization parameters
1. <web-app>
2. <servlet>
3. ......
4.
5. <init-param>
6. <param-name>parametername</param-name>
7. <param-value>parametervalue</param-value>
8. </init-param>
9. ......
10. </servlet>
11. </web-app>
DemoServletInit.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class DemoServletInit extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
Unit – 2 CS-25 - Advance Java Programming (J2ee)
8.
9. response.setContentType("text/html");
10. PrintWriter PW = response.getWriter();
11.
12. ServletConfig config=getServletConfig();
13. String name=config.getInitParameter("name");
14. pw.print("Name is: "+name);
15.
16. pw.close();
17. }
18. }
19. Here web.xml is updated as following
<servlet>
<servlet-name>D</servlet-name>
<servlet-class>DemoServletInit</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>KSCPAC</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>D</servlet-name>
<url-pattern>/Demo</url-pattern>
</servlet-mapping>
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client
opens a separate connection to the Web server and the server automatically does not keep any
record of previous client request.
Still there are following three ways to maintain session between web client and web server −
Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.
It sets the maximum time which should apply till the cookie expires
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot
support general session tracking.
URL Rewriting
Unit – 2 CS-25 - Advance Java Programming (J2ee)
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.
index.html
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. //appending the username in the query string
18. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
19.
20. out.close();
Unit – 2 CS-25 - Advance Java Programming (J2ee)
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }
web.xml
1. <web-app>
1. <servlet>
1. <servlet-name>s1</servlet-name>
2. <servlet-class>FirstServlet</servlet-class>
2. </servlet>
2. <servlet-mapping>
1. <servlet-name>s1</servlet-name>
2. <url-pattern>/servlet1</url-pattern>
2. </servlet-mapping>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
3. <servlet>
1. <servlet-name>s2</servlet-name>
2. <servlet-class>SecondServlet</servlet-class>
4. </servlet>
5. <servlet-mapping>
1. <servlet-name>s2</servlet-name>
2. <url-pattern>/servlet2</url-pattern>
6. </servlet-mapping>
7. </web-app>
The servlet container uses this interface to create a session between an HTTP client and an HTTP
server. The session persists for a specified time period, across more than one connection or page
request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below −
You need to call request.getSession() before you send any document content to the client. Here is
a summary of the important methods available through HttpSession object −
This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
11
This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.
getSession(boolean create)
12 Returns the current HttpSession associated with this request or, if there is no
current session and create is true, returns a new session.
getSession()
13 Returns the current session associated with this request, or if the request does not
have a session, creates one.
Session Example
index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
<input type="submit" value="submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping> </web-app>
First Screen:
Remove a particular attribute − You can call public void removeAttribute(String name)
method to delete the value associated with a particular key.
Delete the whole session − You can call public void invalidate() method to discard an
entire session.
Setting Session timeout − You can call public void setMaxInactiveInterval(int interval)
method to set the timeout for a session individually.
Log the user out − The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
web.xml Configuration − If you are using Tomcat, apart from the above mentioned
methods, you can configure session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in
seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( )
returns 900.
Servlet Collaboration
The Servlet collaboration is all about sharing information among the servlets. Collaborating
servlets is to pass the common information that is to be shared directly by one servlet to another
through various invocations of the methods. To perform these operations, each servlet need to
know the other servlet with which it is collaborated. Here are several ways to communicate with
one another:
- The collaboration can be done by redirecting a servlet from another or loading the servlets from the
ServletContext access methods.
- This can also be achieved by the methods forward() and include() of RequestDispatcher or by
sendRedirect() method.
1. ServletContext : In an application, there must be one Servlet context which is shared by all the
servlets in this application. It works as a global map .each servlet put necessary information , which
needs to be shared
and other can get that info
<servlet>
<servlet-name>ServletName</servlet-name>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
<servlet-class>com.example.ServletTest</servlet-class>
</servlet>
<context-param>
<param-name>name</param-name>
<param-value>Shamik Mitra</param-value>
</context-param>
To get this
getServletContext().getInitParameter("email");
Request Dispatcher:
request.setAttribute("name", "Shamik Mitra")
request.getRequestDispatcher("destination_name").forward(req,res);
request.getRequestDispatcher("destination_name").include(req,res);
import java.util.*;
Unit – 2 CS-25 - Advance Java Programming (J2ee)
}
}
To create the registration page in servlet, we can separate the database logic from the servlet. But
here, we are mixing the database logic in the servlet only for simplicity of the program. We will
develop this page in JSP following DAO, DTO and Singleton design pattern later.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Example of Registration form in servlet
register.html
Register.java
web.xml
register.html
In this page, we have getting input from the user using text fields and combobox. The
information entered by the user is forwarded to Register servlet, which is responsible to
store the data into the database.
<html>
<body>
<form action="servlet/Register" method="post">
Name:<input type="text" name="userName"/><br/><br/>
Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>
<br/><br/>
<input type="submit" value="register"/> </form> </body> </html>
Register.java
This servlet class receives all the data entered by user and stores it into the database. Here, we
are performing the database logic. But you may separate it, which will be better for the web
application.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Unit – 2 CS-25 - Advance Java Programming (J2ee)
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
out.close();
}
}
web.xml file
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
</welcome-file-list>
</web-app>
First create a employee table in Oracle and insert some data as below.
Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system dsn tab-click
add button-select a driver for which you want to set up data source (for Oracle- Oracle in
XE)-select it and click finish-give any name in data source name textbox-then click ok
button.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
web.xml setting:-
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>display</servlet-name>
<servlet-class>display</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>display</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
</web-app>
Compile
http://localhost:8081/javaservlet/display
Unit – 2 CS-25 - Advance Java Programming (J2ee)