Answer:
We create a table which has the column username and password. The html page has the text box to take username and password and it validate in JSP page. If username and password are matched it displays welcome message.
Create table:
Create table userlist (username varchar2(20), password varchar2(10));
In the below example we are using Oracle database with type 4 driver to connect the JSP program.
input.html
<!doctype html>
<html lang="en">
<head>
<title>Welcome </title>
</head>
<body>
<form method = "post" action = "JspDB.jsp">
<fieldset style="width:23%; background-color:#b3d1ff">
<h3><center> Login Page</center></h3>
<hr>
<table>
<tr>
<td>Username:</td>
<td> <input type = "text" name = "uname"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" name = "pwd"></td>
</tr>
<tr>
<td></td>
<td><input type = "submit" value="check detail" name = "s1"></td>
</tr>
</table>
</fieldset>
</form>
<a href="JspDB.jsp? s1=link">Get all user detail</a>
</body>
</html>
JspDB.jsp
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%!
Connection con;
PreparedStatement ps1, ps2;
public void jspInit()
{
try
{
//loading the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//establish the connection
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "local", "test");
//create statement object
ps1 = con.prepareStatement("select count(*) from userlist where username = ? and password=?");
ps2 = con.prepareStatement("select * from userlist");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
<%
String param = request.getParameter("s1");
if(param =="link")
{
ResultSet rs = ps2.executeQuery();
out.println("<table>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getString(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td");
out.println("</tr>");
}
out.println("</table>");
rs.close();
}
else
{
//write jdbc code for authentication
String user = request.getParameter("uname");
String pass = request.getParameter("pwd");
//set form data as param value
ps1.setString(1,user);
ps1.setString(2,pass);
//excute the query
ResultSet rs = ps1.executeQuery();
int cnt = 0;
if (rs.next())
cnt = rs.getInt(1);
if(cnt == 0)
out.println("<b><i><font color=red>Invalid credential</fonr></i></b>");
else
{
out.println("<form><fieldset style= width:25%; >");
out.println("<b><i><font color=red>valid credential..</fonr></i></b><br>");
out.println("<b><i><font size=6 color=blue>Welcome to My Page</fonr></i></b>");
out.println("</fieldset></form>");
}
}
%>
<%!
public void jspDestroy()
{
try
{
//colse
ps1.close();
ps2.close();
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
web.xml
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/input.html</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Output:

The username and password is correct, so it displays the welcome message.



