2016-05-10 64 views
0

我想使用SpringBoot和@RestController 這裏REST API創建Angularjs Web客戶端是實體產品:

package com.agTest.entities; 

import java.io.Serializable; 

import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 

@Entity 
public class Product implements Serializable{ 
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    private Long idProduct; 
    private String description; 
    private double prix; 


    public Product() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 


    public Product(String description, double prix) { 
     super(); 
     this.description = description; 
     this.prix = prix; 
    } 


    public Long getIdProduct() { 
     return idProduct; 
    } 
    public void setIdProduct(Long idProduct) { 
     this.idProduct = idProduct; 
    } 
    public String getDescription() { 
     return description; 
    } 
    public void setDescription(String description) { 
     this.description = description; 
    } 
    public double getPrix() { 
     return prix; 
    } 
    public void setPrix(double prix) { 
     this.prix = prix; 
    } 

} 

這裏是我的ProductRepository接口使用JpaRepository:

package com.agTest.Dao; 

import org.springframework.data.jpa.repository.JpaRepository; 

import com.agTest.entities.Product; 

public interface ProductRepository extends JpaRepository<Product, Long>{ 

} 

這裏是我的ProductMetier接口:

package com.agTest.services; 

import java.util.List; 

import com.agTest.entities.Product; 

public interface ProductMetier { 
    public Product saveProduct(Product p); 
    public List<Product> getProducts(); 

} 

這裏是我的ProductMetierImpl類:

package com.agTest.services; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 

import com.agTest.Dao.ProductRepository; 
import com.agTest.entities.Product; 
@Service 
public class ProductMetierImpl implements ProductMetier{ 

    @Autowired 
    private ProductRepository productRepository; 
    @Override 
    public Product saveProduct(Product p) { 
     productRepository.save(p); 
     return p; 
    } 

    @Override 
    public List<Product> getProducts() { 

     return productRepository.findAll(); 
    } 

} 

這裏是我的@RestController類:

package com.agTest.RestServices; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

import com.agTest.entities.Product; 
import com.agTest.services.ProductMetier; 

@RestController 
public class ProductRestService { 

    @Autowired 
    private ProductMetier productMetier; 

    @RequestMapping(value="/products", method=RequestMethod.POST) 
    public Product saveProduct(@RequestBody Product p){ 
     return productMetier.saveProduct(p); 
    } 

    @RequestMapping(value="/products", method=RequestMethod.GET) 
    public List<Product> getProducts(){ 
     return productMetier.getProducts(); 
    } 

} 

這裏是我的application.properties:

# Datasource settings: 
spring.datasource.url = jdbc:mysql://localhost:3306/agence_test 
spring.datasource.username = root 
spring.datasource.password = 
spring.datasource.driver-class-name = com.mysql.jdbc.Driver 

spring.jpa.database = MYSQL 

spring.jpa.show-sql = true 

spring.jpa.hibernate.ddl-auto = update 
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 

我過我的API與郵遞員並且一切都很順利,但是當我嘗試創建angularjs客戶端時,http Post方法返回一個異常:

這裏是我的angularjs控制器:

var app=angular.module("AVG",[]); 
app.controller("AVGController",function($scope,$http){ 

    $scope.products=[]; 
    $scope.description=null; 
    $scope.prix=null; 

    $scope.getProducts= function(){ 

     $http.get("/products") 
     .success(function(data){ 
      $scope.products=data; 
     }) 
     .error(function(data){ 
      alert("error"); 
     }); 

    }; 
    // headers :{'Content-Type':'application/json'} 
    $scope.saveMembre= function(){ 
     $http({ 
       method : 'POST', 
       url : "/products", 
       data : "description="+$scope.description+"prix="+$scope.prix, 
       headers :{'Content-Type':'application/json'} 


     }) 
     .success(function(data){ 
      alert("success"); 
     }) 
     .error(function(data){ 
       alert("error"); 
      }); 


    }; 



}); 

這裏是我的index.html:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="ISO-8859-1"> 
<link rel="stylesheet" type="text/css" href=""bootstrap-3.3.6-dist/css/bootstrap.min.css""/> 
<title>Agence Test</title> 
</head> 
<body ng-app="AVG" ng-controller="AVGController"> 
    <h1>AVE.com</h1> 
    <!-- Sauvegarde des Membres --> 
    <div> 

    <form> 
    <label>Description</label> 
    <input type="text" ng-model="description"/> 
    <label>Prix</label> 
    <input type="text" ng-model="prix"/> 
    <button ng-click="saveMembre()"> SAVE </button> 
    </form> 

    </div> 



    <!-- Affichage des Membres --> 
    <div > 
    <button type="button" ng-click="getProducts()">Get Products</button> 
    <table> 
    <tr> 
    <th>ID</th> <th>DESCRIPTION</th> <th>PRIX</th> 
    </tr> 
    <tr ng-repeat="item in products"> 
    <td>{{item.idProduct}}</td> 
    <td>{{item.description}}</td> 
    <td>{{item.prix}}</td> 
    </tr> 
    </table> 
    <!-- <ul> 
     <li ng-repeat="item in membres"> {{item.idMembre}}</li> 
     <li ng-repeat="item in membres"> {{item.nomMembre}}</li> 
    </ul> --> 
</div> 

    <script type="text/javascript" src="angular/angular.min.js"></script> 
    <script type="text/javascript" src="js/app.js"></script> 

</body> 
</html> 

這裏異常調用HTTP POST方法返回的時候:

Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_ 
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_ 
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_ 
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_ 
Hibernate: select product0_.id_product as id_produ1_0_, product0_.description as descript2_0_, product0_.prix as prix3_0_ from product product0_ 
2016-05-10 18:03:33.978 WARN 5420 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'description': was expecting ('true', 'false' or 'null') 
at [Source: [email protected]; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'description': was expecting ('true', 'false' or 'null') 
at [Source: [email protected]; line: 1, column: 13] 

的HTTP獲得方法按預期工作

p在我的PEF中租用我需要的任何幫助,我花了很多時間在上面!

回答

0

$ http post期望的'data'是一個對象,而不是一個字符串。 Try:

data : {"description":$scope.description, "prix":$scope.prix} 
+0

認爲弟弟亨利,我真的不知道怎麼想的,你 –

0

你的彈簧代碼沒有問題。這裏唯一的問題是,你的要求是如何發送值

在你的Ajax請求($ HTTP),你需要發送請求以這種形式

data : {"property1":value1, "property2": value2, ....,"propertyN" : value"} 

你可以看到,在即將值開發者工具網絡選項卡

希望這有些幫助。

快樂學習:)

+0

感謝兄弟它的工作原理 –