Problem with Sessions in JSP

Hi,
I am working on a JSP based website, where I am facing problem with sessions. The user is asked to login by providing her id and password. If found correct, a bean is created and populated with all her details and placed in session scope. I plan to use the information stored in the bean on other related pages until she logs out.
<jsp:useBean id="validUser" scope="session" class="UserBean" >
<c:set target="${validUser}" property="userId" value="${fn:trim(dbValues.UserId)}" />
<c:set target="${validUser}" property="userName" value="${fn:trim(dbValues.UserName)}" />
</jsp:useBean>
<c:redirect url="userHome.jsp" /> The user is presented her homepage - 'userHome.jsp', where she can find various links, like 'Update Profile', 'Pay Registration Fees', 'Book Room' etc. The information stored in the bean is available on 'userHome.jsp'page.
<A HREF='userHome.jsp'>Home</A>
<A HREF='editPersonal.jsp'>Update Profile</A>
<A HREF='registrationFee.jsp'>Pay Registration Fees</A>
<A HREF='bookRoom.jsp'>Book Room</A>
<A HREF='logout.jsp'>Logout</A> The problems are:
1. Whenever user clicks on any of the above mentioned links and moves to any page, the bean comes out as null.
<%-- Verify that the user is logged in --%>
<c:if test="${validUser == null}">
<jsp:forward page="loginForm.jsp">
<jsp:param name="origURL" value="${pageContext.request.requestURL}" />
<jsp:param name="errorMsg" value="You must be logged in to access this site." />
</jsp:forward>
</c:if> 2. The URL shows an additional jsessionid, which my client doesn't want to see.
3. On every click on any link, the value of this jsessionid changes.
What I presume, when I am clicking on different links, my session changes, and so I am seeing a different jsessionid. And since session is changing, therefore the bean is not available in a different session.
All this works fine with localhost, problem comes into picture, when I upload my pages to the server.
Puzzled, can anyone help, where am I going wrong? Let me add here, I am new to JSP and hence don't have much resources with me.

There are several ways sessions can be exchanged between the browser and the server in a j2ee web application.
1. The default is through cookies. However when the client does not accept cookies, the server appends the session id to the url.
2. Some servers also facilitate session information exchange using session id in the url even if the client does accept cookies. This is usually ahieved through a setting in some server configuration file.
You will have to find out why the server in your application is appending the session id to the url.
Whatever be the case, the server should be able to look up the session from the incoming request (be it from the session id in the url or a session cookie).
When session information is exchanged through the JSESSIONID in the url, you should ensure that each and every url that goes to the server has this input parameter. To do that all links and form post urls in your servlet/jsp should be treated with a call to encodeURL().
For example, in a jsp
   <a href = "<%=response.encodeURL("/nextJsp.jsp")%>">Click here </a>
or
   <form action = "<%=response.encodeURL("/nextJsp.jsp")%>">
   </form>etc.
ram.

