Download Document

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Computer file wikipedia , lookup

Versant Object Database wikipedia , lookup

Semantic Web wikipedia , lookup

Web analytics wikipedia , lookup

Transcript
Servlets:
Servlets are java programs which generates dynamic web content. Using servlets we can
create dynamic web pages effectively. Servlets are programs they run at server side.
Servlets are programs that run on a Web server, acting as a middle layer between a
requests coming from a Web browser and databases or applications on the HTTP server.
Server job is to:
1. Read any data sent by the user.
2. Look up any other information about the request that is embedded in the HTTP
request.
3. Generate the results based on the user request.
4. Format the results inside a document.
5. Set the appropriate HTTP response parameters.
6. Send the document back to the client.
DISADVANTAGES with Earlier Technologies (CGI ):
 CGI is oldest technique.
 For every request CGI creates a new process.
 Process creation takes huge amount of time and consumes more resources.
 There is limit on number of processes.
THE ADVANTAGES OF SERVLETS OVER “TRADITIONAL” CGI
Java servlets are efficient, easier to use, more powerful, more portable, safer, and cheaper
than traditional CGI (Common Gateway Interface).
Efficient
1.
In CGI a new process is started for each HTTP request where as with servlets,
the Java Virtual Machine stays running and handles each request using a
lightweight Java thread. Process creation takes huge amount of time. There is
limit on number of processes. CGI is the oldest technique to generate the content
dynamically.
2.
If there are N simultaneous requests to the same CGI program, the code for the
CGI program is loaded into memory N times. With servlets, however, there
would be N threads but only a single copy of the servlet class. Finally, when a
CGI program finishes handling a request, the program terminates. Servlets,
however, remain in memory even after they complete a response.
Convenient:
Servlets automatically parsing and decoding HTML form data, reading and setting HTTP
headers.
Powerful:
Multiple servlets can also share data, making it easy to implement database connection.
Servlets can also maintain information from request to request, simplifying techniques
like session tracking and caching of previous computations.
Portable:
Servlets are written in the Java programming language and follow a standard API. Server
can run virtually unchanged on Apache, Microsoft Internet Information Server (IIS), IBM
WebSphere, or Web Logic, Star Nine WebStar.
Secure:
Servlets are secure because of its Byte Code.
TO IMPLEMENT A SERVLET THE SOFTWARES REQUIRED
ARE:
1. JAVA 1.6 or 1.7
2. Apache Tomcat Server(call as ServletContainer)
3. Any Operating System
NOTE: below showing the installation of Apache Tomcat Server and setting the
CLASSPATH these are mandatory to execute a servlet.
TOMCAT INSTALLATION:
INSTALLATION PROCESS:
Step 1:
If you click on tomcat installer file then this program will automatically install
tomcat web server on computer. When you start installation process then initially
following window will appear.
Step 2:
Click next button then following window will appear then the license
agreement will appear accept the agreement by pressing “I Agree” button.
Step 3:
Then “Choose components” window will appear just click on next button.
Step 4:
The next window appeared is installation directory. If we want to change the
default path click on browse and change it. Then press next button.
Step 5:
Then you will get configuration window. Here you can set the connector port.
By default port is 8080 for Apache Tomcat Server. If you want to change, change the
port number. We can also set the user name and password.
Step 6:
The next window appeared is Java virtual machine installation folder if you
want to change, change the folder change it and then press Install button.
Step 7:
Then the installation process will start.
Step 8:
Press “Finish” button and the installation procedure gets completed.
PATH SETTING:
USER_VARIABLES:
Set the path for Tomcat:
Variable name: classpath
Variable value: C:\Program Files\Apache Software Foundation\Tomcat
6.0\lib\servlet-api.jar; C:\Program Files\Java\jdk1.7.0_03\lib\tools.jar;
And also configure
Variable name: path
Variable value: C:\Program Files\Java\jdk1.7.0_03\bin;
CONFIGURE TOMCAT:
The window will appear press start button to run the tomcat .
Click on Internet Explorer and then in the address bar type
http://localhost:8080 then Tomcat window will appear.
SERVLETS CREATION:
Two packages are used to create the servlets.Package manes set of classes and interfaces.
 javax.servlet.*;
 javax.servlet.http.*;
