开发者

Spring MVC - Variables between pages, and Unsetting a SessionAttribute

The question sounds weird, I'm playing around with Spring MVC and am trying to move between two pages and basically I'm creating a JSP page using Spring Form JSTL's so it just uses a POST, and I use a controller to move from one page to the next. But Models are lost from page to page, and I'd like to hide the actual variable so QueryStrings are out of the question(as far as I know). I know I can use a InternalResourceView, but only allows me to use a model.

I want to transfer a variable that will be exclus开发者_高级运维ive to that page, what's the best way without a model or using QueryStrings?

I was planning on using SessionAttribute to easily define them, but was wondering, how do you remove a SessionAttribute created variable? I tried HttpSession.removeAttribute and it didn't seem to work.


You can also use SessionStatus.setComplete() like this:

@RequestMapping(method = RequestMethod.GET, value="/clear")
public ModelAndView clear(SessionStatus status, ModelMap model, HttpServletRequest request) {
    model.clear();
    status.setComplete();
    return new ModelAndView("somePage");
}

or DefaultSessionAttributeStore.cleanUpAttribute like this:

@RequestMapping(method = RequestMethod.GET, value="/clear")
public ModelAndView clear(DefaultSessionAttributeStore status, WebRequest request, ModelMap model) {
    model.remove("mySessionVar");
    status.cleanupAttribute(request, "mySessionVar");
    return new ModelAndView("somePage");
}

I use it like this on one of my forms that has mulitple sessionAttributes and I want to remove only one of them.


Yes... HttpSession.removeAttribute


You can use the removeAttribute method from the HttpSession class.


you can use WebRequest.removeAttribute(String name, int scope) that works with Spring @SessionAttributes. Quote from @SessionAttributes javadoc - "Alternatively, consider using the attribute management capabilities of the generic {@link org.springframework.web.context.request.WebRequest} interface."

Also look at my example.

@Controller
@SessionAttributes({"sessionAttr"})
public class MyController {

    @ModelAttribute("sessionAttr")
    public Object defaultSessionAttr() {
        return new Object();
    }

    @RequestMapping(value = "...", method = RequestMethod.GET)
    public String removeSessionAttr(WebRequest request, Model model) {
        request.removeAttribute("sessionAttr", WebRequest.SCOPE_SESSION);

        model.addAttribute("sessionAttr", defaultSessionAttr());
        return "myView";
    }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