7*4 2015-01-04 02:07 采纳率: 50%
浏览 10

Spring MVC-Ajax响应

I am trying to submit a form to the server using ajax. I have looked into various tutorials but could not figure out my own error. Since I just start learning ajax, so I didn't try anything fancy but send and display the json string in my console.

This is my controller:

@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;
        }
    }

My form:

<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>

and this is my ajax script:

$(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;
    });
});

I have look at the code many time but couldn't find the error in my implementation. This is the error that I am getting

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]

My Model:

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

   // getters and setters
}

Any hints would help. Thank you.

  • 写回答

1条回答 默认 最新

  • weixin_33699914 2015-01-04 18:48
    关注

    @RequestBody and @ResponseBody are used when you want spring to deal with your json object directly. In your case, you are submitting a JSON object but the function parameter is a String.

    Your function should look like :

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

    No need to deal with the ObjectMapper yourself.

    You can see an example here : http://spring.io/guides/gs/rest-service/

    In this tutorial, they are using @RestController instead of @Controller. RestController assume @ResponseBody on every function.

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

    Regards

    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line