简体   繁体   中英

How to get the POST request parameters of a jQuery $.post from a spring mvc controller?

I need to load data from database dynamically on the page, without any page reload.

My code in JSP is like this:

<script>
$(document).ready(function() {
    $("#ClassNext").click(function(event){
        var data = {};
        var classArray = [];
        $.each($("input[name='classCheckbox']:checked"), function(){            
            classArray.push($(this).val());
        });
        console.log(classArray);
        data["list"] = classArray;
        data["var"] = "1";
        console.log(data);
        $.post('PopulateClassSample',data,function(responseJson){
            if(responseJson!=null){
                $.each(responseJson,function(key,value){
                    // do something
                })
            }
        })
    })
});
<script>
<c:forEach items="${classList}" var="Class">     
    <li>
        <input class="classCheckbox" type="checkbox" name="classCheckbox" value="${Class.classStart}"></input>
        <c:out value="${Class.showString}"/>
        <button style="display: none;" id="${Class.classStart}">Edit</button>
    </li>
</c:forEach>

<button id="ClassNext">Next</button>

Here I am posting a request to extract some information from the database through jQuery POST ($.post). I am expecting the response as a JSON object which contains the information from the database. The data variable is an object of two fields- one field contains an array of Strings, the other field contains a String. This data variable gets its required values correctly through javascript.

The method that catches this request in a controller:

@RequestMapping(value="/PopulateClassSample", method = RequestMethod.POST)
    @ResponseBody
    protected void SendResponse(@RequestParam("list") ArrayList<String> list, @RequestParam("start") String start, HttpServletResponse response) throws IOException
    {
        for(String s:list){
            System.out.println(s);

        }
        System.out.println(start);
        /*

        ArrayList<AcademicClass> classList = new ArrayList<AcademicClass>();
        DataAccess db = new DataAccess();
        classList = db.getClassList();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(classList,new TypeToken<List<AcademicClass>>() {}.getType());
        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
        */
    }

Inside the DataAccess class, I am doing all the database query and returning the result through its methods. I need HttpServletResponse object here, because I will return something to the jQuery code as a JSON object. But I am getting errors like this in console:

jquery.min.js:4 POST http://localhost:8080/Mytuition/PopulateClassSample 400 ()

And the initial prints in the controller method doesn't gets executed.

I tried declaring a separate model class (which has two fields- an ArrayList of Strings and a String) and used the @ModelAttribute annotation. But then I get exceptions like this:

java.lang.NumberFormatException: For input string: ""

Is there any way to do it without @ModelAttribute annotation? And why isn't this working even if I am using the @ModelAttribute annotation?

Note: I will definitely return something to the JSP. That part is commented out only for testing purpose.

Your controller method its wrong. If you are doing an Ajax call to the server and need to retrieve the JSON response from the server you only need to do 2 things.

  1. Define your method in the controller with @ResponseBody. Then Spring will translate your returning object to JSON format

  2. Return some object to the view. You are returning "void"

Should be something like this

@RequestMapping(value="/PopulateClassSample", method = RequestMethod.POST)
    @ResponseBody
    protected List<AcademicClass> SendResponse(@RequestParam("list") ArrayList<String> list, @RequestParam("start") String start) throws IOException
    {
        /** DO your staff here and return the AcademicClass list */
        System.out.println(start);
        DataAccess db = new DataAccess();
        return db.getClassList();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM