File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes How to avoid Session Collision  between Jsp And Servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "How to avoid Session Collision  between Jsp And Servlets" Watch "How to avoid Session Collision  between Jsp And Servlets" New topic
Author

How to avoid Session Collision between Jsp And Servlets

Elanges waran
Greenhorn

Joined: Dec 13, 2007
Posts: 17
Hi All,

I developed a web application using JSP & servlet. I created LoginController servlet to get user name to JSP Forms. If More than 2 user access the same form that time the form data would be mixed between users and also refresh (press F5 Key on the browser)the forms repeatedly the same collision will be occurred. Kindly reply any one to avoid this exception...

The Following code is used for LoginController with Active Directory intergration:

/**
* File Name : Logincontroller.java
* Description : Logincontroller is a servlet that handles request & reponse to
* login.jsp
*/

package controller;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Employee;

import com.sun.security.auth.module.NTSystem;

import dao.impl.LoginDAO;
import dao.impl.ViewSuggestionDAOImpl;

/**
* Servlet implementation class for Servlet: Logincontroller
*
*/
public class Logincontroller extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

/**
*
*/
private static final long serialVersionUID = 1L;

private Employee user;
private Employee emp;
private LoginDAO loginDAO;
private List list;
private Iterator iterator;

private FileInputStream fstream;
private DataInputStream in;
private File file;

private FileInputStream ADstream;
private DataInputStream ADin;
private File ADfile;

private String dept_agent;
private String emp_email;
ViewSuggestionDAOImpl view;
HttpSession session;


/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/

public Logincontroller() {
super();
user = new Employee();
loginDAO = new LoginDAO();
list = new ArrayList();
view = new ViewSuggestionDAOImpl();
} //End of Constructor

/**
* This method handles doGet operation for this servlet
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} //End Of doGet()

/**
* This method handles doGet operation for this servlet
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String filepath = "";
String empId = "";
String totalempid = "";
String[] adminempId = {};

String filePath1 ="";
filePath1 = getServletContext().getRealPath("/properties/dbconnection.properties");

ADfile = new File(filePath1);
ADstream = new FileInputStream(ADfile);
ADin = new DataInputStream(ADstream);
String host ="";
session = request.getSession(true);
/*Session Intialized */
session.setAttribute("empname","");
session.setAttribute("empid","");
session.setAttribute("email","");
session.setAttribute("dept_id","");
session.setAttribute("dept","");
session.setAttribute("dept_email","");
session.setAttribute("depagent","");
session.setAttribute("desig","");
session.setAttribute("eligible","");

String user_name = request.getParameter("username");
String password = request.getParameter("pass");

String AD_username = "";
String AD_pass = "";
String ad = "";

String domain_ext="";
String domain_name="";

while (ADin.available() !=0){
String data = "";
String tot_val = "";

//try{
tot_val = ADin.readLine();
data = tot_val.substring(0,tot_val.indexOf("="));
//}catch (Exception e) {
//}

if(data.equals("host")) {
host = tot_val.substring(tot_val.indexOf("=")+1,tot_val.length());
}
if(data.equals("AD_username")) {
AD_username = tot_val.substring(tot_val.indexOf("=")+1,tot_val.length());
}
if(data.equals("AD_password")) {
AD_pass = tot_val.substring(tot_val.indexOf("=")+1,tot_val.length());
}
if(data.equals("domain_ext")) {
domain_ext = tot_val.substring(tot_val.indexOf("=")+1,tot_val.length());
}
if(data.equals("domain_name")) {
domain_name = tot_val.substring(tot_val.indexOf("=")+1,tot_val.length());
}
if(data.equalsIgnoreCase("AD")) {
ad = tot_val.substring(tot_val.indexOf("=")+1,tot_val.length());
}
}
if(ad.equalsIgnoreCase("YES")){
emp_email = ADLoginAuthentication(host,AD_username,user_name,AD_pass,domain_name, domain_ext);
list = loginDAO.getData(emp_email);
}
else{
list = loginDAO.getData(user_name, password);
}


