Wednesday, May 6, 2009

User Login in JSP

Every website and software in the world is having login facility. Login gives access rights to user and defines their role in website and application. Nobody can access website if they failure in proving their identity on website or application.
Registration is first step by login to website. We will keep focus on only user login in JSP.

User login contain two fields, first one important User ID. This is unique ID provided by site owner or software application itself or most of provide facility to choose user id themselves on their website of web application.

Second is password, it is secret field and user have to keep remember without sharing with anybody. This field gives authentication to user to login on the website. User ID and password keep isolate one user to other users.

We have three forms of JSP pages.

login.jsp take input from user, mainly user id and password then submitted to server for further processing. This process handles with database. Database has a SQL table name usermaster. Usermaster table is having number of fields which are not using in login process. We need user id, password, user type, user level, first name, last name.

User type field in database explain user type as e.g. admin role, power user role, moderator role, end user role. User levels field explain about permission defined to user. Read, write, update, view are permission on user can work accordingly to these permission. This certainly is not using in current login facility. This can be useful after user login successfully and work in application.


SQL usermaster Table

CREATE TABLE `usermaster` (
`sUserID` varchar(45) NOT NULL,
`sEmail` varchar(250) NOT NULL,
`sFirstName` varchar(45) NOT NULL,
`sLastName` varchar(45) NOT NULL,
`iDOB` datetime NOT NULL,
`cGender` varchar(45) NOT NULL,
`iCountryID` int(10) unsigned NOT NULL,
`iCityID` varchar(45) NOT NULL,
`iUserType` varchar(45) DEFAULT NULL,
`iUserLevel` varchar(45) DEFAULT NULL,
`sPassword` varchar(45) NOT NULL,
`sForgetPassword` varchar(45) DEFAULT NULL,
`sContact` bigint(20) unsigned NOT NULL,
`sCreatedBy` varchar(45) DEFAULT NULL,
`dCreatedDate` datetime DEFAULT NULL,
`sModifiedBy` varchar(45) DEFAULT NULL,
`sModifiedDate` datetime DEFAULT NULL,
`sStatus` varchar(45) NOT NULL,
PRIMARY KEY (`sUserID`),
UNIQUE KEY `sEmail` (`sEmail`)
);

login.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
String error=request.getParameter("error");
if(error==null || error=="null"){
error="";
}
%>
<html>
<head>
<title>User Login JSP</title>
<script>
function trim(s)
{
return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

function validate()
{
if(trim(document.frmLogin.sUserName.value)=="")
{
alert("Login empty");
document.frmLogin.sUserName.focus();
return false;
}
else if(trim(document.frmLogin.sPwd.value)=="")
{
alert("password empty");
document.frmLogin.sPwd.focus();
return false;
}
}
</script>
</head>

<body>
<div><%=error%></div>
<form name="frmLogin" onSubmit="return validate();" action="doLogin.jsp" method="post">
User Name <input type="text" name="sUserName" /><br />
Password <input type="password" name="sPwd" /><br />
<input type="submit" name="sSubmit" value="Submit" />
</form>
</body>
</html>

doLogin.jsp mainly deals with database to check user id and password is matched with user trying to provide to get access from the server.

Our password field is encrypted with mysql password function. To decrypt password we have to use mysql password function again. If you are using Oracle or other database password function come with different name. Only user knows exact password and anybody can find out real password of the user. This increases the security of the system and reduces the hacking.

doLogin.jsp

<%@ page language="java" import="java.sql.*" errorPage="" %>
<%
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root", "");

ResultSet rsdoLogin = null;
PreparedStatement psdoLogin=null;

String sUserID=request.getParameter("sUserName");
String sPassword=request.getParameter("sPwd");
String message="User login successfully ";

try{
String sqlOption="SELECT * FROM usermaster where"
+" sUserID=? and sPassword=password(?) and sStatus=’A'";

psdoLogin=conn.prepareStatement(sqlOption);
psdoLogin.setString(1,sUserID);
psdoLogin.setString(2,sPassword);

rsdoLogin=psdoLogin.executeQuery();

if(rsdoLogin.next())
{
String sUserName=rsdoLogin.getString("sFirstName")+" "+rsdoLogin.getString("sLastName");

session.setAttribute("sUserID",rsdoLogin.getString("sUserID"));
session.setAttribute("iUserType",rsdoLogin.getString("iUserType"));
session.setAttribute("iUserLevel",rsdoLogin.getString("iUserLevel"));
session.setAttribute("sUserName",sUserName);

response.sendRedirect("success.jsp?error="+message);
}
else
{
message="No user or password matched" ;
response.sendRedirect("login.jsp?error="+message);
}
}
catch(Exception e)
{
e.printStackTrace();
}


/// close object and connection
try{
if(psdoLogin!=null){
psdoLogin.close();
}
if(rsdoLogin!=null){
rsdoLogin.close();
}

if(conn!=null){
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}

%>

doLogin.jsp match user id and password with database record. If record is matched with user field and password. It will set user id, user type, user level, first name, last name in session. This can access from session in further in application. It will finish processing and return to success.jsp page.

success.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java"%>

<html>
<head>
<title>Successfully Login by JSP</title>
</head>
<body>
Successfully login by JSP<br />
Session Value<br />
<%
out.print("UserName :"+session.getAttribute("sUserID")+"<br>");
out.print("First & Last Name :"+session.getAttribute("sUserName"));
%>
</body>
</html>

If user id and password is not matched, it will return back to login.jsp page and print error message to user, user id and password is not matched.

The example of login is given with source code, login.jsp, doLogin.jsp and success.jsp.

1 nhận xét:

pjyankee said...

i get below error in dologin.jsp..please help me out :



PWC6199: Generated servlet error:
string:///doLogin_jsp.java:11: com.mysql.jdbc.Connection is already defined in a single-type import

PWC6197: An error occurred at line: 24 in the jsp file: /doLogin.jsp
PWC6199: Generated servlet error:
string:///doLogin_jsp.java:73: incompatible types
found : java.sql.Connection
required: com.mysql.jdbc.Connection

PWC6197: An error occurred at line: 24 in the jsp file: /doLogin.jsp
PWC6199: Generated servlet error:
string:///doLogin_jsp.java:86: incompatible types
found : java.sql.PreparedStatement
required: com.mysql.jdbc.PreparedStatement