Replacement algorithms are essential for efficient memory use in computers. The choice of algorithm affects system performance, especially in cache and virtual memory. Real systems use approximations of LRU or custom policies for speed and efficiency.

lalithaacse 0 views 89 slides Oct 08, 2025
Slide 1
Slide 1 of 89
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89

About This Presentation

common gateway interface


Slide Content

Common Gateway Interface(CGI)
•CGIis actually an external application which is written by using any of the
programming languages like CorC++and this is responsible for
processing client requests and generating dynamic content
•In CGI application, when a client makes a request to access dynamic Web
pages, the Web server performs the following operations :
–It first locates the requested web pagei.ethe required CGI application
using URL.
–It then creates a new process to service the client’s request.
–Invokes the CGI application within the process and passes the request
information to the server.
–Collects the response from CGI application.
–Destroys the process, prepares the HTTP response and sends it to the
client.

•inCGIserver has to create and destroy the process for every
request
•Its easy to understand that this approach is applicable for
handling few clients
•as the number of client increases the workload on the server
increases and so the time taken to process requests increases

Difference between Servlet and CGI
Servlets CGI
●Servlets are portable and efficient.●CGI is not portable
●In Servlets, sharing of data is
possible.
●In CGI, sharing of data is not
possible.
●Servlets can directly communicate
with the web server.
●CGI cannot directly communicate
with the web server.
●Servlets are less expensive than
CGI.
●CGI are more expensive than
Servlets.
●Servlets can handle the cookies.●CGI cannot handle the cookies.

Servlets
•Servlets are java programs that run on web or application
servers, acting as middle layer between request coming from
the web browsers or other HTTP clients and database servers
•Servlets process user request, produce the results and sends the
results as a response to the user

Advantages of Java Servlets
•Portability
•We can develop a servlet on Windows machine running the tomcat server
or any other server and later we can deploy that servlet effortlessly on
any other operating system like Unix server running on the
iPlanet/Netscape Application server
•Powerful
–Servlets can share data among each other, they even make the database
connection pools easy to implement.
–They can maintain the session by using the session tracking mechanism which
helps them to maintain information from request torequest.
•Safety
•. Java's automatic garbage collection and a lack of pointers means that
servlets are generally safe from memory management problems.

•Efficiency
–As compared to CGI the servlets invocation is
highly efficient.
–When the servlet get loaded in the server, it
remains in the server's memory as a single object
instance
–Multiple concurrent requests are handled by
separate threads so we can say that the servlets
are highly scalable
CGIServlets

•Extensibilty
–The servlet API is designed in such a way that it
can be easily extensible.
–the servlet API support Http Servlets, but in later
date it can be extended for another type of
servlets
•Inexpensive
–There are number offree web servers available
for personal use or for commercial purpose

Life Cycle of a Servlet
•The entire life cycle of a Servlet is managed by theServlet
containerwhich uses thejavax.servlet.Servletinterface
•The Servlet life cycle mainly goes through four stages:
–Loading a Servlet.
–Initializing the Servlet.
–Request handling.
–Destroying the Servlet.

Servlet life cycle diagram

•Loading a Servlet
–The servlet container loads the servlet during startup or when
the first request is made
–The loading of the servlet depends on the attribute <load-on-
startup> of web.xml file.
–If the attribute <load-on-startup> has a positive value then the
servlet is load with loading of the container otherwise it load
when the first request comes for service.
–After loading of the servlet, the container creates the instances
of the servlet.

•Initialization:
–After creating the instances, the servlet container calls the
init() method and passes the servlet initialization
parameters to the init() method.
–The init() must be called by the servlet container before the
servlet can service any request.
–The initialization parameters persist untill the servlet is
destroyed.
–The init() method is called only once throughout the life
cycle of the servlet

•Servicing the Request
–After successfully completing the initialization process, the
servlet will be available for service.
–Servlet creates seperate threads for each request.
–The sevlet container calls the service() method for servicing
any request.
–The service() method determines the kind of request and
calls the appropriate method (doGet() or doPost()) for
handling the request and sends response to the client using
the methods of the response object.

•Destroying the Servlet
–If the servlet is no longer needed for servicing any request,
the servlet container calls the destroy() method
–Like the init() method this method is also called only once
throughout the life cycle of the servlet
–Calling the destroy() method indicates to the servlet
container not to sent the any request for service and the
servletreleases all the resources associated with it
–Java Virtual Machine claims for the memory associated
with the resources for garbage collection.