Servlets are created in many ways
 By implementing the Servlet Interface
 By extending the GenericServlet class or HttpServlet class
NOTE: Many programmers use HttpServlet class
Compiling and Installing the Servlet:
1. Check server is configured properly or not (i.e Tomcat server).
2. CLASSPATH environmental variable points to JAR files containing the standard
servlet classes and java classes.
Variable name: classpath
Variable value: C:\Program Files\Apache Software Foundation\Tomcat
6.0\lib\servlet-api.jar; C:\Program Files\Java\jdk1.7.0_03\lib\tools.jar;
Variable name: path
Variable value: C:\Program Files\Java\jdk1.7.0_03\bin;
The next step is to decide where to put the servlet classes. This location varies from
server to server, so refer to your Web server documentation for definitive directions.
Most servers have three distinct locations for servlet classes,
1. A directory for frequently changing servlet classes.
Servlets in this directory are automatically reloaded when their class file changes,
so you should use this directory during development. With Tomcat 6.0, place servlets
class file in rootdirectory/WEB-INF/classes.
2. A directory for infrequently changing servlet classes.
Servlets placed in this location are slightly more efficient since the server doesn’t
have to keep checking their modification dates. However, changes to class files in this
directory require you to restart the server. This option is the one to use for “production”
servlets deployed to a high-volume site. This directory is usually something like
rootdirectory/WEB-INF/classes, which is the default name with Tomcat
3. A directory for infrequently changing servlets in JAR files.
With the second option above, the class files are placed directly in the classes
directory or in subdirectories corresponding to their package name. Here, the class files
are packaged in a JAR file, and that file is then placed in the designated directory
Invoking the Servlet:
To invoke servlets use a URL of the form
http://host/servlet/ServletName.
Procedure for Creation and Execution of a servlet:
Following Software’s is required:
1. JAVA Software.
2. Apache Tomcat Server.
3. Web Browsers.
Procedure for servlet:
1.
Create a root directory(eg E:\Welcome)
2.
Under root direcory create Welcome.java file.
E:\Welcome
Welcome.java
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Response.setContentType(“text/html”);
out.println("Welcome to Servlet Programming");
}
}
3.
Compile the Welcome.java ,we get Welcome.class file in the root directory.(open
command prompt)
I. E:\Welcome>javac Welcome.java –classpath “C:\Program Files\Apache
Software Foundation\Tomcat 6.0\lib\servlet-api.jar”
(OR)
The user who set env variables already directly use option II
II. E:\Welcome>javac Welcome.java
Set the Environmental variable :
Variable name: classpath
Variable value: C:\Program Files\Apache Software Foundation\Tomcat
6.0\lib\servlet-api.jar
NOTE: At the time of compilation use servlet-api.jar file is mandatory otherwise
we can’t compile (it displays 6 errors)
4.
Under the root directory create WEB-INF direcoty.
5.
Move to E:\Welcome\WEB-INF and under create(classes,lib,web.xml all
lower case letters)
a. classes directory
b. lib directory
c. web.xml file(web.xml file is called Deployment Descriptor)
NOTE: web.xml file modification is very important
6.
Cut the Welcome.class file from the root directory and paste under classes
directory.
7.
Move to the root directory and generate a WAR(WEB ARCHIVE FILE)
E:\Welcome>jar cvf Welcome.war .
8.
After creating war file Deploy the war file in the server.
9.
To invoke the servlet Open your Web Browser and type the URL
http://localhost:8080/Welcome/WelcomeServlet
context path
protocol
port no
<url-pattern>
name
IP Address
Invoking the above servlet:
Open Web Browser and type
http://localhost:8080/Welcome/Welcome
The final step is to check that your HTML has no syntax errors that could cause
unpredictable results on different browsers.
A Servlet That Generates Plain Text:
Simple Servlet that outputs plain text. Before generating think about the process of
installing, compiling, and running of simple servlet so that we can easily execute any
kind of servlet.
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType(“text/plain”);//THIS LINE IS IMPORTNAT
out.println("Welcome to Servlet Programming");
}
}
Specifies that response is a plain text file
A Servlet That Generates HTML:
Instead of generating plain text servlet also generates HTML content, so make
modification in above code
response.setContentType("text/html");
1. Tell the browser that you’re sending it HTML.
2. Modify the println statements to build a legal Web page.
3. Check your HTML with a formal syntax validator.
Servlets to create other document types. servlets also generate Excel spreadsheets
(content type application/ vnd.ms-excel—see), JPEG images (content type image/jpeg—
see Section), and XML documents (content type text/xml).
Listing 3.3 HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Welcome</title></head>");
out.println("<body bgcolor=blue>");
out.println(“<h1>Generating the HTML file</h1>”)
out.println("</body>");
out.println("</html>");
}
}
The Life Cycle of a Servlet
There are three methods used to demonstrate the life cycle of a servlete are init( ),
service( ), and destroy( ). These methods are implemented by every servlet. In the
overall life cycle the init () &destroy () methods are called only once where as the
service () method is called ‘N’ no of times.

