最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Set session attribute using javascript - Stack Overflow

programmeradmin2浏览0评论

I'm using jqueryui autoplete bobox in my jsp page. I need to set selected value of bo-box to the HttpSession.

I tried as below.

this._on(this.input, {
    autopleteselect: function (event, ui) {
        // alert(ui.item.value);
        var value = ui.item.value;
        <% session.setAttribute("boboxvalue",value); %>  

        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
}

Problem with this way is that code don't recognize value param.

How can I solve this and set session attribute using javascript ?

I'm using jqueryui autoplete bobox in my jsp page. I need to set selected value of bo-box to the HttpSession.

I tried as below.

this._on(this.input, {
    autopleteselect: function (event, ui) {
        // alert(ui.item.value);
        var value = ui.item.value;
        <% session.setAttribute("boboxvalue",value); %>  

        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
}

Problem with this way is that code don't recognize value param.

How can I solve this and set session attribute using javascript ?

Share Improve this question edited Jul 6, 2017 at 5:16 Bishan asked Aug 3, 2013 at 11:08 BishanBishan 15.7k53 gold badges171 silver badges268 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

You might misunderstand that jsp and javascript existed on same file. Yes but JSP part piles on server side itself es to client.

The code inbetween <% %> executes on serverside.

You can't do that with Javascript.

You need to make a server request(There are forms,Ajax,url..etc) for that.

Java script is a client side technology. Its not possible to set any session variables from Java script.

You can do this using Ajax. Through Ajax you have to send a request to the server asynchronously and then add the data to the session from within the servlet.

Here is how I achieved my task successfully.

I have created a new servlet and trigger an AJAX call as below. Then I set boboxvalue to session from servlet.

this._on( this.input, {
    autopleteselect: function( event, ui ) {
        $.ajax({
        type: 'POST',
        url: 'AjaxServlet',
        dataType : 'json',
        data: { boboxvalue : ui.item.value  }
        });
        ui.item.option.selected = true;
        this._trigger( "select", event, {
            item: ui.item.option
        });
    },

    autopletechange: "_removeIfInvalid"
});

You cannot set session values in JavaScript.

For your case, you can trigger an AJAX call for onChange event in your select box. You can simply send the select box value to server and place it in session.

you can use javaScript operating form to post args to a servlet class, and setSession in this servlet class.

发布评论

评论列表(0)

  1. 暂无评论