Servlet API
•Javax.servlet
The javax.servlet package contains a number of classes and
interfaces that describe and define the contracts between a
servlet class and the runtime environment
•Javax.servlet.http
The javax.servlet.http package contains a number of classes
and interfaces that describe and define the contracts between a
servlet class running under the HTTP protocol

javax.servletpackage
•javax.servlet.Servlet
•javax.servlet.ServletConfig
•javax.servlet.ServletContext
•javax.servlet. RequestDispatcher
•javax.servlet.ServletRequest
•javax.servlet.ServletResponse
•javax.servlet.GenericServlet

Javax.servlet.Servlet interface

Javax.servlet.ServletConfig

Javax.servlet.ServletContext

Javax.servlet.ServletRequest

Javax.servlet.ServletResponse

javax.servlet. RequestDispatcher
•Defines an object that receives requests from the client and sends them
to any resource (such as a servlet, HTML file, or JSP file) on the server
•public void forward(ServletRequestrequest,
ServletResponseresponse) throws ServletException,
java.io.IOException
•Forwards a request from a servlet to another resource (servlet, JSP file, or
HTML file) on the server
•public void include(ServletRequestrequest,
ServletResponseresponse) throws ServletException,
java.io.IOException
•Includes the content of a resource (servlet, JSP page, HTML file) in the
response. In essence, this method enables programmatic server-side
includes.

javax.servlet.GenericServlet class
•GenericServletclass implements Servlet, ServletConfigand
Serializableinterfaces.
•It provides the implementation of all the methods of these
interfaces except the service method.
•GenericServlet class can handle any type of request so it is
protocol-independent.

●public void init(ServletConfig config)----to initialize the servlet.
●public abstract void service(ServletRequest request,
ServletResponse response)------provides service for the
incoming request.
●public void destroy()----is invoked only once throughout the life
cycle and indicates that servlet is being destroyed.
●public ServletConfig getServletConfig()------returns the object
of ServletConfig.
●public String getServletInfo()-----returns information about
servlet such as writer, copyright, version etc.

●public ServletContext getServletContext()returns the object of
ServletContext.
●public String getInitParameter(String name)returns the parameter
value for the given parameter name.
●public Enumeration getInitParameterNames()returns all the
parameters defined in the web.xml file.
●public String getServletName()returns the name of the servlet object.
●public void log(String msg)writes the given message in the servlet
log file.
●public void log(String msg,Throwable t)writes the explanatory
message in the servlet log file and a stack trace.

javax.servlet.httppackage
•Javax.servlet.http.HttpServlet
•javax.servlet.http. HttpServletRequest
•javax.servlet.http. HttpServletResponse
•javax.servlet.http. HttpSession
•javax.servlet.http.Cookie Class

javax.servlet.http.HttpServlet
•The HttpServlet class extends the GenericServlet class and
implements Serializable interface
•It provides http specific methods such as doGet, doPost,
doHead, etc.
●public void service(ServletRequest req,ServletResponse res)dispatches the
request to the protected service method by converting the request and response
object into http type.
●protected void service(HttpServletRequest req, HttpServletResponse res)
receives the request from the service method, and dispatches the request to the
doXXX() method depending on the incoming http request type.
●protected void doGet(HttpServletRequest req, HttpServletResponse res)
handles the GET request. It is invoked by the web container.

●protected void doPost(HttpServletRequest req, HttpServletResponse res)handles the POST
request. It is invoked by the web container.
●protected void doHead(HttpServletRequest req, HttpServletResponse res)handles the HEAD
request. It is invoked by the web container.
●protected void doOptions(HttpServletRequest req, HttpServletResponse res)handles the
OPTIONS request. It is invoked by the web container.
●protected void doPut(HttpServletRequest req, HttpServletResponse res)handles the PUT
request. It is invoked by the web container.
●protected void doTrace(HttpServletRequest req, HttpServletResponse res)handles the
TRACE request. It is invoked by the web container.
●protected void doDelete(HttpServletRequest req, HttpServletResponse res)handles the
DELETE request. It is invoked by the web container.

–Base class for web-based servlets
–Overrides method service
•Request methods:
–GET-retrieve HTML documents or image
–POST-send server data from HTML form
–Methods doGetand doPostrespond to GET
and POST
•Called by service
•Receive HttpServletRequestand
HttpServletResponse (return void) objects

