Spring mvc - Ajax响应

时间:2015-01-04 02:07:21

标签: ajax spring-mvc

我正在尝试使用ajax向服务器提交表单。我已经查看了各种教程,但无法弄清楚我自己的错误。因为我刚刚开始学习ajax,所以我没有尝试任何花哨的东西,而是在我的控制台中发送和显示json字符串。

这是我的控制者:

@RequestMapping(value="/create/transaction", method=RequestMethod.POST)
    @ResponseBody
    public String createTran(@RequestBody String json) throws IOException {
        LOGGER.info("Create New Transaction");
        System.out.println("--- Json: " + json);
        ObjectMapper mapper = new ObjectMapper();
        MyTransaction tranValue = mapper.readValue(json, MyTransaction.class);

        MyTransaction tran = MyTransaction.getInstance();
        tran.setName(tranValue.getName());
        tran.setAmount(tranValue.getAmount());


        return toJson(tran);

    }


    private String toJson(MyTransaction tran) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String value = mapper.writeValueAsString(tran);
            LOGGER.info("---- Value: " + value);
            return value;
        } catch(JsonProcessingException e) {
            LOGGER.debug("----- Fail");
            e.printStackTrace();
            return null;
        }
    }

我的表格:

<form id="c-t-form" method="post"    action="${pageContext.request.contextPath}/create/transaction">
<div class="modal-form">
    <h3>Create New Transaction</h3>
    <table class="table-form">
        <tr>
            <td class="c-50">
                <label for="c-t-t">Title</label>
                <span id="c-t-t-error" class="c-t-t-error error">Please enter the budget title.</span>
                <div class="input-txt">
                    <input id="c-t-t" class="txt" type="text" name="name"/>
                </div>
            </td>
            <td class="c-10">
                <label for="c-t-a">Amount</label>
                <span id="c-t-a-error" class="c-t-a-error error">Please enter correct budget amount.</span>
                <div class="input-txt">
                    <input id="c-t-a" class="txt" type="text" name="amount"/>
                </div>
            </td>

        </tr>
        <tr>
            <td>
                <div>
                    <input class="submit-btn acc-btn" name="t-b" type="submit" value="Save" />
                </div>
            </td>
        </tr>
    </table>
</div>
</form>

这是我的ajax脚本:

$(document).ready(function() {
    $("#c-t-form").submit(function(event) {
        var tranName = $('#c-t-t').val();
        var amount = $('#c-t-a').val();

        var data = {"name" : tranName,"amount" : amount};
        $.ajax({
            url: $('#c-t-form').attr('action'),
            data: JSON.stringify(data),
            type: "POST",
            cache: false,
            beforeSend:function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },

            success: function(reponse) {
                alert("success");
            },
            error: function(xhr, status, error) {
                alert(status);
            }
        });
        return true;
    });
});

我已经多次查看代码但在我的实现中找不到错误。这是我得到的错误

SEVERE: Servlet.service() for servlet [spring] in context with path [/budgetme] threw exception
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN
 at [Source: name=asda&amount=12&t-d=&t-b=Save; line: 1, column: 5]

我的模特:

class MyTransaction {
   private int id;
   private String name;
   private String details;
   private Bigdecimal amount;

   // getters and setters
}

任何提示都会有所帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

当你希望spring直接处理你的json对象时,会使用@RequestBody和@ResponseBody。 在您的情况下,您提交的是JSON对象,但函数参数是String。

您的功能应如下所示:

@RequestMapping(value="/create/transaction", method=RequestMethod.POST)
@ResponseBody
public MyTransaction createTran(@RequestBody MyTransaction json) throws IOException {

    ...
    MyTransaction tran = MyTransaction.getInstance();
    ...
    return tran;
}

无需自己处理ObjectMapper。

你可以在这里看到一个例子: http://spring.io/guides/gs/rest-service/

在本教程中,他们使用@RestController而不是@Controller。 RestController在每个函数上假设@ResponseBody。

Spring doc:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody

此致