开发者

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

开发者 https://www.devze.com 2023-03-31 21:12 出处:网络
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 datab

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(i.e. 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=开发者_JAVA百科"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.

0

精彩评论

暂无评论...
验证码 换一张
取 消