Similar Messages

  • Problem with sessions in Kate Editor

    Hey guys!
    I'm using Kate Editor to code and i'm having problems with sessions. If kate is open and I logout KDE, when I come back to KDE all my customizations in Kate's session (activated plugins, font size, etc) are lost.
    If I manually close Kate before logout from KDE, all the customizations are kept when a manually start Kate. I tried a lot of workarounds, but none worked.
    Is this a bug? Someone else with this issue?
    Thanks in advance!

    The Warning errors are simply because you don't have the tablespaces, users, and roles defined in your application system under the DB Admin tab. Unless it is important to you to capture the physical implementation of your tables exactly as well as the table definitions, you can safely ignore these. If the physical implementation IS important to you, then you need to create these tablespaces, roles and users under the database that you created under the DB Admin tab before you start the capture.
    The Error is because in the set of objects you are capturing there is a foreign key that references the table named "PLEASANT". This table must be among the objects that you are capturing, or must already be in a Table Definition in your application system in the repository.

  • Problem with JavaBeans in JSP.IT'S URGENT!!!

    Hi, i have problems with JavaBeans in JSP.
    In a jsp file( locating in ROOT directory of tomcat 4.0.6 :jakarta-tomcat-4.0.6\webapps\root ) i have this code:
    <jsp:useBean id="paramBean" class="licentza.ParamBean" />
    <jsp:setProperty name="paramBean"
    property="nume"
              value='<%= request.getParameter("numeUser") %>' />
    where ParamBean it's a "bean" class locating in jakarta-tomcat-4.0.6\webapps\examples\web-inf\classes\licentza (licentza is the package i'm using).
    And i get this error:
    Generated servlet error:
    D:\jakarta-tomcat-4.0.6\work\Standalone\localhost\_\dora\intrare2$jsp.java:67: Class licentza.ParamBean not found.
    ParamBean paramBean = null;
    What is the problem?Thank you.

    Hi,
    Put the class file or the package under :jakarta-tomcat-4.0.6\webapps\root\WEB-INF\classes.
    Rajesh

  • I have a problem with session manager session files because of the invalid json storage data submited by firefox

    Hi, i have problem with session manager's session files. The problem is: the submitted storage data from firefox which is put between "storage":{ and its matching closing brace } But in some of my session files there is non equal { and } under storage's braces. I need to get storage data but in my case it is very hard to do. My question is there any char put before or after { and } like /{ or \{ to avoid confusion? If there is not such thing, i think there could be different solution but i am not sure: i look couple of my session files; after "storage":{...} there is ,_"formDataSaved" so i can get storage data in this example ... by looking between "storage":{ and ,"_formDataSaved" easily. Is there every time ,"_formDataSaved" after "storage":{ ?  Thank you.

    Well, it seems waiting is not my strong suit..! I renamed a javascript file called recovery to sessionstore. This file was in the folder sessionstore-backups I had copied from mozilla 3 days ago, when my tabs were still in place. I replaced the sessionstore in mozilla's default folder with the renamed file and then started mozilla. And the tabs reappeared as they were 3 days ago!
    So there goes the tab problem. But again when I started mozilla the window saying "a script has stopped responding" appeared, this time the script being: chrome//browser/contenttabbrowser.xml2542
    If someone knows how to fix this and make firefox launch normally, please reply! Thank you

  • Servlets - problem with session

    Hi there ppl,
    I have a login servlet which is called form a link in a static html page. The doGet() method is as below:
    public void doGet(HttpServletRequest request,
              HttpServletResponse response)
         throws ServletException, java.io.IOException
         HttpSession session = public void doGet(HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws ServletException, java.io.IOException
              HttpSession session = request.getSession(false);
              RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
              response.setContentType("text/html");
              //PrintWriter out = response.getWriter();
              if(session != null){
                   //display members page(with users name as a welcome)
                   System.out.println("in login servletb");
              else{
                   System.out.println("in login servlet");
                   request.setAttribute("membersName", "adom");
                   rd.forward(request, response);
                   //out.close();
         RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
         if(session != null){
         //display members page(with users name as a welcome)
         System.out.println("session exists");
         else{
         System.out.println("session not exisit");
         request.setAttribute("membersName", "adom");
         rd.forward(request, response);
    Problem is when i click on the link in the html page it goes into tthe else statement and displays the login.jsp page fine. But when i click bak on the browser and then click the link agian it goes into the if statemtn..as if a session exists. But why does a session exisit???...if i use request.getSession(false) this shouldnt create a session if one doent already exists so where is this mysterious session being created??
    any ideas would be greatly appreaciated
    Mycall

    yer i do need the session because in my doPost() method of the servlet i create a session once the user logs on with there login/pass. The doGet() method is only to direct the person to the login page. But i want to check for the session in the doGet() incase they have already login in...if so direct them to the main page rather than to the login page agian.
    I stuffed up the code in my previous post...everything compiles and works fine apart from the fact that a session is created when it shouldnt be. I did a test println with session.getCreationTime() and it was created the same time the servlet was initial called. However im not sure if it was created by my servlet or if the broswer somehow had something to do with it....hmm is a worry.
    Heres the code again...hopefully a bit neater for u :D
    public void doGet(HttpServletRequest request, HttpServletResponse reponse)throws ServletException, java.io.IOException{
    HttpSession session = request.getSession(false);
    RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
    if(session != null){
    //display members page(with users name as a welcome)
    System.out.println("session exists");
    else{
    System.out.println("no session");
    request.setAttribute("membersName", "adom");
    rd.forward(request, response);
    thanks agian :)

  • Problem with Sessions in Servlets

    Hi,
    I'm having a problem with sesions with servlets. It seems that if someone logs into my website, which is running on all servlets, while another person is logged on, the second person gets the session of the first person.
    I'm using
    HttpSession session = request.getSession(true);to get the session in each page. The session contains a user object which shows if the user is logged in and what permissions.
    The session should be unique to the client computer right? Or am I jsut screwing this up big time?

    Yes, each client will have their own session. However, you may be testing incorrectly:
    In Firefox, for example, all instances of the application running on the same machine will share the same cookies, therefore the same session, and would be considered one client.
    MS IE will do the same if you use File - New to open a new wondow rather than clicking on the desktop icon.
    If the different clients are using different machines and still getting shared data, then you may be using class-level variables in the servlet, which would not be thread safe and could lead to your problems...
    public class MyServlet extends HttpServlet {
      String data;  //bad
      int moredata; //bad
      public void doGet(...) ... { ... }
    }

  • Problem with Sessions, Servlets, Netscape and Solaris

    We are experiencing a problem that is confounding and frustrating us (I have
              a felling that it is something exremely minor that we are overlooking).
              Here goes:
              Context:
              The problem only occurs when using a netscape browser against weblogic
              4.51running on our Solaris 7 box (Everything works fine through IE, and
              through both browsers against our development machines which are on NT)
              Problem:
              We have a bunch of JSP pages and servlets that are used togehter throughout
              our site. They both manage session information for the user. What is
              happening is that there is no problem maintaining session information among
              all the JSP pages, but when we hit a servlet that we use to stream graphs
              back to the browser, it gets the session but it has no contents all of a
              sudden. What seems to be even more strange is that the session is not
              tagged as new (by checking isNew()), it is just empty of the contents that
              were placed it by the JSP pages. Again, this is only occurring from
              Netscape browsers against our Solaris server.
              If anyone can provide any help it would be greatly appreciated. I can
              provide more details if need be.
              Jeremy
              

    There is a property in the weblogic.properties file that lets you set
              the cookie name. If this isn't set, the port will be appended as part of
              the name. I've had a similar problem switching between http and https
              and losing sessions.
              Carles
              Jeremy wrote:
              >
              > in the link tothe servlet the URL had a :80 in it. This was because the url
              > was generated by a JSP page so that when it was moved from server to server
              > and port to port the code wouldn't have to be changed. Unfortuneately,
              > Netscape sucks and takes this to mean that x.x.x.x and x.x.x.x:80 are
              > different and won't acknowledge the cookie from the JSP pages (x.x.x.x) to
              > the servlet (x.x.x.x:80). Thanks fpr your help.
              >
              > Jeremy <[email protected]> wrote in message
              > news:[email protected]...
              > > my mistake, it appears to always happen on port 80 regardless of the
              > server
              > > it is on.
              > >
              > > Jeff Martin <[email protected]> wrote in message
              > > news:[email protected]...
              > > > It really sounds like your servlet is making a new session, even though
              > > > isNew() doesn't say so. What you might try to do is use session.getId()
              > > > to print out the session ID from your jsp pages as well as your servlets
              > > > to determine if it really is a new session.
              > > >
              > > > Do your servlets and JSPs both use the same scheme (http or https) or
              > > > cookie.setSecure()? Do your cookies use domains or paths in either
              > > > servlets or jsps (cookies can be restricted to certain subdirectories
              > > > which might be different between jsps and servlets)? Are you testing
              > > > through a proxy or firewall, or does either browser have different proxy
              > > > settings than the others?
              > > >
              > > > Jeff
              > > >
              > > > Jeremy wrote:
              > > > >
              > > > > We are experiencing a problem that is confounding and frustrating us
              > (I
              > > have
              > > > > a felling that it is something exremely minor that we are
              > overlooking).
              > > > > Here goes:
              > > > >
              > > > > Context:
              > > > > The problem only occurs when using a netscape browser against weblogic
              > > > > 4.51running on our Solaris 7 box (Everything works fine through IE,
              > and
              > > > > through both browsers against our development machines which are on
              > NT)
              > > > >
              > > > > Problem:
              > > > > We have a bunch of JSP pages and servlets that are used togehter
              > > throughout
              > > > > our site. They both manage session information for the user. What is
              > > > > happening is that there is no problem maintaining session information
              > > among
              > > > > all the JSP pages, but when we hit a servlet that we use to stream
              > > graphs
              > > > > back to the browser, it gets the session but it has no contents all of
              > a
              > > > > sudden. What seems to be even more strange is that the session is not
              > > > > tagged as new (by checking isNew()), it is just empty of the contents
              > > that
              > > > > were placed it by the JSP pages. Again, this is only occurring from
              > > > > Netscape browsers against our Solaris server.
              > > > >
              > > > > If anyone can provide any help it would be greatly appreciated. I can
              > > > > provide more details if need be.
              > > > >
              > > > > Jeremy
              > >
              > >
              

  • Problem with Javascript in JSP

    Hi Guys,
    I have this problem with my JSP page. I am using a javascript function
    which calls a function within a bean. The problem that I have is that I get an error when trying to call the following function :
    function refDataTypes_onchange()
    Vector empNames = DBQuery.getResult();
    I get a runtime error at the line Vector empNames = DBQuery.getResult;
    Any ideas would be much appreciated.
    Below is the whole code:
    Thanks in advance
    FRank
    <%@ page contentType="text/html;charset=WINDOWS-1252"%>
    <%@ page import="java.util.*, java.lang.*" %>
    <%-- Declare the java bean for the countries to be queried --%>
    <jsp:useBean id="DBQuery" class="DBQuery" scope="page" />
    <%-- Bean property searchCondition is not set to query countries --%>
    <jsp:setProperty name="DBQuery" property="searchCondition" />
    <%
    Vector empNames = DBQuery.getResult();
    %>
    <HTML>
    <BODY BGCOLOR="GREY">
    <SCRIPT LANGUAGE="JavaScript1.1">
    function refDataTypes_onchange()
    Vector empNames = DBQuery.getResult();
    </SCRIPT>
    <FORM NAME = form1>
    Please enter in the following details
    <p>
    Reference Type :::====
    <select name="refDataTypes" onchange="refDataTypes_onchange()">
    <option value ="1"></option>
    <% for(Enumeration enum = empNames.elements();enum.hasMoreElements();)
    String nextEmpName = (String)enum.nextElement();
    %>
    <option value =<%=nextEmpName%>><%=nextEmpName%></option>
    <%
    %>
    </select>
    <BR>
    <BR>
    Emp No
    <INPUT TYPE="text" NAME=txtAge >
    <BR>
    <BR>
    <INPUT TYPE="button" VALUE="Check Details" NAME=butCheckForm >
    </FORM>
    </BODY>
    </HTML>

    Thanks dimadoo
    I need my JSP to do the following :
    When a user selects a option from a select list. There is a textfield which I want to populate based on the option that thas been selected from the list.
    I tried the following :
    <% Vector empNames = DBQuery.getResult(); %>
    and it does not even go into the bean.
    Will this work if I refresh the page?

  • Purchased ColdFusion 10: Having problem with session variables

    My Dept. has just bought CF10 and I'm finally updating my existing web app to CF10 from CF8. My First Problem with CF10 is using session variables.
    When using the lower version of CF (since CF 4 to 8) I have never had any problem setting up session variables and getting or using these variables in other pages after a successful login but with CF 10 it seems setting session variables and using them in other pages are a major problems. I'm not sure where have I done wrong in the codes.
    First I'm setting the session in my Application.cfc This way:
    <cfcomponent displayname="Application" output="true">
      <cfset THIS.Name ="MyNewApp"/>
      <cfset THIS.ApplicationTimeout = CreateTimeSpan(0,0,20,0) />
      <cfset THIS.SessionManagement ="YES"/>
      <cfset THIS.SessionTimeout = CreateTimeSpan( 0, 0, 20, 0 ) />
      <cfset THIS.SetClientCookies = false />
    <cffunction name="OnApplicationStart" access="public" returntype="boolean" output="false">
    <cfset application.Main_DSN = "TESTDB">
    <cfreturn true />
    </cffunction>
    <cffunction name="onApplicationEnd" output="false">
          <cfargument name="applicationScope" required="true">
        </cffunction>
    <cffunction name="OnSessionStart" access="public" returntype="void" output="false" hint="Fires when user session initializes.">
    <cfset session.loggedin = "NO">
    <cfset session.username = "">
    <cfset session.userrights = "">
    <cfset session.usergroup = "">
    </cffunction>
    </cfcomponent>
    After login, user is validated and set values to those session.variables:
    ........user validation codes here......................
    <cfif mylogin NEQ true>
          <cflocation url="/login/login.cfm">
          <cfabort
    <cfelse>
          <cfset session.loggedin="Yes">
          <cfset session.username="#Trim(Form.username)#">
         <CFSET qUserRights = LoginObj.getUserRights('#Trim(Form.username)#')>
         <cfset session.userrights = qUserRights><!--- it's a query --->
        <CFSET qUserGroup = LoginObj.getUserGroup('#Trim(Form.username)#')>
            <cfloop query="qUserGroup">
               <cfset session.usergroup = user_group>
               <cfbreak>
            </cfloop>
        <!--- ****************** ???????????????????????????????????????????????????????????????????????????
        When I do cfdump in at this level, I can see that all of these session variables have been assigned to their values.
        But these session variables are not accessible from other pages. Other pages still show these session variable without its value.
        So, when I use these cfdumps in the index.cfm it is shown as they're not yet assigned with any values   ****************** --->
       <cfdump var="#session.loggedin#">
       <cfdump var="#session.username#">
       <cfdump var="#session.userright#">
       <cfdump var="#session.usergroup#">
    </cfif>
    In index.cfm, Before Login I got:
    session.loggedin = NO
    session.username = ["empty string"]
    session.userrights = ["empty string"]
    session.usergroup = ["empty string"]
    After a successful Login:
    session.loggedin = NO
    session.username = ["empty string"]
    session.userrights = ["empty string"]
    session.usergroup = ["empty string"]
    Have I done something wrong? These codes work on CF8. Please help.
    I need to mentioned:
    CF10 is in Linux and my web app is under https not http. But these session variables should be shared bentween http and https because some older application are still in http.

    On which page is the following code?
    After login, user is validated and set values to those session.variables:
    ........user validation codes here......................
    <cfif mylogin NEQ true>
          <cflocation url="/login/login.cfm">
          <cfabort
    <cfelse>
          <cfset session.loggedin="Yes">
          <cfset session.username="#Trim(Form.username)#">
         <CFSET qUserRights = LoginObj.getUserRights('#Trim(Form.username)#')>
         <cfset session.userrights = qUserRights><!--- it's a query --->
        <CFSET qUserGroup = LoginObj.getUserGroup('#Trim(Form.username)#')>
            <cfloop query="qUserGroup">
               <cfset session.usergroup = user_group>
               <cfbreak>
            </cfloop>
        <!--- ****************** ???????????????????????????????????????????????????????????????????????????
        When I do cfdump in at this level, I can see that all of these session variables have been assigned to their values.
        But these session variables are not accessible from other pages. Other pages still show these session variable without its value.
        So, when I use these cfdumps in the index.cfm it is shown as they're not yet assigned with any values   ****************** --->
       <cfdump var="#session.loggedin#">
       <cfdump var="#session.username#">
       <cfdump var="#session.userright#">
       <cfdump var="#session.usergroup#">
    </cfif>

  • Problem with session while sending a multipart-form (a file via post)

    I have a problem with the communication between my applet and my server. I use a method to post an xml to my server with the Content-Type "application/x-www-form-urlencoded" and with it I'm not having any problem to preserve the session.
    However I use another method I found in the forums to post files and try to adapt it, but I'm being send from the server to the login page because it's not recognizing my session
    Can anybody help me? This is my method
    public String uploadFile(String adr, BufferedImage img) {
            String res = "";
            String CONTENT_BOUNDARY = "--abvx98734732";
            String s;
            File f = null;
            URL url;
            URLConnection conn;
            try {
                url = new URL(adr);
                conn = url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data; boundary=" + CONTENT_BOUNDARY);
                conn.setRequestProperty("file-Name", "process_image.jpg");
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr
                        .write(("--"
                                + CONTENT_BOUNDARY
                                + "\r\n"
                                + "Content-Disposition: form-data; name=\"fileData\"; filename=\""
                                + "process_image.jpg" + "\"\r\nContent-Type: image/jpg\r\n\r\n")
                                .getBytes());
                ImageIO.write(img, "jpg", wr);
                wr.write(("\r\n--" + CONTENT_BOUNDARY + "--\r\n").getBytes());
                wr.flush();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                while ((s = in.readLine()) != null) {
                    res += s;
                in.close();
            catch (MalformedURLException muo) {
                muo.printStackTrace();
            catch (IOException io) {
                io.printStackTrace();
            return res;
        }This is how I preserve session in my other method:
    private static final String SESSION_KEY = "_session_id";
    URLEncoder.encode(SESSION_KEY, "UTF-8") + "=" +
    URLEncoder.encode(sessionId, "UTF-8");
    wr.writeBytes(content);
    ....

    Yes, the only way is to pass the value u want in the query string. But make sure that the value is not too large.
    In case you have too much info i guess the only way is to circumvent multipart and handle the process in your own custom class, which wont be worth the effort if u need pass only 2-3 small parameters.
    Always,
    Leo.
    Hi,
    Before I upload a file, I want to get a few parameter
    values (getParameter) on the form first. I've tried
    using com.oreilly.servlet MultipartRequest and a few
    other free servlets but they require that the file
    must to be uploaded first. For example:
    MultipartRequest multi = new
    MultipartRequest(request,filepath, 10*1024*1024);
    //this will instantiate the object and upload the
    file
    String command = multi.getParameter("command"); //get
    the form parameter
    Is there any way I can get the parameter first before
    uploading the file? I truly appreciate any helps you
    can provide me.
    Regards,
    Lily

  • Problem with Session Beans in JSP

    Hi,
              I'm testing Weblogic for our company's IT department and just ran into a
              strange error. I wrote a simple JSP script to use a bean that works fine
              except when trying to set the bean scope to session. I looked at the the log
              file and the only exception recorded was a ClassCastException. Could anyone
              please clarify this to me? Is this a current bug in Weblogic?
              Thank you for your attention,
              Paul Visan
              

              classcastexception are generally due to bad classpaths...
              can you provide more information like what is the code trying to do..stack trace etc..
              "Paul Visan" <[email protected]> wrote:
              >Hi,
              >
              >I'm testing Weblogic for our company's IT department and just ran into a
              >strange error. I wrote a simple JSP script to use a bean that works fine
              >except when trying to set the bean scope to session. I looked at the the log
              >file and the only exception recorded was a ClassCastException. Could anyone
              >please clarify this to me? Is this a current bug in Weblogic?
              >
              >Thank you for your attention,
              >Paul Visan
              >
              >
              

  • Problem with Sessions and window.open

    Hi,
    Hi everyone,
    Help Please!!!
    I am working with Sevlet session objects and HTML forms and windows. I have an HTML form for the user to supply a username and password. Once the user clicks submit I need to open another browser window that has no toolbar, no location, no status bar, etc. The user should also be able to go back to that login screen and login again and open a 2nd, 3rd, etc. instance of the application. My problem is that each application is being asigned the same sessionId. I believe it is being asigned to the main login window and thus to the other child windows it opens. Is there a way to work around this? Do I need to make the user open another browser window to login? I need to be able to let the user open multiple instances of the application with unique session ids for each.
    Any insight is GREATLY appreciated on this topic. Anything you can tell me about sessions (Java), IE, window.open would help greatly!
    THANK YOU IN ADVANCE!!!
    MA

    To achieve this, you must introduce another level of
    abstraction to the Servlet specifications. When you
    work with JSP/Servlets you use mostly the HttpSession
    to handle user related tasks, and the aplication
    context, for things that are common to all users. But
    inside the HttpSession scope, you want to create
    containers that have 'smaller' scope and are uniquely
    identified.
    A ipothetical scenario :Let's say that you must have
    multiple connections to several databases, on each
    database user rights beeing diferrent, and you must be
    able to track user actions globaly, and eventualy
    capture a 'Close Application event' and close all db.
    connections.
    1. when the user first accesses the login frame create
    the HttpSession. In the HttpSession object, store a
    Hastable (let's call it 'ConnectionTable'). Each
    object in the Hashtable must identify uniqely a
    database connection. Now, to create unique identifiers
    ids, make the keys in the hashtable java.lang.Long
    objects, created using System.getCurrentTimeMillis().
    This guaranties there will be no possible confusion.
    From each new open window, on each request to the
    server, along with the usefull parameters, send the
    connection identifier. When proccessing the request,
    select the object from the Hastable wich corresponds
    to the ID.
    2. Now, the values in the ConnectionTable, must act as
    the containers that I mentioned in the first
    paragraph. The simplest way to do this is to have
    again a Hashtable derived class to do the job, wich
    exploses methods similar to HttpSession: setAttibute (
    Object key, Object value) and getAttibute ( Object
    key, Object value). This container may use internally
    a Hashtable to store object, and explose only the
    getAttribute and setAttribute methods for clarity. Any
    way, this is a problem of implementation. Let's call
    this class CustomSession.
    Now, a textual activity diagram:
    1 user accesses the main page, you start a new
    HttpSession; In the HttpSession object, store the
    ConnectionTable object.
    2. the user enters the userID and pwd and adatabase
    name, and a new window is opened. Let's supose the
    data entered is valid.
    3. when you process the login data, you create a new
    CustomSession object. you put in it whatever you would
    put in your HttpSession. You generate a unique
    identifier using System.CurrentTimeMillis(). Put the
    CustomSession object in the ConnectionTable, using the
    generated id as key. Send the response.
    ..... later on .....
    100. the user asks for a particular action to be
    performed - e.g. a row deletion. The page contains a
    form with text field where the user introduces the
    row number, a submit button and a hidden input with
    the ID.
    101. you process the data. Get the ID from the request
    object, get the ConnectionTable from the session, get
    the CustomSession using the ID as key, do whatever
    your logic was doing, but obtaining the objects from
    the CustomSession instead of HttpSession
    NicNic,
    Very slick idea. I think that it could work and it seems that there would be not security issues because the id that you would store on the client side is the Unique Identifier and not the actual Session Id. Do you forsee any security issues for this implementation?

  • Problem with onload in jsp page

    Hi all,
    I had two jsp pages, a search and a results page. I need to enter some search criteria in the first page and based on that criteria i will be getting the results in the results jsp. Now, when i click the back button in the results page, i need to go to the search page and the values which i entered in the search page needs to be present there. But the problem is i had a javascript function which runs on loading of the search page. This function will set all the values in this search page to empty whenever we go to the search page. I am calling this javascript function as follows in my search jsp page.
    <body onload="setdefaultvalues('<%=name%>');">
    I am having the code for the back button in the results page as follows.
    <INPUT TYPE="button" VALUE='Back' onClick="javascript:history.go(-1);resetvalue(name);" class="button">
    The problem i am facing is whenever i go to the search page by clicking on the back button, the values in the search page are getting empty because of the onload method. There is no way that i can remove this onload method as i require it for setting the values in the search page evrytime i get to that from other modules as it is the main page for my module. So, is there anyway that i can stop this function from executing when i come from the results page or is there any other way that i can store the values in the search page when going from the results page.

    i think you really should have the result page include your search page contents rather than having the user need to click back as you'll end up with all sorts of nightmares in caching & session object management to be honest. if the search page is complex use javascript to hide contents and let the users expand them when they want to re-search.
    however, if you feel you must i would suggest the following:
    in your result page:
    session.setAttribute("userQuery","true"); (you probably actually want to put a container object with the query information in here)
    in your search page you could have something like:
    <body <% session.getAttribute("userQuery")==null { %>onload="setdefaultvalues('<%=name%>');"<% } %>>
    -or-
    <body onload="setdefaultvalues('<%=name%>',<%=session.getAttribute("userQuery")==null?"true":"false"%>);">
    function setdefaultvalues(name,run) { if ( !run ) return;....}
    you'll have to decide when to remove the object though cause once its set its there until the session expires or you remove it.
    hope that helps, good luck!

  • Problem with session variable

    Hi,
    After I insert a record into my MS Access database, it seems
    to me that the session variable got destroyed so the next page
    display the session variable as undefined. Has anyone have similar
    problem? If so, how to work around that?
    Thanks.
    Tommy,

    neptunes wrote:
    but its leading to jsp page error...For starters: never, never, ignore errors (exceptions and stacktraces). Those contain very, very, worthful information about the cause of the problem and what exactly went wrong. This way you can easily trackback the problem and solve it.
    If you're unable to think logically and smart so that you can interpret the error yourself, if necessary with help of Google, then post it here. Then we'll tell you about the actual problem and possible soltions.
    At any way:
    iam displaying some data in a table using resultset object,now at the same time iam using to session variable to use the resultset object in my other applications...This already doesn't sound very good. You should never pass expensive resources around like that. You should acquire and close the Connection, (Prepared)Statement and ResultSet in the shortest possible scope. Preferably already in the same method as where you query the data.

  • Problem with session.removeAttribute()

    Hi,
    After doing
    <% session.removeAttribute("USER");%>from one jsp, if i say
    <% =session.getAttribute("USER") %>in another jsp, I still get the value of the session variable USER.
    Can anybody tell what might be the problem ???
    Thanks !

    No it shouldn't and it doesn't just apply to those objects.
    Quoting the api:
    The remove attribute method:
    public void removeAttribute(java.lang.String name)
    Removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing.
    After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueUnbound. The container then notifies any HttpSessionAttributeListeners in the web application.removeAttribute removes the attribute from session.
    If you can still see it in another jsp, you must be putting it back INTO the session somewhere.
    Cheers,
    evnafets

Maybe you are looking for