HttpServletRequestinterface
–Object passed to doGetand doPost
–Extends ServletRequest
•Methods
–String getParameter( String name )
•Returns value of parameter name(part of GETor POST)
–Enumeration getParameterNames()
•Returns names of parameters (POST)
–String[] getParameterValues( String name
)
•Returns array of strings containing values of a parameter
–Cookie[] getCookies()
•Returns array of Cookieobjects, can be used to identify client

HttpServletResponse
•HttpServletResponse
–Object passed to doGetand doPost
–Extends ServletResponse
•Methods
–void addCookie( Cookie cookie )
•Add Cookieto header of response to client
–ServletOutputStream getOutputStream()
•Gets byte-based output stream, send binary data to client
–PrintWriter getWriter()
•Gets character-based output stream, send text to client
–void setContentType( String type )
•Specify MIME type of the response (Multipurpose Internet Mail
Extensions)
•MIME type “text/html” indicates that response is HTML document.
•Helps display data

Javax.servlet.http.HttpServletRequest

Javax.servlet.http.HttpServletResponse

Javax.servlet.http.HttpSession
•HttpSession provides a way to identify a user
across more than one page request or visit to a
Web site and to store information about that user
•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.

Javax.servlet.http.HttpSession

Javax.sevlet.http.Cookie
•A cookieis stored on a client and contains state information.
•Cookies are valuable for tracking user activities
•A cookie, a small amount of information sent by a servlet to a
Web browser, saved by the browser, and later sent back to the
server.
•A cookie's value can uniquely identify a client, so cookies are
commonly used for session management.
•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.

Javax.servlet.http.Cookie

Javax.servlet.http.HttpServlet

Session Tracking:
•Http is a statelessprotocol, means that it can't persist the
information.
•It always treats each request as a new request.
•In Http client makes a connection to the server, sends the
request., gets the response, and closes the connection.

•In session management client first make a request for any
servlet or any page, the container receives the request and
generate a unique session ID and gives it back to the client
along with the response.
•This ID gets stores on the client machine. Thereafter when the
client again sends a request to the server then it also sends the
session Id with the request. There the container sees the Id and
sends back the response.

•Session Tracking can be done in Four ways:
–Hidden Form Fields:
–Cookies
–HttpSession
–URL Rewriting

Cookies in Servlet
•Acookieis 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.

How Cookie works
•By default, each request is considered as a new
request.
•In cookies technique, we add cookie with response
from the servlet.
•So cookie is stored in the cache of the browser.
•After that if request is sent by the user, cookie is
added with request by default. Thus, we recognize the
user as the old user.

•Types of Cookie
–Non-persistent cookie
–Persistent cookie
•Non-persistent cookie
–It isvalid for single sessiononly. It is removed
each time when user closes the browser.
•Persistent cookie
–It isvalid 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
–Simplest technique of maintaining the state.
–Cookies are maintained at client side.
•Disadvantage of Cookies
–It will not work if cookie is disabled from the
browser.
–Only textual information can be set in Cookie
object.

index.html
<formaction="servlet1"method="post">
Name:<inputtype="text"name="userName"/><
br/>
<inputtype="submit"value="go"/>
</form>

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassFirstServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throws
IOException,ServletException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Stringn=request.getParameter("userName");
out.print("Welcome"+n);
Cookieck=newCookie("uname",n);//creatingcookieobject
response.addCookie(ck);//addingcookieintheresponse
//creatingsubmitbutton
out.print("<formaction='servlet2'>");
out.print("<inputtype='submit'value='go'>");
out.print("</form>");
out.close();
}
}

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassSecondServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResp
onseresponse)throws IOException,ServletExcepation{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Cookieck[]=request.getCookies();
out.print("Hello"+ck[0].getValue());
out.close();
}
}

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

HttpSession interface
•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:
–bind objects
–view and manipulate information about a session,
such as the session identifier, creation time, and
last accessed time.

