Hularnate Object作为AngularJS和Spring中的@RequestBody

时间:2017-04-19 14:30:15

标签: java angularjs spring spring-mvc spring-restcontroller

我有以下html文件

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script>
    angular.module("myapp", [])
    .controller("MyController", ['$scope', '$http', function($scope, $http) {
        console.log("Start");
        $scope.myForm = {};
        $scope.role = [{ roleName :"A"},{roleName : "B"},{ roleName : "C"}];
        $scope.submitForm = function() {
            var dataObj = {
                    "attUid" : $scope.myForm.firstName,
                    "role" : $scope.myForm.selectedRole
            };  
            $http.post('/UPRS/services/poc/add',dataObj).then(function(response) {
                console.log("Success!");
            },
            function(error) {
                console.log("Something went wrong!");
            });
        }
    }]);
  </script>

</head>

<body ng-app="myapp">

  <div ng-controller="MyController">
    <form ng-submit="submitForm()" method="POST">
      ATTID :
      <input type="text" name="firstName" ng-model="myForm.firstName">
      <br/> Role :
      <select ng-model="myForm.selectedRole" ng-options="r.roleName for r in role"></select>
      <br/>
      <input type="submit" id="submit" value="Submit" />
    </form>
    <div>
      {{myForm.firstName}} {{selectedRole.roleName}}
    </div>
  </div>


</body>

</html>

我的Hibernate对象文件是:

@Entity
@Table(name="ATTUIDRoles")
public class Role {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="No")
    Long no;

    @Column(name="ATTUID")
    String attUid;


    @Column(name="Role")
    String role;


    public Long getNo() {
        return no;
    }


    public void setNo(Long no) {
        this.no = no;
    }


    public String getAttUid() {
        return attUid;
    }


    public void setAttUid(String attUid) {
        this.attUid = attUid;
    }


    public String getRole() {
        return role;
    }


    public void setRole(String role) {
        this.role = role;
    }


}

我的服务档案是:

@RestController
@RequestMapping("/poc")
public class POCService {

    @Autowired
    POCRepository pocRepository;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void addPOCDetails(@RequestBody Role role){
        System.out.println("HI");
        System.out.println(role.getAttUid());
        System.out.println(role.getRole());
    }
}

错误生成为:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:228)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:213)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:197)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:149)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:127)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:261)
    at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1233)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1121)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1074)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:490)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2913)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:225)
    ... 34 common frames omitted
19:50:30.897 [http-bio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public void org.uprs.services.POCService.addPOCDetails(org.uprs.model.Role)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"])
19:50:30.897 [http-bio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public void org.uprs.services.POCService.addPOCDetails(org.uprs.model.Role)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"])
19:50:30.897 [http-bio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public void org.uprs.services.POCService.addPOCDetails(org.uprs.model.Role)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"])
19:50:30.898 [http-bio-8080-exec-5] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@f354fd; line: 1, column: 23] (through reference chain: org.uprs.model.Role["role"])
19:50:30.898 [http-bio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling
19:50:30.898 [http-bio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request

我已经使用了hibernate对象,就像在responsebody中一样。由于它有什么影响,或者其他东西就是这种情况。请接受我的帮助。

2 个答案:

答案 0 :(得分:1)

h1返回对象。

您应该使用$scope.myForm.selectedRole获取roleName值。

答案 1 :(得分:-1)

implements Serializable添加到您的角色实体定义。