How to return an object from a Spring MVC controller in response to AJAX request?

前端 未结 4 934
醉酒成梦
醉酒成梦 2020-11-30 08:13

I have to return a list of employees from a controller in response to jQuery AJAX request. How should I do for it?

My controller:



        
相关标签:
4条回答
  • 2020-11-30 08:35

    The ModelAndView implies you plan to render a view, which you don't. To just return the object, use the @ResponseBody annotation:

    @RequestMapping("phcheck")
    public @ResponseBody List<Employee> pay(@RequestParam("empid") int empid, String fdate, String tdate) {
       return entityManager.createQuery("select e from Employee e where e.empId="+empid, Employee.class).getResultList();
    }
    

    Also, you should be more careful about how you handle queries. Your query is insecure and would allow sql injection. For example, if someone called your method with empId = "'15' or '1'='1'", then it would return the entire list of employees.

    0 讨论(0)
  • 2020-11-30 08:44
    @RequestMapping(value = "phcheck", produces = "application/json")
    @ResponseBody
    public ModelAndView pay(@RequestParam("empid") int empid, @RequestParam("fdate") String fdate, @RequestParam("tdate") String tdate) {
    
       return entityManager.createQuery("select e from Employee e where e.empId="+empid, Employee.class).getResultList();
    }
    
    
    url:"phcheck.htm?empid="+$("#empid").val()+"&fdate="+$("#fdate").val()+"&tdate="+$("#tdate").val()
    

    In Spring MVC you will have to have registered MappingJackson2HttpMessageConverter like being done here

    0 讨论(0)
  • 2020-11-30 08:47

    I need this list of employee in ajax

    In spring when you need object serialization, de-serialization and message conversion. in that case you need to annotate your controller handler method with @RequestBody and @ResponseBody.

    Where:

    • @ResponseBody : will inform spring that try to convert its return value and write it to the http response automatically.
    • @RequestBody : will inform spring that try to convert the content of the incoming request body to your parameter object on the fly.

    in your case you need JSON type, you have to add @ResponseBody to your method signature or just above the method, and produces and consumes which are optional, like:

    @RequestMapping(value="phcheck", method=RequestMethod.GET
                    produces="application/json")
    public @ResponseBody List<Employee> pay(@RequestParam("empid") int empid, String fdate, String tdate) {
    
      //get your employee list here
      return empList;
    }
    

    and in AJAX call use:

    • contentType: 'application/json' attribute tells the type of data you're sending. and
    • dataType: json attribute tells jquery what content type of response will receive.

    in your case contentType: 'application/json' is not needed, default one i.e. 'application/x-www-form-urlencoded; charset=UTF-8' is enough.

    and you can receive list of employees in your AJAX success, to iterate over it do like:

      success: function (data) {
              $.each(data, function(index, currEmp) {
                 console.log(currEmp.name); //to print name of employee
             });    
            },
    


    Note: Jackson mapper or any other mapper should be available on buildpath in order to work JSON serialize and deserialize.

    See Also:

    • New features in spring mvc 3.1
    0 讨论(0)
  • 2020-11-30 08:53

    Make the method as @ResponseBody Type in the controller and in the ajax take the List from success function.

    Put the Jackson Mapper file in Pom.xml file if using Maven

    0 讨论(0)
提交回复
热议问题