First, assume that a user enters a Uniform Resource Locator (URL) to a
Webbrowser. The browser then generates an HTTP request for this URL. This
request is then sent to the appropriate server.

Second, this HTTP request is received by the Web server. The server maps this
request to a particular servlet. The servlet is dynamically retrieved and loaded into
the address space of the server.

Third, the server invokes the init( ) method of the servlet. This method is invoked
only when the servlet is first loaded into memory. It is possible to pass
initialization parameters to the servlet so it may configure itself and database
initialization parameters and file initializations are takes place in this method.

Fourth, the server invokes the service( ) method of the servlet. This method is
called to process the HTTP request. You will see that it is possible for the servlet
to read data that has been provided in the HTTP request. It may also formulate an
HTTP response for the client. The servlet remains in the server’s address space
and is available to process any other HTTP requests received from clients. The
service( ) method is called for each HTTP request.

Finally, the server may decide to unload the servlet from its memory. The
algorithms by which this determination is made are specific to each server. The
server calls the destroy( ) method to relinquish any resources such as file handlers
and closing database connections that are allocated for the servlet.
init() method
(loading resources)
CLIENT
service() method
(accept resources)
Service() method
called N no of times
destroy() method
(unload resources)
PACKAGING SERVLETS:
To resolve the name space conflict use servlet packing. Programmer who developed two
servlets with same name then naming conflict rises so place the servlets under sepereate
directories.
For this make 4 modifications to implement servelet packing:
1. Insert a package statement in the class file.
package packagename;
2. Compile the class file by using option
E:\HelloServlet>javac –d . HelloServlet.java
(automatically a directory is created with name MyPack ,that directory conatins
class file )
3. Cut the MyPack directory and place it under classes directory.
4. Modify the web.xml file where the <urlpattern> line.
HelloServlet.java
package MyPack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet for testing the use of packages. */
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<HTML>\n" +
"<HEAD><TITLE>Hello (2)</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello (2)</H1>\n" +
"</BODY></HTML>");
}
}
SIMPLE HTML-BUILDING UTILITIES:
This code common to most of the programs
<HTML>
<HEAD><TITLE>...</TITLE>...</HEAD>
<BODY ...>...</BODY>
</HTML>
Rewriting this code is common to all the programs to avoid that develop some HTML
return routines so that make easy to use in all programs.
ServletUtilities.java:
package MyPack;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUtilities {
public static String headWithTitle(String title) {
return(
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
}
}
HelloServlet3.java
package MyPack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet for testing the use of packages
* and utilities from the same package.
*/
public class HelloServlet3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Hello";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR="red">\n" +
"<H1>" + title + "</H1>\n" +
"</BODY></HTML>");
}
}
HANDLING FORM DATA:
User enters data in the form on clicking the submit button it sends a request to the
appropriate server in which server process the request with the help of a servlet and
generates a result that is sent as part of response to the client.
In handling the form data concentrate on two factors
1. name attribute in the form
2. use request.getParamater() in servlet code
PROGRAM TO HANDLE THE FORM DATA:
Develop a servlet to handle the form data and validate user name and password. Display
whether she/he is authorized user or unauthorized user.
To implement this create the following files
 LoginServlet.html
 LoginServlet.java
