开发者

How to store JavaScript variable value in JSP session [duplicate]

This question already has answers here: how to access the javascript variable in jsp [duplicate] 开发者_开发技巧 (3 answers) Closed 5 years ago.

I want to store a JavaScript variable value in JSP session to use it further in my Java classes methods. Please provide solution for storing any JavaScript variable in JSP session.


Pass that variable to Servlet using ajax OR set it in some hidden field when form will get submit it will also get POSTed.


Make an AJAX call from your JSP to a different JSP that does that. The jsp will take a variable name and its value as request parameters and will put the variable in the session.

You cannot do this with client side (javascript) code only !


Your best bet is to just store the value in a cookie. Both client side javascript and server side jsp can access cookies.


There should be a natural flow to your program, so that you don't have to have a mechanism specifically for storing variables just for the sake of storing variables. By that I mean that if you are storing a userName, it should be while login is occurring, or if you are obtaining contactInfo, then you should have a servlet specifically for that purpose. Regardless, here is a three part answer to your question. It is very general and non-specific, but will accomplish what you want once fleshed out:

Here is the web.xml file:

    <servlet>
        <servlet-name>StoreVariableServlet</servlet-name>
        <servlet-class>tests.servlets.StoreVariableServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>StoreVariableServlet</servlet-name>
        <url-pattern>/storeVariableServlet</url-pattern>
    </servlet-mapping>

Here is the jQuery Code:

    $.ajax({
        type: "POST",
        url: "/storeVariableServlet",
        data: ({
            variable : $(variableName).val()
        }),
        success: function(){
            alert("Success");
        }
    });

Here is the Servlet Code:

    String variableToBeStored = request.getParameter("variable");
    HttpSession session = request.getSession();
    session.setAttribute("variableXYZ", variableToBeStored);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