iterator = list.iterator();
while(iterator.hasNext()) {
user = (Employee) iterator.next();
}
if(list.size() > 0) {
setIntoSession(user);
response.sendRedirect("suggestion/index.jsp");
}
else {
response.sendRedirect("suggestion/invalid.jsp");
}
}catch(Throwable e){
e.printStackTrace();
}finally{
}
} // End of doPost()

/* (non-Java-doc)
* @see String ADLoginAuthentication(String host,String username,String password,String domain_ext)
*/
private String ADLoginAuthentication(String host,String username,String password,String domain_ext) {
String mail = "";
String searchBase;
String searchFilter;

Hashtable ldapEnv = new Hashtable();
NTSystem system = new NTSystem();
String domain = system.getDomain()+"."+domain_ext;
String user =System.getProperty("user.home");
String port="389";
String urlDC="ldap://"+host+":"+port+"/";
String dcList="";
try {
dcList="DC="+domain.replaceAll("\\.",",DC=");
} catch (Exception ex) {
System.err.println("Error in regular expression kit: " + ex.getMessage());
}

ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

ldapEnv.put(Context.SECURITY_AUTHENTICATION,"simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL,username);
ldapEnv.put(Context.SECURITY_CREDENTIALS,password);
ldapEnv.put(Context.PROVIDER_URL, urlDC);

searchBase= dcList;
searchFilter = "(&(objectClass=person)(anr="+username+"))";
String objAttribs[]={"mail"};

try {
// Create an LDAP directory context
LdapContext ctx = new InitialLdapContext(ldapEnv,null);
// Search controls are used to assign the scope of the search and the attributes to be returned
SearchControls srchInfo = new SearchControls();
// We want to browse all of the sub-branches of our directory tree
srchInfo.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Identify the attributes of the objects that we want to return
srchInfo.setReturningAttributes(objAttribs);
int nodirObjects = 0;
// Submit the query to the LDAP directory service and return the results in a NamingEnumeration object
NamingEnumeration dirObjects = ctx.search(searchBase, searchFilter, srchInfo);
// Loop through dirObjects returned by the LDAP query
SearchResult dirObject1 = (SearchResult)dirObjects.next();
while (dirObjects != null && dirObjects.hasMoreElements()) {
SearchResult dirObject = (SearchResult)dirObjects.next();
// Display name and requested attributes to the console
String email = "";
for (int i=0; i<objAttribs.length; i++) {
email = String.valueOf(dirObject.getAttributes().get(objAttribs));
String mail_id = email.substring(email.indexOf(":")+1,email.length()).trim();
if(mail_id.equalsIgnoreCase(username)) {
mail = mail_id;
}
}
// Increment the counter
nodirObjects++;
}
ctx.close();
}
catch (NamingException ex) {
System.err.println("Error during query: " + ex.getMessage());
}
return mail;
}// End of ADLoginAuthentication()




private String ADLoginAuthentication(String host,String Aduser_name,String user_name,String password,String domain_name, String domain_ext) {
String mail = "";
String searchBase;
String searchFilter;

Hashtable ldapEnv = new Hashtable();

String domain = domain_name+"."+domain_ext;
String user = user_name+"@"+domain;
String username = Aduser_name;
String port="389";
String urlDC="ldap://"+host+":"+port+"/";
String dcList="";
try {
dcList="DC="+domain.replaceAll("\\.",",DC=");
} catch (Exception ex) {
System.err.println("Error in regular expression kit: " + ex.getMessage());
}

ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.SECURITY_AUTHENTICATION,"simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL,username);
ldapEnv.put(Context.SECURITY_CREDENTIALS,password);
ldapEnv.put(Context.PROVIDER_URL, urlDC);

searchBase= dcList;
searchFilter = "(&(objectClass=person)(anr="+user_name+"))";
String objAttribs[]={"mail"};

try {
// Create an LDAP directory context
LdapContext ctx = new InitialLdapContext(ldapEnv,null);
// Search controls are used to assign the scope of the search and the attributes to be returned
SearchControls srchInfo = new SearchControls();
// We want to browse all of the sub-branches of our directory tree
srchInfo.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Identify the attributes of the objects that we want to return
srchInfo.setReturningAttributes(objAttribs);
int nodirObjects = 0;
// Submit the query to the LDAP directory service and return the results in a NamingEnumeration object
NamingEnumeration dirObjects = ctx.search(searchBase, searchFilter, srchInfo);
// Loop through dirObjects returned by the LDAP query
//SearchResult dirObject = (SearchResult)dirObjects.next();
while (dirObjects != null && dirObjects.hasMoreElements()) {
SearchResult dirObject = (SearchResult)dirObjects.next();
// Display name and requested attributes to the console
String email = "";
for (int i=0; i<objAttribs.length; i++) {
email = String.valueOf(dirObject.getAttributes().get(objAttribs));
String mail_id = email.substring(email.indexOf(":")+1,email.length()).trim();
if(mail_id.equalsIgnoreCase(user)) {
mail = mail_id;
}
}
// Increment the counter
nodirObjects++;
}
ctx.close();
}
catch (NamingException ex) {
System.err.println("Error during query: " + ex.getMessage());
}
return mail;
}
/**
*
* @param user
* setIntoSession() is a synchronized methos to set all necessary
* values in to the session for entire appliation
*
*/
public synchronized void setIntoSession(Employee user){
try {
session.setAttribute("empname",user.getEmpName());
session.setAttribute("empid",user.getEmpId());
session.setAttribute("email",user.getEmp_email());

session.setAttribute("dept_id",user.getDepartment_id());
session.setAttribute("dept",user.getDepartment());

dept_agent = view.findByDepartment(user.getDepartment());


List emp_list = view.findByID(dept_agent);
Iterator iterate = emp_list.iterator();
while(iterate.hasNext()) {
emp = (Employee)iterate.next();
session.setAttribute("dept_email",emp.getEmp_email());
}

if(user.getImd_super_id()==null){
session.setAttribute("imdsuper",emp.getEmpName());
session.setAttribute("imd_super_id",dept_agent);
session.setAttribute("imd_super_email", emp.getEmp_email());
}
else {
session.setAttribute("imdsuper",user.getImmediateSupervisor());
session.setAttribute("imd_super_id",user.getImd_super_id());
session.setAttribute("imd_super_email", user.getImd_super_email());
}

session.setAttribute("depagent",dept_agent);
session.setAttribute("desig",user.getDesignation());
session.setAttribute("eligible",user.getRole());

String filepath = getServletContext().getRealPath("/properties/role.properties");

file = new File(filepath);
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
while (in.available() !=0){
String empId = in.readLine();
String totalempid = empId.substring(empId.indexOf(":")+1,empId.length());
String [] adminempId = totalempid.split(",");
for(String empid : adminempId){
if(empid.equals(user.getEmpId())) {
session.setAttribute("role","Admin");
break;
}
else {
session.setAttribute("role","Not Admin");
}
}
}
session.setAttribute("date",user.getDateOfJoin());
session.setAttribute("user",user.getEmpName());
}catch(Exception e){
System.err.println("-- Exception in setIntoSession() -->> "+e);

}
}
}

From the above servlet, i used the session setAttributed values on the forms.


Regards,<br />K.Elanges
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

There is only a single servlet instance, and all visitors share the same instance. THerefore they share the state set in the following instance fields:



The short answer is never use instance fields in Servlets.
Elanges waran
Greenhorn

Joined: Dec 13, 2007
Posts: 17
Hi David O'Meara,

Thanks for your valuable Suggestion & ideas. I used SingleThreadModel implmentation in the above servlet and handle the variables as local in doPost() then I added <%@page isThreadSafe="false"%> om my jsp pages. The session collision problem was fixed.

Thanks,
K.Elanges
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

SingleThreadModel is deprecated and shouldn't be used.

Even with it, you could have problems with those instance variables.
It's a particularly bad idea to hold a reference to the HttSession in an instance variable.

Move all of those variable declarations into your doPost/doGet methods.


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to avoid Session Collision between Jsp And Servlets
 
Similar Threads
LDAP Syntax - Don't Understand
How to approach Single Sign On(SSO)
Active Directory Authentication using java
How to get list of user groups of active directory?
Change Ldap Password