简体   繁体   中英

How do I share session attributes between a servlet and jsp file?

I have a form which when submitted stores data from it's fields to the database. The action forward in the struts-config maps back to the same page on Success/Failure of data insertion into the database. I would like to alert the user once this is successfully completed, so I set a session attribute(ie success/failure) in the method of the action class for the form. I then get and print out this session attribute once the jsp page has been accessed again.

So far I have done this in the Action Class:

 public static void setJavaScriptNotification(HttpServletRequest request, String notificationText) {

    HttpSession session = request.getSession(true);
    session.setAttribute("notification_javascript", notificationText);

}

And in the jsp file that contains the form I have:

    <% String notificationJavaScript = (String) request.getSession().getAttribute("notification_javascript");
pageContext.setAttribute("notification_javascript", notificationJavaScript);
request.getSession().removeAttribute("notification_javascript"); %>

<html>
<head>
<logic:present name="notification_javascript">
        <script type="text/javascript" language="JavaScript">
            function showAlerts() {
                alert("<bean:write name="notification_javascript"/>");
            }
        </script>
    </logic:present>
</head>       
<body onload="doPreOnload(); showAlerts();">

When I print out the session attributes in the jsp, I can't find the notification_javascript attribute. I'm new to HTTP, so I could be doing something wrong there.

  • After setting notification_javascript in session in setJavaScriptNotification() do the request is forwarded to jsp where notification_javascript is accessed.

  • If yes, then session.getAttribute("notification_javascript") will do the job.

    request.setAttribute() vs session.setAttribute()

  • request.setAttribute() will make the key available in following page.

  • session.setAttribute() will make the key available in all pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM