복붙노트

[SPRING] 내 서비스 계층 내부에서 쿠키를 생성하고 http 응답에 추가하는 방법은 무엇입니까?

SPRING

내 서비스 계층 내부에서 쿠키를 생성하고 http 응답에 추가하는 방법은 무엇입니까?

내 봄 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
      }

   }

}

응답에 쿠키를 만들고 추가하려면 어떻게합니까?

해결법

  1. ==============================

    1.Spring MVC에서는 기본적으로 HtppServletResponce 객체를 얻는다.

    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. ==============================

    2.@ Aravind의 대답에 이어 더 자세한 정보 제공

    @ 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

  3. ==============================

    3.쿠키는 고객과 관련된 정보를 저장하는 키 값 쌍이있는 객체입니다. 주요 목표는 고객의 경험을 개인화하는 것입니다.

    쿠키는 고객과 관련된 정보를 저장하는 키 값 쌍이있는 객체입니다. 주요 목표는 고객의 경험을 개인화하는 것입니다.

    유틸리티 메소드는 다음과 같이 작성할 수 있습니다.

    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;
    }
    

    중요한 정보를 저장하는 경우 alsways는 setHttpOnly를 두어 쿠키가 javascript를 통해 액세스 / 수정 될 수 없도록해야합니다. setSecure는 쿠키가 https 프로토콜을 통해서만 액세스되도록하려는 경우에 적용 할 수 있습니다.

    위의 유틸리티 메소드를 사용하여 응답에 쿠키를 추가 할 수 있습니다.

    Cookie cookie = createCookie("name","value");
    response.addCookie(cookie);
    
  4. ==============================

    4.새 쿠키를 추가하려면 HttpServletResponse.addCookie (쿠키)를 사용하십시오. 쿠키는 건설 중 문자열로 이름과 가치를 취하는 핵심 가치 쌍입니다.

    새 쿠키를 추가하려면 HttpServletResponse.addCookie (쿠키)를 사용하십시오. 쿠키는 건설 중 문자열로 이름과 가치를 취하는 핵심 가치 쌍입니다.

  5. from https://stackoverflow.com/questions/8889679/how-to-create-a-cookie-and-add-to-http-response-from-inside-my-service-layer by cc-by-sa and MIT license