1
我將數據保存到會話中,但後來我嘗試將其讀回,並且它爲空。 Spring MVC是我的後端,而Angular 4是前端。會話奇怪地返回null
的Java:
@RestController
@CrossOrigin(origins = "http://localhost:3009", allowCredentials = "true")
@RequestMapping(value = "api")
public class RestController {
@Autowired
MainLogic mainLogic;
@RequestMapping(value = "/data", method = RequestMethod.GET)
public List<Data> getData(HttpServletRequest httpServletRequest){
// user is null here)-:
User user = (User)httpServletRequest.getSession().getAttribute("user");
if (user == null) {
return null;
}
return mainLogic.getData();
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public LoginResult logIn(HttpServletRequest httpServletRequest, @RequestParam("username") String username, @RequestParam("password") String password){
LoginResult result = mainLogic.logIn(username, password);
if (result.getUser() != null) {
// user is not null here
httpServletRequest.getSession().setAttribute("user", result.getUser());
}
return result;
}
}
角:
logIn(username: string, password: string): Observable<LoginResult>{
let result = this.http
.post(`${this.baseUrl}/login?username=${username}&password=${password}` , {headers: configuration.getHeaders(), withCredentials: true})
.map(response => response.json());
return result;
}
getData(): Observable<Affiliate[]>{
let results = this.http
.get(`${this.baseUrl}/data`, {headers: configuration.getHeaders(), withCredentials: true})
.map(response => response.json());
return results;
}
任何想法,我在這裏失蹤?也許與CORS有什麼關係?
可能重複[Java新會話爲每個請求?](https://stackoverflow.com/questions/19067787/java-new-session-for-each-request) – user7294900
你可以檢查,如果httpServletRequest.getSession( )在這兩種情況下返回相同的對象? – alexd
@ user7294900剛剛嘗試過,並沒有幫助 – Alon