Java 如何从我的服务层内部创建cookie并添加到http响应?
我正在spring mvc应用程序中创建自定义身份验证服务:Java 如何从我的服务层内部创建cookie并添加到http响应?,java,spring,cookies,spring-mvc,Java,Spring,Cookies,Spring Mvc,我正在spring mvc应用程序中创建自定义身份验证服务: @Service public class AuthenticationServiceImpl implements AuthenticationService { @Autowired UserService userService; @Override public void login(String email, String password) { boolean isValid =
@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并将其添加到响应中?要添加新cookie,请使用。基本上是一个键值对,在构造时将名称和值作为字符串。在Spring MVC中,默认情况下,您将获得htppServletResponse对象
@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);
以下是@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's subdirectories
response.addCookie(cookie);
}
相关文件:
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设置为不能通过javascript访问/修改cookie。如果您希望仅通过https协议访问Cookie,则SetSecurity适用
使用上述实用程序方法,您可以将cookie添加到响应中,如下所示:
Cookie cookie = createCookie("name","value");
response.addCookie(cookie);
顺便说一句,我不建议您这样做来创建自己的身份验证方案。