Angular 2 Spring Restful webservice中的会话管理

时间:2017-08-15 03:07:13

标签: angular session session-cookies spring-restcontroller

我正在学习角度2.我正在尝试在角度2和弹簧mvc中进行会话管理。我发现很多关于角1的文章,但没有找到有关angular2的任何重要内容。我尝试使用withCredentials:true,但它没有用。

       var headers = new Headers();
       headers.append('Content-Type', 'application/json');
       headers.append( 'Accept', 'application/json;charset=UTF-8');
       let options = new RequestOptions({headers: headers, withCredentials:true });
       return this.http.get('http://localhost:8080/getAllProducts', options).map((res:Response) => res.json()).subscribe();

在产品控制器中,我试图按如下方式进行会话。

public @ResponseBody List<Product> getAllProducts(HttpServletRequest httpRequest) {
    System.out.println("Inside product controller");
    HttpSession httpSession = httpRequest.getSession(false);
    List<Product> productList = Collections.emptyList();
    if (httpSession == null) {
        //TODO - Redirect to login page.
    } else {
        productList = new ArrayList<>();
        Product product = new Product();
        product.setDescription("Product1 Description");
        product.setName("Product1 Name");
        product.setPrice(BigDecimal.TEN);
        product.setSku("PRODUCT1_SKU");
        productList.add(product);
    }

但我总是将会话视为null。我已经在登录控制器中创建了会话,并在会话中设置属性如下。

@ResponseBody public String login(@RequestBody User user, HttpServletRequest request) throws JSONException {
    System.out.println("Inside Login Controller");
    if ("abc".equalsIgnoreCase(user.getUsername()) && "xyz".equals(user.getPassword())) {
        HttpSession httpSession = request.getSession(true);
        httpSession.setAttribute("username", user.getUsername());
    }

0 个答案:

没有答案