angularjs + spring mvc + json post request

时间:2014-04-05 13:29:42

标签: json spring angularjs spring-mvc post

我一直在网上就我的问题做一些研究,我觉得我的代码反映了大多数例子中写的内容 - 然而,它仍然无效。因此,我的问题。

长话短说,我想发送POST请求,将新项目添加到某些“后端”。对于REST API,我使用Spring MVC,用于发送我使用AngularJS

中的$ http的请求

这就是我调用POST请求的方式

    $scope.testAddItem = function(){
    $http({
        'url' : 'addNewItem',
        'method' : 'POST',
        'headers': {'Content-Type' : 'application/json'},
        'data' : $scope.newItem
    }).success(function(data){
        $scope.marketForm.texts.push({'text' : data.text});
    })
}

哪个映射到正确的URL。问题是我得到以下回复

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 400 BAD_REQUEST</title>
</head>
<body><h2>HTTP ERROR 400</h2>
<p>Problem accessing /poll/addNewItem/. Reason:
<pre>    BAD_REQUEST</pre></p><hr /><i><small>Powered by Jetty://</small></i><br/> 

当我点击网站上的按钮,以及通过某个REST客户端测试时,我收到此错误。

我已经包含在我的pom.xml

中的依赖项
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

一个注意事项 - 通过GET发送其他请求。

我的控制器类

@Controller
@RequestMapping(value = "/")
public class PollController {

@RequestMapping(method = RequestMethod.GET)
public String mainPage(){
    return "poll";
}

@RequestMapping(value = "/getNewElement")
public @ResponseBody
List<PollItem> getNewElement(){

    List<PollItem> listOfItems = new ArrayList<PollItem>(2);

    listOfItems.add(new PollItem("test 1"));
    listOfItems.add(new PollItem("test 2"));

    return listOfItems;
}

@RequestMapping(value = "/addNewItem", method = RequestMethod.POST, consumes =    MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody PollItem addNewElement(@RequestBody PollItem pollItem){
    pollItem.setId(2); // I know it makes no logical sense, but it's just for testing.
    return pollItem;
}

}

任何线索?

修改

添加调试模式后,似乎是一些JSON解析问题

Method [public com.poll.model.PollItem com.poll.controller.PollController.addNewElement(com.poll.model.PollItem)]

    org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected character ('a' (code 97)): expected a valid value (number, String, arr
    ay, object, 'true', 'false' or 'null')
    at [Source: HttpInputOverHTTP@5ce15706; line: 1, column: 2]; nested exception is org.codehaus.jackson.JsonParseException: Unexpected character ('a' (code 97)): expected
    a valid value (number, String, array, object, 'true', 'false' or 'null')
    at [Source: HttpInputOverHTTP@5ce15706; line: 1, column: 2]
    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readJavaType(MappingJacksonHttpMessageConverter.java:187)
    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.read(MappingJacksonHttpMessageConverter.java:179)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodAr
    gumentResolver.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:183)

    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:98)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:738)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:551)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:568)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1111)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:478)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:183)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1045)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:199)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:462)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:279)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:232)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:534)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536)
    at java.lang.Thread.run(Thread.java:724)
    Caused by: org.codehaus.jackson.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null'
    )
    at [Source: HttpInputOverHTTP@5ce15706; line: 1, column: 2]
    at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1433)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
    at org.codehaus.jackson.impl.Utf8StreamParser._handleUnexpectedValue(Utf8StreamParser.java:2090)
    at org.codehaus.jackson.impl.Utf8StreamParser._nextTokenNotInObject(Utf8StreamParser.java:606)
    at org.codehaus.jackson.impl.Utf8StreamParser.nextToken(Utf8StreamParser.java:492)
    at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2770)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2718)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1923)
    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readJavaType(MappingJacksonHttpMessageConverter.java:184)
    ... 38 more

EDIT2

似乎它有效,问题是它只支持“(双引号)我想使用单引号。有什么理由为什么我在做JSON时应该双引号?

我应该做些什么来改变JSON映射器的默认行为?

3 个答案:

答案 0 :(得分:3)

好的,回答这个问题 - 问题是我使用了格式错误的JSON。我应该使用双引号而不是单引号(这基本上遵循JSON标准。我是新手,我有点困惑,因为很多网站使用单引号作为他们的示例 - 例如谷歌图表)。

{"id":10,"text":"smth smth"}

很好

{'id':10,'text':'smth smth'}

错误:)

答案 1 :(得分:3)

如果你的JSON没有正确映射到服务器端对象,那么它就会抛出异常。我在这里找到了一个非常好的简单例子,正是你正在寻找的东西:

AngularJS Post Spring MVC JSON Example

AngularJS Form Post Spring MVC JSON

答案 2 :(得分:0)

您可能缺少PollItem域中的默认构造函数。

public class PollItem {
     public PollItem () {
     }
     //your rest of the codes
}

添加此代码,您的代码就可以正常使用。

你已经在PollItem中定义了一个构造函数,它使它成为默认的构造函数。因此添加虚拟构造函数将解决您的问题