Unit5 Servlets
Unit5 Servlets
Lecture-1
Apache Tomcat Servlet/JSP container. Apache Tomcat version 6.0 implements the Servlet 2.5 and
JavaServer Pages 2.1 specifications from the Java Community Process, and includes many additional
features that make it a useful platform for developing and deploying web applications and web services.
/bin - Startup, shutdown, and other scripts. The *.sh files (for Unix systems) are
functional duplicates of the *.bat files (for Windows systems). Since the Win32
command-line lacks certain functionality, there are some additional files in here.
/conf - Configuration files and related DTDs. The most important file in here is
server.xml. It is the main configuration file for the container.
/logs - Log files are here by default.
/webapps - This is where your webapps go.
Installing Tomcat on Windows can be done easily using the Windows installer. Its interface and
functionality is similar to other wizard based installers, with only a few items of interest.
Installation:
JDK:
Tomcat:
To facilitate creation of a Web Application Archive file in the required format, it is convenient to
arrange the "executable" files of your web application (that is, the files that Tomcat actually uses
when executing your app) in the same organization as required by the WAR format itself. To do
this, you will end up with the following contents in your application's "document root" directory:
*.html, *.jsp, etc. - The HTML and JSP pages, along with other files that must be visible
to the client browser (such as JavaScript, stylesheet files, and images) for your
application. In larger applications you may choose to divide these files into a subdirectory
hierarchy, but for smaller apps, it is generally much simpler to maintain only a single
directory for these files.
/WEB-INF/classes/ - This directory contains any Java class files (and associated
resources) required for your application, including both servlet and non-servlet classes,
that are not combined into JAR files. If your classes are organized into Java packages,
/WEB-INF/lib/ - This directory contains JAR files that contain Java class files (and
associated resources) required for your application, such as third party class libraries or
JDBC drivers.
Example:
As mentioned above, the /WEB-INF/web.xml file contains the Web Application Deployment
Descriptor for your application. As the filename extension implies, this file is an XML document, and
defines everything about your application that a server needs to know (except the context path, which is
assigned by the system administrator when the application is deployed).
Web.xml
In order to be executed, a web application must be deployed on a servlet container. This is true
even during development. We will describe using Tomcat 6 to provide the execution
environment. A web application can be deployed in Tomcat by one of the following approaches:
Copy the web application archive file into directory $CATALINA_BASE/webapps/. When
Tomcat is started, it will automatically expand the web application archive file into its
unpacked form, and execute the application that way. This approach would typically be
used to install an additional application, provided by a third party vendor or by your
internal development staff, into an existing Tomcat installation. NOTE - If you use this
approach, and wish to update your application later, you must both replace the web
application archive file AND delete the expanded directory that Tomcat created, and then
restart Tomcat, in order to reflect your changes.
Use the Tomcat 6 "Manager" web application to deploy and undeploy web applications.
Tomcat 6 includes a web application, deployed by default on context path /manager, that
allows you to deploy and undeploy applications on a running Tomcat server without
restarting it. See the administrator documentation (TODO: hyperlink) for more
information on using the Manager web application.
Use "Manager" Ant Tasks In Your Build Script. Tomcat 6 includes a set of custom task
definitions for the Ant build tool that allow you to automate the execution of commands
to the "Manager" web application. These tasks are used in the Tomcat deployer.
Deploying your app on other servlet containers will be specific to each container, but all
containers compatible with the Servlet API Specification (version 2.2 or later) are required to
accept a web application archive file. Note that other containers are NOT required to accept an
unpacked directory structure (as Tomcat does), or to provide mechanisms for shared library files,
but these features are commonly available.
Lecture-2
The web is based on a very basic client/server architecture that can be summarized as follows:
A client (usually a Web browser) sends a request to a server (most of the time a web server like
Apache, Nginx, IIS, Tomcat, etc.), using the HTTP protocol.
The server answers the request using the same protocol.
Protocols:
FTP-Transfers files from server to client support several requests for connection
The first web browser is Mosaic created by the National Center for Supercomputing Applications(NCSA)
Early in the development of HTML,the designers created a mechanism to permit a user to invoke a
program on the web server.This mechanism was called the Common Gateway Interface(CGI).When a
website includes CGI Processing this is called a web application.
At runtime a CGI program is launched by the web server as a separate operating system(OS) shell.
The shell includes an os environment and process to excecute the code of the CGI program.which
resides within the servers file system.
1. A program can be written in varirty of languages although they are primarily written in Perl
2. A CGI Program with bugs docs not crash the web server
3. Programs are easy for a web designer to reference.when the script is written,the designer can
reference it in one line in a web page.
4. Because of CGI Programs execute in their own OS Shell,these programs do not have concurrency
conflicts with other HTTP requests executing the same CGI program.
5. All service providers support CGI Programs
1. The response time of CGI prigrams is high because CGI programs execute in their own OS
Shell.The creation of OS shell is heavyweight activity for the OS
2. CGI is not Scalable.If the number of people accessing the web application increases from 50 to
5000.can not be adopted to handle the load.
3. The languages for CGI are not always secure or object-oriented.
4. The CGI script has to generate an HTML response,so the CGI code is mingled with HTML.This is
not good seperation of presentation and business logic.
5. Scripting languages are often platform-dependent.
Java Servlets:
Unlike CGI programs, servlets run within component container architecture.This container is called web
container or servlet engine.
The web container is a JVM that supplies an implementation of the Servlet API
Servlet instances are components that are managed by the web container to respond to HTTP
requests.
1. The basic processing steps for Java servlets are quite similar to the steps for CGI.However,the
servlet runs as a thread in the web container instead of in a separate OS process.
1. Each request is run in a separate thread, so servlet request processing is significantly faster than
traditional CGI Processing.
2. Servlets are Scalable.Many more requests can be excecuted because the web container uses a
thread rather than an operating system process,which is a limited system resource.
3. Servlets are robust and object oriented.
4. Servlets are platform independent
5. The web container provides additional services to the servlets,such as error handling and
security.
Presentation Logic: is anything that controls how the application presents information to the user.
Business Logic:is anything that manipulates data to accomplish something,such as storing data.
Note:To overcome above servlet disadvantages Java Server Pages(JSP) are introduced.
Lecture-3
Server
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.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts,
jsf, ejb etc.
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.
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.
Every request has a header that tells the status of the client. There are many request
methods. Get and Post requests are mostly used.
GET
POST
HEAD
PUT
DELETE
OPTIONS
TRACE
HTTP Description
Request
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.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond
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 In case of post request, large amount of
data can be sent because data is sent in header. data can be sent because data is sent in
body.
2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
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.
Header line 1
Header line 2
-----------
-----------
Header line n
blank line
request body (optional)
user-Agent: Mozilla/4.5
Header line 1
---------
---------
Header line n
blank line
Response body
HTTP/1.0 200 OK
OK : status message
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.
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.
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
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10.ServletException
11.UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
Lecture-4
Servlet LifeCycle:
A servlet follows a certain life cycle. The servlet life cycle is managed by the servlet
container. The life cycle contains the following steps:
Step 1, 2 and 3 are executed only once, when the servlet is initially loaded. By
default the servlet is not loaded until the first request is received for it. You can
force the container to load the servlet when the container starts up though.
See web.xml Servlet Configuration for more details about that.
Step 4 is executed multiple times - once for every HTTP request to the servlet.
Step 5 is executed when the servlet container unloads the servlet.
Each step is described in more detail below:
Before a servlet can be invoked the servlet container must first load its class
definition. This is done just like any other class is loaded.
When the servlet class is loaded, the servlet container creates an instance of the
servlet.
Typically, only a single isntance of the servlet is created, and concurrent requests
to the servlet are executed on the same servlet instance. This is really up to the
servlet container to decide, though. But typically, there is just one instance.
When a servlet instance is created, its init() method is invoked. The init() method
allows a servlet to initialize itself before the first request is processed.
You can specify init parameters to the servlet in the web.xml file. See web.xml
Servlet Configuration for more details.
For every request received to the servlet, the servlets service() method is called.
For HttpServletsubclasses, one of the doGet(), doPost() etc. methods are typically
called.
As long as the servlet is active in the servlet container, the service() method can be
called. Thus, this step in the life cycle can be executed multiple times.
When a servlet is unloaded by the servlet container, its destroy() method is called.
This step is only executed once, since a servlet is only unloaded once.
There are given 6 steps to create a servlet example. These steps are required for
all the servers.
Here, we are going to use apache tomcat server in this example. The steps are
as follows:
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.
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 are inheriting the HttpServlet class and providing the
implementation of the doGet() method. Notice that get request is the default
request.
Servlethtml.java
package com.cmrcet.servletexample;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html><body>");
out.println("<b>WT LAB</b>");
out.println("</b></center>");
out.println("</body></html>");
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
Put the java file in any folder. After compiling the java file, paste the class file of
servlet in WEB-INF/classes directory.
E:\IIICSEA\cmrwebapp1\WEB-INF\classes>javac -d . *.java
E:\IIICSEA\cmrwebapp1\WEB-INF\classes>
E:\IIICSEA\cmrwebapp1\WEB-INF\classes>set classpath=E:\servlet-api.jar;.;
E:\IIICSEA\cmrwebapp1\WEB-INF\classes>javac -d . *.java
E:\IIICSEA\cmrwebapp1>tree/f
E:.
│ Home.html
└───WEB-INF
│ web.xml
├───classes
│ │ servlethtml.java
│ │
│ └───com
│ └───cmrcet
│ └───servletexample
│ servlethtml.class
└───lib
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
<web-app>
<servlet>
<servlet-name>servlethtml</servlet-name>
<servlet-class>com.cmrcet.servletexample.servlethtml</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlethtml</servlet-name>
<url-pattern>/getHomeHtml</url-pattern>
</servlet-mapping>
</web-app>
Go to My Computer properties:
http://localhost:9090/cmrwebapp1/Home.html
package com.cmrcet.lifecycleex;
import javax.servlet.*;
import java.io.*;
public class LifeCycle implements Servlet
{
private ServletConfig myconfig;
public void init(ServletConfig sc)
{
this.myconfig=sc;
System.out.println("In Init() Method");
Lifecycle.html
<!doctype html>
<html lang="en">
<head>
</body>
</html>
Note:Arrrane in Directory structure and compile and deploy in Tomcat server and
Test
Lecture-5
ServletContext and ServletConfig are the interfaces provided by javasoft as part of servlet-api.It is the
responsibility of the web container vendors to provide the classes implementing the ServletConfig
interface and the 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.
There can be a lot of usage of ServletContext object. Some of them are as follows:
<web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</web-app>
SCExample.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SCExample extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.close();
}
}
<!--Login.html-->
<html> <body>
<center><h1>CMR College of Engineering & Technology</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td width="15%" valign="top" align="center">
<br/><a href="Login.html">Login</a><br/>
<br/><a href="Register.html">Register</a><br/>
</td>
<td valign="top" align="center"><br/>
<form action="login"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b> </td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>
</tr>
</table></form>
</td>
</tr>
</table>
</body></html>
<init-param>
<param-name>dbuser</param-name>
<param-value>yellaswamy</param-value>
<servlet>
<servlet-name>rs</servlet-name>
<servlet-class>
com.yellaswamy.servlets.RegistrationServlet
</servlet-class>
<init-param>
<param-name>dbuser</param-name>
<param-value>yellaswamy</param-value>
</init-param>
<init-param>
<param-name>dbpass</param-name>
<param-value>yellaswamy</param-value>
</init-param>
<init-param>
<param-name>sqlstatement</param-name>
<param-value>
insert into userdetails values(?,?,?,?,?)
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ls</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>rs</servlet-name>
<url-pattern>/register</url-pattern>
<welcome-file-list>
<welcome-file>Home.html</welcome-file>
</welcome-file-list>
</web-app>
Lecture-6
HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
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.
1. Non-persistent cookie
2. 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 signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It
provides a lot of useful methods for cookies.
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String constructs a cookie with a specified name and
value) value.
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of
cookie
}
In the previous page, we learned a lot about cookie e.g. how to create cookie, how
to delete cookie, how to get cookie etc.
Here, we are going to create a login and logout example using servlet cookies.
In this example, we are creating 3 links: login, logout and profile. User can't go to
profile page until he/she is logged in. If user is logged out, he need to login again to
visit profile.
1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml
index.html
<!DOCTYPE html>
<html>
<head>
Link.html
<!doctype html>
<html lang="en">
<head>
<title>Links</title>
</head>
<body>
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>
</body>
</html>
Login.html
<!doctype html>
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
<form action="LoginServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);
out.close();
}
request.getRequestDispatcher("link.html").include(request, response);
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>yellaswamy.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>yellaswamy.ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>yellaswamy.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>
Output:
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.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
In this example, we are storing the name of the user in a hidden textfield and
getting that value from another servlet.
3)URL Rewriting
1. URL Rewriting
2. Advantage of URL Rewriting
3. Disadvantage of URL Rewriting
4. Example of 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&??
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.
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.
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="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
SendRedirect in servlet
1. sendRedirect method
2. Syntax of sendRedirect() method
3. Example of RequestDispatcher interface
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.
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.*;
response.sendRedirect("http://www.google.com");
pw.close();
}}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<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;
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
1. AIM: Write a Servlet for Registration to connect to database Insert the details of the users who
register with the web site.
2. Write a Servlet for Login to connect to database using registration details
Table created.
You need to perform the following broad level steps to create this application:
<!--Home.html-->
<html><body>
<tr>
<br/><a href="Login.html">Login</a><br/>
<br/><a href="Register.html">Register</a><br/>
</td>
Welcome to CMRCET
</td>
</tr>
</table>
</body></html>
Output:
<!--Login.html-->
<html> <body>
<center><h1>CMR College of Engineering & Technology</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td width="15%" valign="top" align="center">
<br/><a href="Login.html">Login</a><br/>
<br/><a href="Register.html">Register</a><br/>
</td>
<td valign="top" align="center"><br/>
<form action="login"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b> </td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>
</tr>
</table></form>
</td>
</tr>
K.Yellaswamy ,AssistantProfessor|CMR College of Engineering & Technology
</table>
E-mail:[email protected]
</body></html>
Output:
<!--Register.html-->
<html> <body>
<center><h1>CMR COLLEGE OF ENGINEERING & TECHNOLOGY</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td width="15%" valign="top" align="center">
<br/><a href="Login.html">Login</a><br/>
<br/><a href="Register.html">Register</a><br/>
</td>
<td valign="top" align="center"><br/>
<form action="register"><table>
<tr>
<td colspan="2" align="center"><b>Registration Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b> </td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td>Re-Password</td>
<td><input type="password" name="repass"/></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="addr"/></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="text" name="phno"/></td>
</tr>
<tr> <td>Email ID</td>
<td><input type="text" name="email"/></td>
</tr>
<tr> <td> </td>
<td> </td>
</tr>
<tr><td colspan="2" align="center"><input type="submit" value="Register"/></td>
</tr>
</table></form></td></tr></table></body></html>
//RegistrationServlet.java
package com.yellaswamy.servlets;
import javax.servlet.*;
import java.io.*;
import java.sql.*;
/**
* @author yellaswamy
*/
public class RegistrationServlet extends GenericServlet {
//Getting the DB Username, password & sqlstatement from servlet init parameter
String dbuser=getInitParameter("dbuser");
String dbpass=getInitParameter("dbpass");
String sqlst=getInitParameter("sqlstatement");
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
{
System.out.println("In service");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try {
String uname=req.getParameter("uname");
String pass= req.getParameter("pass");
String repass= req.getParameter("repass");
if (uname==null||uname.equals("")
||pass==null||pass.equals("")
||!pass.equals(repass)) {
out.println("<html><body><center>");
out.println("<li><i>Given details are not valid to register</i></li><br/>");
out.println("<li><i>Please try again later</i>");
out.println("</center></body></html>");
return;
}//if
ps.setString(1,uname);
ps.setString(2,pass);
ps.setString(3,addr);
ps.setString(4,phno);
ps.setString(5,email);
int count=ps.executeUpdate();
if (count==1||count==Statement.SUCCESS_NO_INFO){
out.println("<html><body>");
out.println("<center><h1>CMRCET</h1></center>");
out.println("<table border=\"1\" width=\"100%\" height=\"100%\">");
out.println("<tr>");
out.println("<td width=\"15%\" valign=\"top\" align=\"center\">");
out.println("<br/><a href=\"Login.html\">Login</a><br/>");
out.println("<br/><a href=\"Register.html\">Register</a><br/>");
out.println("</td>");
out.println("<td valign=\"top\" align=\"center\"><br/>");
out.println("<h3>Welcome, "+uname+"</h3><br/>");
out.println("<h2>Enjoy browsing the Site</h2>");
out.println("</td></tr></table>");
out.println("</body></html>");
}
else{
out.println("<html><body><center>");
out.println("Given details are incorrect<br/>");
out.println("<li><i>Please try again later</i>");
out.println("</center></body></html>");
}
}//try
catch(Exception e){
out.println("<html><body><center>");
out.println("<h2>Unable to the process the request try after some time</h2>");
out.println("</center></body></html>");
}//catch
}//service
import javax.servlet.*;
import java.io.*;
import java.sql.*;
/**
* @author yellaswamy
*/
public class LoginServlet extends GenericServlet {
System.out.println("In service");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try {
String uname=req.getParameter("uname");
String pass= req.getParameter("pass");
if (uname==null||uname.equals("")||pass==null||pass.equals("")) {
out.println("<html><body><center>");
out.println("<li><i>User Name and Password cannot be
empty</i></li><br/>");
out.println("<li><i>We cannot log you into your account at this time.
Please try again later</i>");
out.println("</center></body></html>");
return;
}//if
ps.setString(1,uname);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
if (rs.next()){
out.println("<html><body>");
out.println("<center><h1>CMR COLLEGE OF ENGINEERING &
Technology</h1></center>");
out.println("<table border='1' width='100%' height='100%'>");
out.println("<tr>");
out.println("<td width='15%' valign='top' align='center'>");
out.println("<br/><a href='Login.html'>Login</a><br/>");
out.println("<br/><a href='Register.html'>Register</a>");
out.println("</td>");
out.println("<td valign='top' align='center'><br/>");
out.println("<h3>Welcome, "+uname+"</h3><br/>");
out.println("<h2>Enjoy browsing the Site</h2>");
out.println("</td></tr></table>");
<context-param>
<param-name>driverClassName</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>
jdbc:oracle:thin:@localhost:1521:xe
</param-value>
</context-param>
<servlet>
<servlet-name>ls</servlet-name>
<servlet-class>com.yellaswamy.servlets.LoginServlet</servlet-class>
<init-param>
<param-name>dbuser</param-name>
<param-value>yellaswamy</param-value>
</init-param>
<init-param>
<param-name>dbpass</param-name>
<param-value>yellaswamy</param-value>
</init-param>
<init-param>
<param-name>sqlstatement</param-name>
<param-value>
select * from userdetails where uname=? and pass=?
</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>rs</servlet-name>
<servlet-class>
<init-param>
<param-name>dbuser</param-name>
<param-value>yellaswamy</param-value>
</init-param>
<init-param>
<param-name>dbpass</param-name>
<param-value>yellaswamy</param-value>
</init-param>
<init-param>
<param-name>sqlstatement</param-name>
<param-value>
insert into userdetails values(?,?,?,?,?)
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ls</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>rs</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Home.html</welcome-file>
</welcome-file-list>
</web-app>
E:\WTLABFINALPROGRAMS\cmrsite>tree/f
Folder PATH listing for volume data
Volume serial number is 08FA-885D
E:.
│ CMRSITE.docx
│ Home.html
│ Login.html
│ Register.html
│
└───WEB-INF
│ web.xml
│
├───classes
│ │ LoginServlet.java
│ │ RegistrationServlet.java
│ │
│ └───com
│ └───yellaswamy
│ └───servlets
│ LoginServlet.class
│ RegistrationServlet.class
│
└───lib
classes12.jar
ojdbc14.jar
http://localhost:8086/cmrsite/Register.html