Как создать cookie и добавить к HTTP-ответу внутри моего уровня обслуживания?
Я создаю собственную службу проверки подлинности в моем приложении spring mvc:
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
@Autowired
UserService userService;
@Override
public void login(String email, String password) {
boolean isValid = userService.isValidLogin(email, password);
if(isValid) {
// ??? create a session cookie and add to http response
}
}
}
Как я могу создать и добавить файл cookie в ответ?
Ответы
Ответ 1
В Spring MVC вы получаете объект HtppServletResponce по умолчанию.
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception{
//Do service call passing the response
return new ModelAndView("CustomerAddView");
}
//Service code
Cookie myCookie =
new Cookie("name", "val");
response.addCookie(myCookie);
Ответ 2
Следуя @Aravind ответьте более подробно
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory subdirectories
response.addCookie(cookie);
}
Связанные документы:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
Ответ 3
Файл cookie представляет собой объект с парой значений ключа для хранения информации, относящейся к клиенту. Основная цель - персонализировать опыт клиентов.
Можно использовать метод утилиты, например
private Cookie createCookie(String cookieName, String cookieValue) {
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setPath("/");
cookie.setMaxAge(MAX_AGE_SECONDS);
cookie.setHttpOnly(true);
cookie.setSecure(true);
return cookie;
}
Если вы храните важную информацию, мы должны также добавить setHttpOnly, чтобы файл cookie не был доступен или изменен с помощью javascript. setSecure применим, если вы хотите, чтобы файлы cookie были доступны только по протоколу https.
используя вышеуказанный метод утилиты, вы можете добавить файлы cookie в ответ как
Cookie cookie = createCookie("name","value");
response.addCookie(cookie);
Ответ 4
Чтобы добавить новый файл cookie, используйте HttpServletResponse.addCookie(Cookie). Cookie - это почти пара ключевых значений, принимающая имя и значение как строки при построении.