I am new to spring MVC and started to make a sample application by doing what I learned. I am planning to implement Session management in spring MVC. I found this one helpful.
But I am not able to get it clearly. We add values to the session like
HttpSession session = request.getSession(false);
session.setAttribute("key", value);
session.setAttribute("key1", value1);
and later on we fetch values based on the keys like
session.getAttrubute("key");
but in spring MVC, I could not see anything similar and it totally confuses me.
@Controller
@SessionAttributes("thought")
public class SingleFieldController {
@RequestMapping(value="/single-field")
public ModelAndView singleFieldPage() {
return new ModelAndView("single-field-page");
}
@RequestMapping(value="/remember")
public ModelAndView rememberThought(@RequestParam String thoughtParam) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("thought", thoughtParam);
modelAndView.setViewName("single-field-page");
return modelAndView;
}
}
In the above code @SessionAttributes("thought")
is totally confusing me like what is this thought
defined also I have no need to return a ModelAndView
since I am using backbone.marionette.js
So how can I set values in a session and use them whenever required? I also have to convert the session object to my user defined object since, while returning the values to screen, I return only a List of UserDefined objects which are available in the session.
So please help me to understand it better. Maybe I am confused with the way I used jsp / servlet.
UPDATE
Below is the controller I have and provided comments
package com.hexgen.puppet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.hexgen.puppet.CreatePuppet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class PuppetService {
@RequestMapping(method = RequestMethod.POST, value = "/create")
public @ResponseBody
void createOrder(@RequestBody CreatePuppet request) {
//logic to add/update values in session
}
@RequestMapping(method = RequestMethod.GET, value = "/list")
public @ResponseBody
List<Puppet> getGroups() {
//logic to retrive objects from session and convert it as List and send it back
return puppets;
}
}
and convert the object if needed and go on
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…