How to transfer value from one JSP to another JSP page?

I have two JSP pages: search.jspand update.jsp.

When I run search.jsp, then one value is fetched from the database, and I store that value in a variable named scard. Now I want to use this variable value on another JSP page. I do not want to use request.getparameter().

Here is my code:

<% 
String scard = "";
String id = request.getParameter("id");

try {
    String selectStoredProc = "SELECT * FROM Councel WHERE CouncelRegNo ='"+id+"'";

    PreparedStatement ps = cn.prepareStatement(selectStoredProc);
    ResultSet rs = ps.executeQuery();

    while(rs.next()) {
        scard = rs.getString(23);
    }

    rs.close();
    rs = null;
} catch (Exception e) {
    out.println(e.getLocalizedMessage());
} finally {

}
%>

How can I achieve this?

+10
source share
4 answers

Using the query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using a hidden variable.

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

You can submit using the Session object.

   session.setAttribute("userId", userid);

These values ​​will now be available from any jsp while your session is still active.

   int userid = session.getAttribute("userId"); 
+16
source

jsp jsp

A.jsp

   <% String userid="Banda";%>
    <form action="B.jsp" method="post">
    <%
    session.setAttribute("userId", userid);
        %>
        <input type="submit"
                            value="Login">
    </form>

B.jsp

    <%String userid = session.getAttribute("userId").toString(); %>
    Hello<%=userid%>
+5

search.jsp

scard , session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

, session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>
+4

Suppose we want to pass three values ​​(u1, u2, u3) from say 'show.jsp' to another page, say 'display.jsp' Make three hidden text fields and a button that is automatically clicked (using javascript). // Code for writing to 'show.jsp'

<body>
<form action="display.jsp" method="post">
 <input type="hidden" name="u1" value="<%=u1%>"/>
 <input type="hidden" name="u2" value="<%=u2%>" />
 <input type="hidden" name="u3" value="<%=u3%>" />
 <button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
  <script type="text/javascript">
     document.getElementById("qq").click();
  </script>
</body>

// Code to be written to 'display.jsp'

 <% String u1 = request.getParameter("u1").toString();
    String u2 = request.getParameter("u2").toString();
    String u3 = request.getParameter("u3").toString();
 %>

If you want to use these servlet variables in javascript just write

<script type="text/javascript">
 var a=<%=u1%>;
</script>

Hope this helps :)

0
source

Source: https://habr.com/ru/post/1531492/


All Articles