Java J2ee Tutorials

Session Tracking Example JSP

Thursday, March 1, 2012


Session Tracking Example


Session tracking is maintain the state of a user through out the application.
There are four typical solutions to this problem.
  1. Session
  2. cookie
  3. Url-rewriting
  4. Hidden field
==================

1.Create a user login page "login-form.jsp"

login-form.jsp

User Login

Login Name
Password
===============

2.create a page to check the valid user.if it exists then it stores in the session forward to the "welcome-home.jsp" else it come back again "login-form.jsp".

login-form-action.jsp

<%@ page language="java" import="java.sql.*;"%>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println("MySQL Connect Example.");
Connection con = null;
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/cms";;
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,username,userPassword);
Statement st = conn.createStatement();
String strQuery = "SELECT count(*) FROM user WHERE loginId='"+userName+"' AND empPassword='"+password+"'";
out.println(strQuery);

ResultSet rs = st.executeQuery(strQuery);

if(rs.next())
{
if(rs.getInt(1)>0)
{
session.setAttribute("userid",userName);
response.sendRedirect("welcome-home.jsp");
}
else
{
response.sendRedirect("login-form.jsp");
}

}
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e) {
e.printStackTrace();
}

%>

===================
welcome-home.jsp

Free Career Predictions

0 comments:

Post a Comment