<formaction="servlet1">
Name:<inputtype="text"name="userName"/><
br/>
<inputtype="submit"value="go"/>
</form>

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassFirstServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResponserespon
se)throws IOException ,ServletException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Stringn=request.getParameter("userName");
out.print("Welcome"+n);
HttpSessionsession=request.getSession();
session.setAttribute("uname",n);
out.print("<ahref='servlet2'>visit</a>");
out.close();
}
}

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassSecondServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throws IOException,ServletException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
HttpSessionsession=request.getSession(false);
Stringn=(String)session.getAttribute("uname");
out.print("Hello"+n);
out.close();
}
}

Hidden Form Field
•In case of Hidden Form Fielda hidden
(invisible) textfieldis used for maintaining the
state of an user.
•we store the information in the hidden field
and get it from another servlet
•the code to store value in hidden field
•<inputtype="hidden"name="uname"value=“
Rajashekar">

•Advantage of Hidden Form Field
–It will always work whether cookie is disabled or
not.
•Disadvantage of Hidden Form Field:
–It is maintained at server side.
–Extra form submission is required on each pages.
–Only textual information can be used.

•<formaction="servlet1">
•Name:<inputtype="text"name="userName"/
><br/>
•<inputtype="submit"value="go"/>
•</form>

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassFirstServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throws
IOException , ServletException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Stringn=request.getParameter("userName");
out.print("Welcome"+n);
//creatingformthathaveinvisibletextfield
out.print("<formaction='servlet2'>");
out.print("<inputtype='hidden'name='uname'value='"+n+"'>");
out.print("<inputtype='submit'value='go'>");
out.print("</form>");
out.close();
}
}

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassSecondServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResponserespon
se)
throws IOException,ServletEception
{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
//Gettingthevaluefromthehiddenfield
Stringn=request.getParameter("uname");
out.print("Hello"+n);
out.close();
}
}

URL Rewriting
•In URL rewriting, we append a token or identifier to the URL
of the next Servlet or the next resource.
•We can send parameter name/value pairs using the following
format:
•url?name1=value1&name2=value2&??
•A name and a value is separated using an equal = sign, a
parameter name/value pair is separated from another parameter
using the ampersand(&).

•Advantage of URL Rewriting
–It will always work whether cookie is disabled or not
(browser independent).
–Extra form submission is not required on each pages.
•Disadvantage of URL Rewriting
–It will work only with links.
–It can send Only textual information.

<formaction="servlet1">
Name:<inputtype="text"name="userName"/
><br/>
<inputtype="submit"value="go"/>
</form>

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassFirstServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse) throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
Stringn=request.getParameter("userName");
out.print("Welcome"+n);
//appendingtheusernameinthequerystring
out.print("<ahref='servlet2?uname="+n+"'>visit</a>");
out.close();
}
}

importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
publicclassSecondServletextendsHttpServlet{
publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
//gettingvaluefromthequerystring
Stringn=request.getParameter("uname");
out.print("Hello"+n);
out.close();
}
}

JDBC (Java DataBase Connectivity)

The Concept of JDBC
•Sun met the challenge in 1996 with the creation of
the JDBC driver and the JDBC API
•The JDBC driver developed by Sun was a
specification that described the detailed
functionality of a JDBC driver
•The specifications required a JDBC driver to be
•a translator that converts low-level proprietary DBMS
messages to low-level messages that are understood by
the JDBC API and vice versa

•JDBC drivers created by DBMS manufacturers have
to:
•Open a connection between the DBMS and the J2EE
application
•Translatelow-level equivalents of SQL statements sent
by the J2EE application into messages that can be
processed by the DBMS
•Return data that conforms to the JDBC specification to
the JDBC driver
•Return information, such as error messages, that
conforms to the JDBC specification to the JDBC driver
•Provide transaction management routines that
conform to the JDBC specification
•Close the connection between the DBMS and the J2EE
application

JDBC Driver Types
•The JDBC driver specification classifies JDBC drivers into four groups
•Each group is referred to as a JDBC driver type
•Type 1 JDBC to ODBC Driver
•Type 2 Java/Native Code Driver
•Type 3 JDBC Driver
•Type 4 JDBC Driver

Type 1 JDBC to ODBC Driver
•Microsoft was the first company to devise a way to create DBMS-independent database
programs when they created Open Database Connectivity (ODBC)
•ODBC is the basis from which Sun created JDBC
•Both ODBC and JDBC have similar driver specifications and an API
•The JDBC to ODBC driver, also called the JDBC/ODBC Bridge
•The JDBC to ODBC driver receives messages from a J2EE application that conforms to the
JDBC specification
•These messages are translated by the JDBC to ODBC driver into the ODBC message
format, which is then translated into the message format understood by the DBMS

