【问题标题】:Session strangely returns null会话奇怪地返回 null
【发布时间】:2017-08-17 10:54:46
【问题描述】:

我将数据保存到会话中,但随后我尝试将其读回,结果为空。 Spring MVC 是我的后端,Angular 4 是前端。

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 有关?

【问题讨论】:

  • 你能检查一下 httpServletRequest.getSession() 在这两种情况下是否返回相同的对象吗?
  • @user7294900 刚试过,没用
  • @alexd 不是,第二次是不同的会话
  • @alexd 可能与 CORS 有关?

标签: javascript java spring angular spring-mvc


【解决方案1】:

你能检查一下是否启用了cookies吗?

【讨论】:

  • 你的意思是在浏览器中?是的。
猜你喜欢
  • 2017-03-02
  • 2016-09-23
  • 2015-10-11
  • 2019-06-08
  • 2017-07-03
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
相关资源
最近更新 更多