sending variable from one jsp to another jsp

55,055

Solution 1

You have a number of options:

  1. Store it in the session.

    // Memorise any passed in user.
    String username = request.getParameter("username");
    if (username != null && username.length() > 0) {
      session.setAttribute("username", username);
    }
    
  2. Store it as a hidden field in the form.

    <input name="username" type="hidden" value=""/>
    
  3. Store it in a cookie.

    username = getCookie(userCookieName);
    
    // Get from cookie.
    function getCookie(name) {
      if (document.cookie) {
        index = document.cookie.indexOf(name);
        if (index !== -1) {
          f = (document.cookie.indexOf("=", index) + 1);
          t = document.cookie.indexOf(";", index);
          if (t === -1) {
            t = document.cookie.length;
          }
          return(document.cookie.substring(f, t));
        }
      }
      return ("");
    }
    
  4. Persist it on the client side in sessionStorage. See here for details.

    sessionStorage.setItem("username", "...");
    
  5. Not really another option but a mechanism - pass it in the URL:

    .... onclick="window.location='details.jsp?username=...'
    

Solution 2

If the reason for including your jsp 2 in jsp 1 is for sending variable, then its not needed. you just need to set a hidden variable in jsp 1, and in your jsp 2 you should able to access it, by using the jsp implicit request object.

Solution 3

Try to use Ajax with JQuery to achieve your goal or you can simply store the String object in session and you can delete it in jsp2.jsp when ever you use it. or you can simply append to a url as query string there are multiple ways among them the above are few.

These questions may help you

Question 1

Question 2

Question 3

Question 4

Share:
55,055
Mayur Gupta
Author by

Mayur Gupta

I am a Software Developer.

Updated on July 09, 2022

Comments

  • Mayur Gupta
    Mayur Gupta almost 2 years

    I have one JSP file as jsp 1.jsp and another JSP file as jsp 2.jsp

    I've included jsp 2.jsp in jsp 1.jsp using <%@include file="jsp 2.jsp" %>

    Now I need a click event on some element. And on that event I want to transfer a string variable to included jsp.

    Lets say I have a list and on click of it I want to transfer the name of the list to another JSP,

    And in another JSP I am trying to use that string to carry out some task.

    And I am doing all these without any servlet. challenging one!! I have google'd a lot, but didnt find anything.