Lets say I have a Spring MVC form like this:
<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 Me checkbox, but just without the checkbox. My controller looks like this:
@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 Cookies so maybe I am missing something? I was following this SO question. But in my case this does not work. Anybody could advice me with the solution to this problem?
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:And I had a method which is used to show the form in the view:
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.