java 使用 Cookies 保存 Spring MVC 表单字段中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13173635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:46:03  来源:igfitidea点击:

Using Cookies to save the values in Spring MVC form fields

javaspringjspspring-mvccookies

提问by Paulius Matulionis

Lets say I have a Spring MVCform like this:

假设我有一个这样的Spring MVC表单:

<form:form action="${pageContext.servletContext.contextPath}/secure/main.htm" commandName="secure/main">

    <form:input path="operatorId" cssClass="textField"/>

    <form:input path="clientId" cssClass="textField"/>

</form:form>

What I am trying to do is to store those fields values in the cookies that they will be saved other time user logins into the system. It is similar to Remember Mecheckbox, but just without the checkbox. My controller looks like this:

我想要做的是将这些字段值存储在 cookie 中,它们将在用户登录系统时保存。它类似于Remember Me复选框,但只是没有复选框。我的控制器看起来像这样:

@RequestMapping(method = RequestMethod.POST)
public String processAuthenticate(@Valid AuthenticationForm authenticationForm,
                                  Map<String, Object> model,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {

    authenticationForm = (AuthenticationForm) model.get("authenticationForm");

    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        System.out.println(cookie.getValue());
        if (cookie.getName().equals("clientId")) {
            authenticationForm.setClientId(cookie.getValue());
        } else if (cookie.getName().equals("operatorId")) {
            authenticationForm.setOperatorId(cookie.getValue());
        }
    }

    String clientId = authenticationForm.getClientId();
    String operatorId = authenticationForm.getOperatorId();

    Cookie cookieClientId= new Cookie("clientId", clientId);
    cookieClientId.setMaxAge(COOKIE_EXPIRY);
    response.addCookie(cookieClientId);

    Cookie cookieOperatorId = new Cookie("operatorId", operatorId);
    cookieOperatorId.setMaxAge(COOKIE_EXPIRY);
    response.addCookie(cookieOperatorId);

    return MAIN_FORM_MAPPING;
}

But when I click the button and this method is invoked, my values are not saved. It is the first time I am trying to use Cookiesso maybe I am missing something? I was following this SOquestion. But in my case this does not work. Anybody could advice me with the solution to this problem?

但是当我单击按钮并调用此方法时,我的值没有保存。这是我第一次尝试使用,Cookies所以也许我遗漏了什么?我正在关注这个问题。但在我的情况下,这不起作用。任何人都可以建议我解决这个问题吗?

采纳答案by Paulius Matulionis

Sorry for the false alarm. I was doing everything right, but I had a method which within each request returned new AuthenticationFormobject as a model attribute, like this:

抱歉误报。我做的一切都是正确的,但我有一个方法,它在每个请求中返回新AuthenticationForm对象作为模型属性,如下所示:

@ModelAttribute("secure/" + MAIN_FORM_MAPPING)
public AuthenticationForm getAuthenticationForm() {
    return new AuthenticationForm();
}

And I had a method which is used to show the form in the view:

我有一个方法用于在视图中显示表单:

@RequestMapping(method = {RequestMethod.GET})
public String showForm(Map<String, Object> model, HttpServletRequest request) {
    AuthenticationForm authenticationForm = (AuthenticationForm) model.get("secure/main");
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        System.out.println(cookie.getValue());
        if (cookie.getName().equals("clientId")) {
           authenticationForm.setClientId(cookie.getValue());   //Just added this code to this method
        } else if (cookie.getName().equals("operatorId")) {
           authenticationForm.setOperatorId(cookie.getValue());
        }
    }
    return MAIN_FORM_MAPPING;
}

Then I realized that this form object is always new, so the values I am setting from cookies always on a new form. I had to set the values from cookies in the showFormmethod and everything is working.

然后我意识到这个表单对象总是新的,所以我从 cookie 设置的值总是在一个新表单上。我必须在showForm方法中设置来自 cookie 的值,并且一切正常。

回答by Sajith

Please check whether this is useful. In spring mvc 3, how to write a cookie while returning a ModelAndView?

请检查这是否有用。 在spring mvc 3中,如何在返回ModelAndView的同时编写cookie?

@RequestMapping("/example")
private ModelAndView exampleHandler(HttpServletResponse response) {

        response.addCookie(new Cookie("COOKIENAME", "The cookie's value"));

        return new ModelAndView("viewname");
}