Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a string in the session with Spring MVC?

I'm new to Spring MVC and I'm trying to figure out the appropriate way to do something that I think is very simple.

I have a simple jQuery AJAX call:

    var dataString = 'existingProject='+ $("#existingProject").val() + '&newProjName=' +      $("#newProjName").val();

    $.ajax({  
        type: "POST",  
        url: "manageProjects.html",  
        data: dataString            
    });

I want to set this user setting "project" for the session for the user. This AJAX call is coming out of a javascript in a JS file and connecting to my Spring MVC controller.

The Controller is getting these variables, but I'm not sure what to do with it to make this data passed-in session specific.

I've googled the hell out of this topic and come across 6 different options (injected Session scoped beans with autowiring, beans with xml config and cgl-nodep libraries, HttpServlet attributes, @ModelAttribute, @SessionAttribute, etc, etc). I tried to go with Session scoped beans and defined the following:

@Component
@Scope("session")
public class UserSettings

...But the bean wasn't being locked down to the session. I used @Autowire in my controller and found it was still the same instance between sessions so I clearly screwed it up.

I just want to save one freaking string! There's got to be a 101 level easy way to do this...

like image 400
Raevik Avatar asked Dec 22 '22 00:12

Raevik


1 Answers

@RequestMapping(value = "/request/mapping")
public ModelAndView methodName(HttpSession session,...){

session.setAttribute("testVariable", "Test Values!!");
}

or

@RequestMapping("/test")
@Controller
public class TestController {
    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request)
    {
        request.getSession().setAttribute("testVariable", "Test Values!!");
        return "testJsp";
    }
}
like image 176
fmucar Avatar answered Dec 28 '22 07:12

fmucar