java - 如何从我的服务层内部创建一个 cookie 并添加到 http 响应?

标签 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 = userService.isValidLogin(email, password);

      if(isValid) {
          // ??? create a session cookie and add to http response
      }

   }

}

如何创建 cookie 并将其添加到响应中?

最佳答案

按照@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);
}

相关文档:

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

关于java - 如何从我的服务层内部创建一个 cookie 并添加到 http 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8889679/

相关文章:

java - 如何在android中获取和设置简单的数学函数?

java - HK2 类型文字和通配符

java - 如何使用java + hibernate将值插入SQL Server中的主键?

java - 如何在Spring Boot应用程序中添加方法级别身份验证?

android - WebView 不接受某些 cookie

javascript - 使用 Node.js 设置 HTTP header Cookie

java - 在 JTS 中联合几何更快?

java - 数组的 ArrayList 与 ArrayLists 的数组与类似的东西

java - 如何在java-spring应用程序中并行调用多个soap调用

java - 通过 HttpClient 接受所有 Cookie