LoginServlet.html
<html>
<body>
<form method="GET" action="http://localhost:8080/LoginServlet/LoginServlet">
FirstName<input type="text" name="fname"/>
Password<input type="password" name="pword"/>
<input type="submit" value="send"/>
</form>
</body>
</html>
LoginServlet.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.util.*;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
throwsIOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String fname=request.getParameter("fname");
String pword=request.getParameter("pword");
if(fname.equals("123") &&pword.equals("123"))
out.println("<h1> Authorized </h1>");
else
out.println("<h1> Unauthorized </h1>");
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
Description of the above example:
Servlets are java programs provide dynamic nature to the user. Servlets are programs they
run at server side.User takes the data from the form on clicking the submit button action
is performed by loading the appropriate servlet.
SHOWING CGI VARIABLES:
Servlet is the technology extension to CGI technology.CGI uses some standard variables
like DOCUMENT_ROOT,PATH_INFO,QUERY_STRING,SERVER_PORT,
SERVER_PROTOCOL,SERVER_SOFTWARE variables gives the information about
the environment.CGI uses some standard variables what are equivalent methods used in
servlets to get that information about the environment.
There are different methods like
CGI environment variables and corresponding Servlet methods
CGI ENVIRONMENT
VARIABLE NAME
SERVLET METHOD
SERVER_NAME
SERVER_PROTOCOL
SERVER_PORT
REQUEST_METHOD
PATH_INFO
PATH_TRANSLATED
request.getServerName()
request.getProtocol()
request.getServerPort()
request.getMethod()
request.getPathInfo()
request.getPathTranslated()
SCRIPT_NAME
DOCUMENT_ROOT
AUTH_TYPE
QUERY_STRING
REMOTE_HOST
REMOTE_ADDR
REMOTE_USER
CONTENT_TYPE
CONTENT_LENGTH
HTTP_ACCEPT
HTTP_USER_AGENT
HTTP_REFERER
request.getServletPath()
GetServletContext().getRealPath(“/”)
request.getAuthType()
request.getQueryString()
request.getRemoteHost()
request.getRemoteAddr()
request.getRemoteUser()
request.getContentType()
request.getContentLength()
request.getHeader(“Accept”)
request.getHeader(“User-Agent”)
request.getHeader(“Referer”)
ShowCGIVariables.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowCGIVariables extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String[][] variables =
{
{ "DOCUMENT_ROOT", getServletContext().getRealPath("/") },
{ "PATH_INFO", request.getPathInfo() },
{ "PATH_TRANSLATED", request.getPathTranslated() },
{ "QUERY_STRING", request.getQueryString() },
{ "REMOTE_ADDR", request.getRemoteAddr() },
{ "REMOTE_HOST", request.getRemoteHost() },
{ "REMOTE_USER", request.getRemoteUser() },
{ "REQUEST_METHOD", request.getMethod() },
{ "SCRIPT_NAME", request.getServletPath() },
{ "SERVER_NAME", request.getServerName() },
{ "SERVER_PORT", String.valueOf(request.getServerPort()) },
{ "SERVER_PROTOCOL", request.getProtocol() },
{ "SERVER_SOFTWARE", getServletContext().getServerInfo() }
};
String title = "Servlet Example: Showing CGI Variables";
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + title + "</H1>\n" +
"<TABLE BORDER=1>\n" +
" <TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>CGI Variable Name<TH>Value");
for(int i=0; i<variables.length; i++) {
String varName = variables[i][0];
String varValue = variables[i][1];
if (varValue == null)
varValue = "<I>Not specified</I>";
out.println(" <TR><TD>" + varName + "<TD>" + varValue);
}
out.println("</TABLE></CENTER></BODY></HTML>");
}
/** POST and GET requests handled identically. */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
OUTPUT:
SHOWING REQUEST HEADER:
Showing request header contains the information about what is the method used, what is
the version of the protocol and what is the user agent you are used and also provides the
information about the server(i.e. server running in local system and port number of the
server)
ShowRequestHeaders.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" +
request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" +
request.getProtocol() + "<BR><BR>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}
}
GENERATING THE SERVER RESPONSE: HTTP STATUS CODES:
Client send a request to the server the server request header contains the following
information like method name, protocol name etc in the same way server generates
response the response header contains the information of response code, protocol and
content type etc
The SERVER REQUEST HEADER & SERVER RESPONSE HEADER looks like
this:
SERVER REQUEST HEADER :(*method name & servlet name is important)
GET /servlet/WelcomeServlet HTTP/1.1
Host: Localhost
Header2: ...
...
HeaderN:
(Blank Line)
SERVER RESPONSE HEADER: :(* 200----status code is important)
Content-Type: text/html
Header2: ...
HTTP/1.1
200 OK
...
HeaderN: ...
(Blank Line)
<!DOCTYPE ...>
<HTML>
<HEAD>...</HEAD>
<BODY>
...
</BODY></HTML>
STATUS CODES: These are the status code generates by any server
1xx
100–199
Informational Messages
2xx
200–299
Successful
3xx
300–399
Redirecting
4xx
400–499
Error due to client
5xx
500–599
Error due to sever
SOME OF THE STATUS CODES AND THEIR DESCRIPTIONS:
100
200
202
204
205
301
302
303
(Continue)
(OK)
(Accepted)
(No Content)
(Reset Content)
(Moved Permanently)
(Found)
(See Other)
304
307
400
401
403
404
405
415
500
501
503
403
404
405
415
500
501
503
(Not Modified)
(Temporary Redirect)
(Bad Request)
(Unauthorized)
(Forbidden)
(Not Found)
(Method Not Allowed)
(Unsupported Media
Type)
(Internal Server Error)
(Not Implemented)
(Service Unavailable)
(Forbidden)
(Not Found)
(Method Not Allowed)
(Unsupported Media
Type)
(Internal Server Error)
(Not Implemented)
(Service Unavailable)
SETTING RESPONSE HEADERS FROM SERVLETS:
To set the response header use setHeader() method of HttpServletResponse. This method
takes two strings: the header name and the header value.
• setHeader(String headerName, String headerValue)
This method sets the response header with the designated name to the given value. In
addition to the general-purpose setHeader method
HttpServlet Response also has two specialized methods to set headers that contain dates
and integers:
 setDateHeader(String header, long milliseconds)
 setIntHeader(String header, int headerValue)
 setContentType(String mimeType)
