2017-09-24 7 views
1

나는 스프링과 함께 몇 개의 간단한 페이지들을 모으고 있으며 세션을 위해 지속되는 객체에 어떤 데이터를 추가하려고한다. GET 요청은 지속되지만 POST 메소드를 사용하여 생성 된 요청은 지속되지 않는 것으로 보입니다. I 탐색시에 "/"UserData.isLoggedIn()의 출력이 거짓Spring에서 POST 요청시 세션 범위에있는 객체를 유지하는 방법은 무엇입니까?

package com.mycompany.controllers; 
... 
@RestController 
@Scope("session") 
public class DefaultController { 

    @Autowired 
    UserData userData; 

    ... 

    @GetMapping("/") 
    public ResponseEntity index() { 

     printUserData(userData); 

     ResponseEntity entity; 
     if((entity = authenticate(userData)) != null) { 
      return entity; 
     } 
     ... 
    } 

    @GetMapping("/setloggedIn") 
    public ResponseEntity setLoggedIn() { 

     printUserData(userData); 

     userData.setLoggedIn(true); 
    } 

    @PostMapping("/logIn") 
    public ResponseEntity logIn(@RequestBody LogInDTO dto) { 

     printUserData(userData); 
     ... 
     userData.setLoggedIn(true); 
    } 


    protected static void printUserData(UserData user) { 
     if(user== null) { 
      LOG.info("UserData is null"); 
      return; 
     } 

     LOG.info("UserData logged in: {}", user.isLoggedIn()); 
    } 
} 
  • 이다

    package com.mycompany.controllers.components; 
    
    import org.springframework.context.annotation.Scope; 
    import org.springframework.stereotype.Component; 
    
    @Component 
    @Scope("session") 
    public class UserData { 
    
        private boolean loggedIn; 
    
        public UserData() { 
         loggedIn = false; 
        } 
    
        public boolean isLoggedIn() { 
         return loggedIn; 
        } 
    
        public void setLoggedIn(boolean loggedIn) { 
         this.loggedIn = loggedIn; 
        } 
    } 
    

    다음 I는 제어기가 다음과 같이

    는 I는 UserData를 성분이 예상했다.

  • "/ logIn"에 게시 요청을하면 예상대로 출력이 다시 false로 설정됩니다. 일부 매개 변수 유효성 검사 후 UserData.setLoggedIn(true) 메서드가 호출되었지만 "/"로 이동해도 출력은 여전히 ​​false입니다.

  • "/ setLoggedIn"로 이동 한 후 loggedIn은 처음에는 false이지만 loggedIn을 true로 설정하면 "/"또는 "/ setLoggedIn"에 대한 모든 요청의 결과가 true가됩니다.

  • 또한 POST 요청은 "/ 로그인"

거짓

의 출력 내가 뭔가 실종을 제공하거나이 정상 동작은?

나는 GET 요청에 세션 ID를 검사 할 때 나는 내 쿠키에 저장된 JSESSIONID 동일하다고 볼 수 있습니다 1

UPDATE. 모든 POST 요청마다 다른 세션 ID가 표시됩니다.

질문은 어떻게 JSESSIONID를 POST 요청과 함께 보내야합니까? 다음과 같이 저는 현재 요청을 수행하고 있습니다 :

fetch('/logIn', { 
    method: 'POST', 
    body: JSON.stringify({ 
     username: txtUsername.value, 
     password: txtPassword.value 
    }), 
    headers : { 
     'Content-Type' : 'application/json' 
    } 
}) 
.then(result => { 
    result.text().then(function(text) { 
     if(result.status == 200) { 
      location.reload(); 
     } else { 
      alert("Error:\n" + text); 
     } 
    }); 
}) 
.catch(e => { 
    console.log(e); 
    alert("Error:\n" + e); 

}); 

UPDATE 나는 JSESSIONID 쿠키는 Http 만 것을 발견하고 자바 스크립트를 읽을 수없고 그게이 함께 전송 아니에요 이유가 될 수 2

POST 요청? 서블릿이 매번 새로운 세션을 생성하게합니다.

답변

0

fetch 명령은 "자격 증명": 'include' "을 true로 설정해야합니다. 이렇게하면 게시 전용 요청과 함께 http 전용 쿠키를 보낼 수 있으므로 서버가 현재 세션을 확인할 수 있습니다. 이렇게 :

fetch('/logIn', { 
    method: 'POST', 
    body: JSON.stringify({ 
    username: txtUsername.value, 
    password: txtPassword.value 
    }), 
    credentials: 'include', // <<< FIX 
    headers : { 
    'Content-Type' : 'application/json' 
    } 
}) 
.then(result => { 
    result.text().then(function(text) { 
    if(result.status == 200) { 
     location.reload(); 
    } else { 
     alert("Error:\n" + text); 
    } 
    }); 
}) 
.catch(e => { 
    console.log(e); 
    alert("Error:\n" + e); 
});