Retrieving session data in JSP  which is forwarded from a servlet

I'm trying to retrieve session data which is set in a servlet and pass to a jsp. But its returning NULL . The session IDs are equal.
Scenario:
JSP display the checkbox, user selects it and submits to a servlet. the servlet display the selected items and stores the data in session.
when the user press back button in servlet all i want to do is display those checked box which were selected before as checked in the JSP so that user can edit.
Following is a small test code
JSP
<html>
     <head>
          <title>Item List</title>
     </head>
     <body bgcolor="#fedeab"><br><br><br>
     <p align=center>
          <font size=4>
          Choose the item you want!!!
     </p>
     <form action="/demo/showitem" method="post">
          <%=session.getId()%>
          <div align=center>
          <fieldset style="width:250px">
          <legend style="text-align:center">List of item</legend> <br>
          <%     
               if (session.getAttribute("book1")!=null) {
          %>
               <input type="checkbox" name="book1" value="book1" checked > Book 1 <br>
          <% } else {%>
               <input type="checkbox" name="book1" value="book1" > Book 1 <br>
          <% }%>
          <input type="submit" value="Enter">
          </fieldset>
          </div>
     </form>
     </body>
</html>               
Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowItem extends HttpServlet
     public void doPost (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException
          HttpSession session = req.getSession(true);
          res.setContentType("text/html");
          PrintWriter out = res.getWriter();
          out.println(session.getId());
          out.println("<br>");
          out.println("<form>");
          String book1 = req.getParameter("book1");
          session.setAttribute("book1",book1);
          if (book1 != null)
               out.println ("1." + book1 +"<br>");
               out.println("<br><br><input type=\"submit\" name=\"buy\" value=\"Buy\">");
          else
               out.println("No item to display<br>");
          out.println("&nbsp&nbsp<input type=\"submit\" name=\"back\" value=\"Back\">");
          out.println("</form>");
          RequestDispatcher page = getServletContext().getRequestDispatcher("/jsp/litemlist.jsp");
          if ((req.getParameter("buy"))!= null)
                    page.forward(req, res);
          if ((req.getParameter("back"))!= null)
                    page.forward(req, res);
     public void doGet (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException
          doPost(req,res);
}

req.getParameter("book1") is not NULL and returning the value of the checkbox "book1". The problem occurs when the back button is press and try to retrieve the session value in the JSP. At that time, session.getAttribute("book1") returns NULL.
But if i convert the servlet to JSP then everything is working fine.
So i wanted to know if there is anything wrong in the way i store the session value in the servlet and forwarding to the JSP.
Thanks

Similar Messages

  • Forms applet does not load when request forwarded from custom servlet

    I have an existing forms app that I wish to call from a newly-developed servlet. The servlet determines which form to call and then forwards the request to the forms servlet using RequestDispatcher.forward().
    The request is forwarded correctly but when it is done all I see is a blank browser (IE7) window. When I View Source I see all the correct HTML code (from basejpi.htm) but it seems my browser does not attempt to load the forms applet. No messages are displayed in the Java Console. This is the same HTML that comes back if I run the forms app directly, e.g. click a link that goes straight to the forms servlet URL, only in that case the forms app starts up fine.
    Anyone know why this does not work?

    Figured out what is going on:
    In basejpi.htm there is "<SCRIPT LANGUAGE=JavaScript SRC=java/forms_ie.js>" that creates an OBJECT tag to load the forms applet. I believe since the context of my custom servlet is different than that of the forms servlet, forms_ie.js is not found when the request is forwarded from my servlet.
    One question answered raises another. There is also an OBJECT tag inside a NOSCRIPT tag for machines where scripting has been disabled:
    <!-- Forms applet definition (start) -->
    <NOSCRIPT>
    <OBJECT name=FormsApplet
    type="application/x-java-applet"
    ...>
    </NOSCRIPT>
    <SCRIPT LANGUAGE="JavaScript" SRC="java/forms_ie.js"></SCRIPT>
    My thinking is to remove the NOSCRIPT tag, and also the SCRIPT tag mentioned above, so all machines will simply see the OBJECT tag, like so:
    <!-- Forms applet definition (start) -->
    <OBJECT name=FormsApplet
    type="application/x-java-applet"
    ...>
    This makes me wonder why the SCRIPT option is there to begin with. Anyone see a downside to this approach?
    Kevin

  • Retrieving session data for user (HOW ?)

    I have written an ecommerce site which uses HttpSession objects for storing data (ie users shopping cart). The touble I have is that when the user clicks pay, there request goes to a different server and if valid that server does a callback to my server.
    PROBLEM - When I receive the request for the call back I have lost the session data. I am able to pass hidden form params in the callback request, so I can send the session id.
    QUESTION - AM I able to retrieve a session with the stored ID. I did try appending jsessionid=<sessionID> into the call back URL but it still created a new session.
    Thanks
    Justin

    How about this
    1) Implement HttpSessionListener interface and hold your own list of sessions in Hashtable
    2) Send session id to request and get it back with from callback
    3) Search in your Hashtable your lost session.
    4) Enjoy
    Pavel
    P.S. The way you're trying is hacky... I mean session id sometimes handled in parameters (as you have tried to hack) or in cookies.

  • How the hell does a person share session data between JSP page and a Servle

    1. How the hell does one share session data between a servlet and a JSP page without using a bean but rather using a normal string variable.
    2. When using session scope to access a bean the application complains about not finding the bean on the specified scope, however when I use an application scope the save the same bean, the application does find it.
    Please help!!!!!!!
    SERVLET:
    HttpSession session = request.getSession(true);
    ServletContext servletContext = session.getServletContext();
    customerID = result.getString("CustomerID");
    userName = result.getString("UserName");
    session.setAttribute("UserName",userName);
    session.setAttribute("CustomerID",customerID);
    System.out.println("Customer UserName = " + session.getAttribute("UserName"));
    response.sendRedirect("/economics/subscriptions/default.jsp");
    JSP PAGE:
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root xmlns:jsp=http://java.sun.com/JSP/Page mlns:c="http://java.sun.com/jsp/jstl/core" xmlns:sql="http://java.sun.com/jsp/jstl/sql" version="2.0">
    <jsp:directive.page isThreadSafe="true" session="true" contentType="text/xml"/><jsp:output omit-xml-declaration="false"/><jsp:scriptlet>response.addHeader("x-xslt-nocache", "true");</jsp:scriptlet><pml>
    <page type="web" search="y">
         <pageName>Commercial Banking</pageName>
         <jsp:directive.include file="/economics/header.inc"/>
         <jsp:directive.include file="/login.inc"/>
         <jsp:directive.include file="/economics/leftMenu.inc"/>
         <!--<jsp:useBean id="UserName" type="java.lang.String" scope="session" />-->
         <content>
         <searchSum>Commercial - Main Content</searchSum>
         Value = <c:out value="${request.session.getAttribute("UserName")}"/>
         </content>
         <jsp:directive.include file="/economics/rightNav.inc"/>
         <jsp:directive.include file="/footer.inc"/>
    </page></pml></jsp:root>

    For a start, just "session" instead of "request.session" would work better. But why did you post this here and not in the JSP forum? Doesn't seem to have anything to do with Java programming.

  • Lost session data on jsps

    I run a jsp on Tomcat. But the Tomcat says that the session is lost and returns a null pointer. There is no session clear statement in my jsp except its pointing out a null session data.
    It works well when I go to a jsp that comes from a servlet processing. But when I click on link that directly calls on a jsp page, the page doesn't finish loading/errs out.
    What to do with this? This works fine in single-serevr instance. But when it's run on a cluster/shared environment, it doesn't.
    Message was edited by:
    rachehernandez

    I'm new to tomcat itself and to this job :) I'm using tomcat 5.0.28.
    I'm not sure how they do clustering in their setup though.
    It's working fine by in a test standalone mode. I do think there's something wrong with the setup. But how would I know?
    The jsp sometimes work , and most of the times not. It works when you try to refresh the page. It also works when it comes from a servlet call. But when its just an href link, it doesn't. JSP is using an object from the session. It throws an exception when it can't find this object in the session. But when I click on a link that calls a servlet to load a jsp that's using the same session object, how come it can load up.
    What's happening with the session?
    Thanks!

  • How to retrieve sessions variables in JSP

    hi,
    I am trying to retrieve session variable from servlet to JSP.
    In the servlet i am retrieving employeenames from database and storing them in a ArrayList variable then i am setting this variable into the session.
    When retrieving the session in the jsp it displays as [empname1, empname2].
    Please help how to retrieve them
    Thanks in Advance,
    sha

    At the servlet:
    ArrayList<String> employeeNames = new ArrayList<String>();
    employeenames.add(blahBlahblah);
    session.setAttribute("eNames", employeeNames);
    At the JSP:
    ArrayList<String> names = (ArrayList<String>) session.getAttribute("eNames");
    for (String nom : names) {
    do something with the name stored in String variable nom...
    }

  • Challenge forwarding from a servlet to a JSP

    Redirecting information from a servlet to a JSP
    Hello Everyone,
         I am processing the contents of a html form using a servlet. After processing the
    information received and storing it into a javabean I am trying to pass control onto a jsp for
    display. At this stage the jsp does not display as desired due to a URL challenge. The URL
    which references my jsp is:
    http://localhot/ferngully/prefset.jspThis url has been designated to the jsp page 'prefset.jsp' by the application specific web.xml
    file (...I am using Tomcat 5!), the relevant contents of which follow:
    <servlet>
         <servlet-name>PreferenceSet</servlet-name>
         <jsp-file>/prefset.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
         <servlet-name>PreferenceSet</servlet-name>
         <url-pattern>/ferngully/prefset.jsp</url-pattern>
    </servlet-mapping>If I access the page with the afore mentioned URL it displays correctly. However the URL which
    is returned to the browser after the servlet has forwarded control to the JSP is:
    http://localhost/ferngully/ferngully/PreferencesThe following form markup is used to access the servlet:
    <form name="form1" method="post" action="ferngully/Preferences"> I know that I have mapped the servlet correctly because the servlet performs it's programatic tasks happily :)
    I am using code within the servlet to forward control to the JSP, and I believe that this is the crux of my challenge.
    The code for the servlet is listed below.
    package userpreferences;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class PreferencesServlet extends HttpServlet
         public void init(ServletConfig config) throws ServletException
              super.init(config);
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              doPost(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              String url = "/prefset.jsp";
              ServletContext servCont = getServletContext();
              RequestDispatcher reqDispatch = servCont.getRequestDispatcher(url);
              reqDispatch.forward(request, response);
    }I believe that the above highlighted code section is responsible for my challenge. I have tried changing the String url to "/ferngully/prefset.jsp",
    however there was no improvement in functionality.
    Can somebody please explain to me how I can go about directing the control of this process from the servlet to the jsp correctly? Particularly
    how I can go about making the url returned to the client correct for accessing the jsp page? Do I need to delete the mapping entry for the
    jsp page in web.xml? I am new to servlets & jsp so any help will be much appreciated.
    Thanks
    Kind Regards
    Davo

    3. >The following form markup is used to access the servlet:
    <form name="form1" method="post" action="ferngully/Preferences">Question 1:
         why do you specify your contextname in action attribute again ?
         General funda about urls:
         When you have an index.html loaded through http://localhost/index.html, then a link in that html whose url is,
         1. say, preferences.html (no forward slashes preffixed or suffixed) would load the html from the same folder.
         2. say, /ferngully/prefences.html, would attempt to load a html from the ferngully folder that is a sub-directory
    of your web-application
         3. say, /ferngully/prefences.jsp, would attempt to load a html from the ferngully folder that is a sub-directory
    of your web-application
         When you have a servlet whose url-pattern is set to intercept requests, it would intercept requests that have that
    pattern it is defined to intercept in web.xml (for example all the above requests in 1,2 and 3 would be intercepted
    by a servlet whose pattern is ferngully/*)
         Now if your action is not a specific resource (.jsp or .html), something like /preferences, this would map to a url
    /ferngully/preferences. (for which a resource should be defined in web.xml - either a servlet or a jsp)
    However the URL which is returned to the browser after the servlet has forwarded control to the JSP is:
    http://localhost/ferngully/ferngully/PreferencesTell us the url of the original html
    I know that I have mapped the servlet correctly because the servlet performs it's programatic tasks happily :)Tell us the url-appetrn of the servlet that intercepted your request
    Particularly
    how I can go about making the url returned to the client correct for accessing the jsp page?The url in the browser is always the request url, you cannot change it to the url of the jsp even which rendered the page
    through a fwd from the servlet.
    Do I need to delete the mapping entry for the
    jsp page in web.xml?Not necessary. You can access the jsp directly from the servlet while forwarding by
    1. specifying the exact path to the jsp. For example if the jsp is under a folder called jsps, your request dispatcher
    url ought to be /jsps/prefset.jsp
    2. specifying the jsp's url-pattern as specified in web.xml
    Questions Contd
    2. Why does the url pattern have to have a .jsp suffixed.
    From your code
    <url-pattern>/ferngully/prefset.jsp</url-pattern>It could equally well have been
    <url-pattern>/ferngully/prefset</url-pattern>And then your servlet would have to forward it to ("/ferngully/prefset")
    2. Your jsp-file mapping is in this form
    <jsp-file>/prefset.jsp</jsp-file>This assumes that the jsp is in the top-level folder of your web-application and not under
    any sub-directories. Correct ?
    cheers,
    ram.

  • How to forward from a servlet to a (secured) jsp

    hi all
    actually i am trying to forward a request from a servlet to a jsp which is located in the WEB-INF-directory of the web-app...
    as i read in the docs the path in the getRequestDispatcher-method must start with a "/" so i tried to get a requestDispatcher-object from this path:
    /WEB-INF/secureJSP/abc.jsp...
    but all i get is a FileNotFoundException: no ressource "..." in the servlet context root "..."
    if i put the jsp in the web-app-root (like /abc.jsp) i am able to get a requestDispatcher-object without troubles...
    whats wrong? any ideas?
    tia
    sandro

    Hi
    Let me clarify this for you, Firstly as I said the WEB-INF directory is not accessible to the browser i.e a user couldn't possibly type in http://server-name:port-number/myapp/WEB-INF/test.jsp - This wouldn't work. But what you can do is forward a request to the jsp through a servlet using the RequestDispatcher.
    The RequestDispatcher object can be obtained in two ways. One is from the servletContext and the other is from the request. If it is obtained from the servletContext then the path is interpreted relative to the root of the web application. If it is got from the request without the "/" then the path is interpreted relative to the current request servicing resource.
    In your case get the RequestDispatcher from the ServletContext and provide the path as you have provided - assuming that WEB-INF directory is just below your myapp directory.
    Keep me posted on your progress & sorry for the confusion.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems inc
    http://www.sun.com/developers/support

  • Passing session data between jsp and servlet

    I have a servlet that I pass data to my jsp.
    I do a session.setAtrribute in the servlet. No problem.
    I get the data no problem in the jsp that I call.
    How do I pass this same data to the another servlet?
    I basically have an array of values that I already have in the existing jsp that has been set in session.
    When I call the secondary servlet, I don't have anything in this session variable related to my array.
    Prior to posting to my next servlet, do I need to do another setAttribute inside the jsp to get the data passed to the servlet?
    Thanks.

    Two different things. The encoding adds this to the URL (after the page, before the query string
    ;jsessionid=ABC123 but only if the user isn't using cookies.
    So in your example, you would do this (maybe):
    <%
      String url = response.encodeURL("Servlet");
    %>
      <form name="form1" method="post" action="<%= url %>?cmd=pay"> ... Or some modification.
    So the difference between encodeing and using a post is that
    1) encoding adds the jsessionid to the url string if necessary. It does nothing else
    2) POSTing will send a request to the provided URL via the POST method, including the inputs of the form as parameters to the URL.
    They really don't interact with each other. It is like asking what is the difference between the Color Orange and thr Size Big? They can both be applied to the same thing, or not... and have no real relation to each other.

  • Sending and retrieving blob data using JSP

    I need to upload images to a database through a web page (jsp)
    and then display them.
    Environment is tomcat + mysql.
    Anyone know a good site that explains
    how to work with blobs through JSP?
    thanks for any help!

    hello Sir,
    I have to make a Image Library.
    What I have done is I am just stroing the Image Path into the path
    and retrieving the path from the database.
    But now I am asked to Store the Image in the Database..
    Could U Please tell me at the time of retrieving the Image
    what exactly I have to do..
    I am just 1 month new to JSP...(Practically)
    Could U please write me the Code for Converting the BINARY Data into
    InputStream ...
    or what exactlt I have to do..
    Please Guide me man..
    Thanks In Advance...
    With Regards
    Eklavya

  • Please make it possible to print e-mail which are forwarded from gmail (google - apps domain).

    With my HP LaserJet Pro P1102w setup to use e-print which works very good.
    Now I want to automatic print the e-mails when received on my (order) google apps email address.
    So I setup a forwarding rule in Google Apps - gmail to the printers e-print email address.
    No I got a error in ePrint Center, to many recipients.
    Can you please make it possible to allow more recipients with a settings or that it is possible to forward-and-print from a gmail e-mail?
    Than you have a very good e-print service!
    Thanks,

    Ok, I made a fresh provider hosted application to test out Dragan's suggested solution.
    You can view the repository here:
    https://github.com/mattmazzola/providerhosted_01
    After comparing this new application and the old one, I realized I had a misunderstanding of how the SP.RequestExecutor expected urls to be constructed. I thought it was required to use the SP.AppContextSite() endpoint.
    I was incorrectly constructing a request to the appWeb with a url similar to the following:
    https://contoso-6f921c6addc19f.sharepoint.com/ProviderHostedApp/_api/SP.AppContextSite(@target)/contextinfo?@target=%27https%3A%2F%2Fcontoso-6f921c6addc19f.sharepoint.com%2FProviderHostedApp%27
    As you can see, the @target was set to the appWeb url but infact when making request to the appWeb using RequestExecutor you do no need to do this.  It is simply appweburl + "/_api/contextinfo".  It is only when making requests for
    resources existing on the hostWeb that you need use the AppContextSite and set the @target.
    I think the link to the solution I provided is more helpful, but I marked Dragan's reply as the answer to give him credit for helping me.

  • How to display data in canvas which is fetched from servlet to midlet.

    I am able to display data from database using servlet.
    I am using MySQL as database.
    But i want to display it more nicely using canvas. Right now i just print all the data's , it doent look professional.
    I want to know how to show those data's nicely. How to use canvas? where i can use canvas? Is there any other way to display data/records so that it looks more professional.
    Need help as soon as possible.
    Thanks in advance.

    hey listen i created midlet and servlet. I can see the record which is on my database but as i have just printed using servlet on the mobile screen. Now i want to display those records nore nicely that is . say for example
    i am showing personal profile of a user.
    I am just displaying like ---"Name:" Abc,
    Age: 27 etc
    now i wnat to bold "Name" , "Age" stuff like that.
    I want to use color etc but i dont know how to do that. How can i my records look good?
    I have stored all the record in resultset and have passed it to midlet not i want display it more nicely. How to do that?

  • Unable to create/cleanup persistent session data cache

    Hi all
    After the iPlanet Webserver 4.1 SP12 starts up the following entries appears in the error log file:
    [14/Oct/2003:09:24:48] info ( 5999): successful server startup
    [14/Oct/2003:09:24:48] info ( 5999): iPlanet-WebServer-Enterprise/4.1SP12 BB1-12/18/2002 14:18
    14/Oct/2003:09:24:49] catastrophe ( 5999): Unable to create/cleanup persistent session data cache
    What does the last entry mean?
    Thanks for any help :-}
    Best regards,
    Jean-Claude

    Check permissions, disk space of following dirs:
    server_root/https-instance/ClassCache/
    server_root/https-instance/SessionData/
    Try to:
    Clear Session Data
    Delete JSP Class Cache Files
    using the Session Data link under Admin Server GUI Java tab
    Hope it helps!

  • The device is not with me. remove device from icloud account will enable new user to retrieve my data

    The IOS device is not with me. By removing device from icloud account will enable new IOS device user to retrieve my data?

    If you remove it from your account all of the data that is in the account will be removed from the iPad.

  • Passing parameter to a jsp from a servlet

    Hi,
    I need to pass a parameter from a servlet to a jsp without using the session object. Is it possible? I've been looking for a method like response.setParameter but it doesn't exist.
    Please help !!!

    Actually, there is no setParameter method in the ServletRequetsObject. Still, you can create one. This can be usefull when you have a jsp that get its parameters from either a direct html form posting or a forward from a servlet. This can be achieved using wrappers, instead of the real request object.
    It's not really tricky, it's only a little "underknown" feature.
    Here is a sample code when you can fake the settings of requets parameters :
    public class MyRequest extends HttpServletRequestWrapper {
       private HashMap fakedParameters;
       public MyRequest(HttpServletRequest nested) {
          super(this);
          fakedParameters=new HashMap();
        public void setParameter(String key,String value) {
            fakedParameters.put(key,value);
        public String getParameter(String name) {
           String res=fakedParameter.get(name):
           if (res==null)
               res=super.getParameter(name);
           return res;
    }NB: this is a sample, you may also override other method (such as getParameterNames) for a full featuerd wrapped request.
    Now, you can use your wrapped request :
    MyRequest req2=new MyRequest(request);
    RequestDispatcher dispatcher=request.getRequestDispatcher("/somePage.jsp");
    req2.setParameter("name","yourName");
    dispatcher.formard(req2,response);Hope it helps.

Maybe you are looking for

  • I can't read my eBooks I purchase from iTunes on my desktop or laptop.  Do I need to go Amazon?  Kindle?

    Is there a future upgrade or availability to read eBooks purchased from iTunes on my desktop or laptop Mac? If not, I am just going to get the free Kindle application and buy all of my ebooks from Amazon as I can read them on any Mac. I purchased a b

  • Error getting an iBook to iTunes

    Need your help.. I created my first iBook using iBook Author tool, and this is picture book with lot of pictures and stories etc. About 250 MB size.. It worked just great on my iPad after exporting as an iBooks format and now trying to get this to iT

  • [Partially Solved] Error with bsdtar and symbolic links

    I'm trying to install a package (asymptote) from AUR but am running into an odd error.  During the extract phase I get errors like asymptote-1.70/base/asy-keywords.el: Can't update time for asymptote-1.70/base/asy-keywords.el: Function not implemente

  • How to install custom dictionaries for openoffice?

    Hello. I'm a user from Croatia, and I do a lot of writing in my mother's tongue. A Croatian spellchecker would be a nice addon for my OpenOffice installation, but there is none on the repository. Is it possible to install it manually into my OpenOffi

  • Lightroom 4 is not identifying duplicates

    I know there is already a thread for this, but I could not figure out how to add to it. I've upgraded from LR3 to LR4, and the checkbox for Don't Import Suspected Duplicates no longer seems to be working. I've done nothing other than upgrade; I have