This method sets the Content-Type of servlets.
 setContentLength(int length)
This method sets the Content-Length header, which is useful if the browser
supports persistent (keep-alive) HTTP connections.
 addCookie(Cookie c)
This method inserts a cookie into the Set-Cookie header.
 sendRedirect(String address)
the sendRedirect method sets the Location header as well as setting the status
code to 302.
General Examples:
Problem:
Develop a servlet to navigate to the HomePage basing on the validation without using
static resources?
Solution:
Static resources menas HTML files,Plain text files.
To provide solution to this develop three servlets named
1. LoginServlet.java
2. HomeServlet.java
3. Validate.java
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Welcome</title></head>");
out.println("<body bgcolor=blue>");
out.println("<form action=http://localhost:8080/LoginServlet/Validate>");
out.println("<h2>UserName</h2> <input type=text name=uname></input><br>");
out.println("<h2>PassWord</h2> <input type=password name=pword></input><br>");
out.println("<input type=submit value=send></input>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Validate extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String pword=request.getParameter("pword");
if(name.equals("murthy")&&pword.equals("murthy"))
{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/HomeServlet");
rd.include(request, response);
}
else
out.println("<h1>Un Authorized User</h1>");
}
}
HomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Home Page</h1>");
}}
web.xml
<web-app>
<servlet>
<servlet-name>Validate</servlet-name>
<servlet-class>Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>HomeServlet</servlet-name>
<servlet-class>HomeServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/HomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>LoginServlet</welcome-file>
</welcome-file-list>
</web-app>