Tuesday, 6 September 2016

How to create login page in jsp with mysql database

                        In this post, we will see how to create log in (User Id and Password) page in JSP.
                        Here, frontend and backend programs are in JSP while database used is Mysql. Database name is "test", Database user name is also "test" and password is "123". Table name in which user id and password are saved is "useridpw". Table's configuration is shown in following table:


              One record of User Id and Password is saved to this table. You can see in following screenshot:

               Now, go throught the following programs:
auth.jsp
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>

<html>
<head>
</head>
<body>

<font color=blue>

<h1> Enter Details into the following Form: </h1>

<form action="authbackend.jsp" method="post">
User Id <input type=text name=userid /> <br /><br />
Password <input type=password name=pw /> <br /><br />

<input type=submit value=Submit>

</font>
</form>

</body>
</html>


authbackend.jsp
<%@ page import="java.sql.*" %>
<html>

<head>
</head>

<body>

<br><br>
<%
String userid="";
String pw="";

userid=request.getParameter("userid");
pw=request.getParameter("pw");
%>

<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String userName ="test";
String password="123";

int flag=0;

Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db,userName,password);

String query="select * from useridpw";
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
%>
<%
while(rs.next())
{
if(userid.equals(rs.getString(1)) && pw.equals(rs.getString(2)))
   {
       flag=1;
       
   } 
}

if(flag==1)
   {
     out.println("<font color=blue size=5><b>"+"Valid User Id and Password"+"</b></font>");
   }
else
   {
     out.println("<font color=blue size=5><b>"+"Invalid User Id OR Password. Please enter again."+"</b></font>");
     out.println("<br /><br /><a href=auth.jsp>Back To Previous Page</a>");
   }

%>
<%
}
catch(Exception e)
{
e.printStackTrace();
}
%>

<br />
<br />

</body>
</html>

No comments:

Post a comment