Type 2 Java/Native Code Driver
•The Java/Native Code driver uses Java classes to generate platform-
specific code
•i.e, code only understood by a specific DBMS
•The manufacturer of the DBMS provides both the Java/Native Code
driver
and API classes so the J2EE application can generate the
platform-specific code
•disadvantage is the loss of some portability of code

Type 3 JDBC Driver
•The Type 3 JDBC driver, also referred to as the Java Protocol,
•is the most commonly used JDBC driver.
•It converts SQL queries into JDBC-formatted statements.
•The JDBC-formatted statements are translated into the format required by the DBMS.

Type 4 JDBC Driver
•Type 4 JDBC driver is also known as the Type 4 Database Protocol
•This driver is similar to the Type 3 JDBC driver, except SQL queries are
translated into the format required by the DBMS
•SQL queries do not need to be converted to JDBC-formatted systems
•the fastest way to communicate SQL queries to the DBMS

JDBC Packages
•JDBC API is contained in two packages
•java.sqlcontains core JDBC interfaces of the JDBC API.
•These include
•the JDBC interfaces that provide the basics for connecting to the
DBMS
•and interacting with data stored in the DBMS.
•java.sql is part of the J2SE
•javax.sqlextends java.sql and is in the J2EE and J2ME
•These include
•the JDBC interface that interacts with Java Naming and Directory
Interface (JNDI) a
•nd the JDBC interface that manages connection pooling

JDBC Process
•Load the JDBC Driver
•The JDBC driver must be loaded before the J2ME application can connect to the
DBMS
•The Class.forName() method is used to load the JDBC driver
•//Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver"); for Type1 driver
•Class.forName( "com.mysql.jdbc.Driver");//for mysql
•Connect to the DBMS
•Once the driver is loaded, the J2EE application must connect to the DBMS using
the DriverManager.getConnection() method
•java.sql.DriverManager class is the highest class in the java.sql hierarchy
•and is responsible for managing driver information
•Three parameters are required
•URL
•User ID
•Password

•//String url = "jdbc:odbc:DSN"; for Type 1 driver
•String url = "jdbc:mysql://localhost:3306/cse”//for mysql
•String userID = “username";
•String password = “password";
•Connection con= DriverManager.getConnection(url,userID,password);
•Create and Execute an SQL Statement
•The Connect.createStatement() is used to create a Statement object
•The Statement object is then used to execute a query and return a ResultSet
object
•ResultSet contains the response from the DBMS, which is usually one or more
rows of information
•String query = "SELECT * FROM emp";
•Statement stmt=con.createStatement();
•ResultSet rs=stmt.executeQuery (query);
•Process Data Returned by the DBMS
while ( rs.next()){
FirstName = rs.getString (“FirstName”) ;
LastName = rs.getString (“LastName”) ;
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
•Terminate the Connection to the DBMS
•con.close();

String url = "jdbc:mysql://localhost:3306/cse ";
String userID = “username";
String password = “password";
try{
Class.forName( " com.mysql.jdbc.Driver ");
Connection con= DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error) {
System.err.println("Unable to load the JDBC/ODBC bridge." + error);
System.exit(1);
}
catch (SQLException error) {
System.err.println("Cannot connect to the database." + error);
System.exit(2);
}

Index.html
<html>
<head>
<title>Login Validation</title>
</head>
<body>
<center>
<form method="post" action="ValidLogin1">
<table>
<tr>
<td>Enter name:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Enter Password:</td>
<td><input type="password"
name="password"></td>
</tr>
</table>
<input type="Submit" value="Submit">
<input type="Reset" value="Reset">
</form>
</center>
</body></html>

ValidLogin.java
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.sql.*;
public class ValidLogin extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("username");
String pass = request.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cse","root","");

PreparedStatement pst = conn.prepareStatement("select
* from users where username=? and password=?");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("Correct login credentials");
}
else {
out.println("Incorrect login credentials");
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
}
}

web.xml
<web-app>
<servlet>
<servlet-name>ValidLogin</servlet-name>
<servlet-class>ValidLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidLogin</servlet-name>
<url-pattern>/ValidLogin</url-pattern>
</servlet-mapping>
</web-app>
Tags