【问题标题】:How to print spring controller response in tabular formate如何以表格格式打印弹簧控制器响应
【发布时间】:2015-10-18 14:15:26
【问题描述】:

我正在向 spring 控制器发送 ajax 请求并获取数组列表。 如何获取 ArrayList 到 ajax 结果并以表格格式打印。当我在 ajax 中打印警报(数据)时,它显示所有 html 页面,任何人都可以建议我如何解决这个问题,`

<div>
    <input type="text" id="searchtext">
    <input type="button" id="verifybtn" value="search" "> 

</div>

<table class="table">
        <tr>
        <th>Application ID</th>
        <th>Application Type</th>
        <th>Customer ID</th>
        <th>Remarks<th>
        </tr>
    <tr>
            <c:forEach var="list4" items="">

            </c:forEach>
    </tr>
    </table>

这是我的ajax`

$("#verifybtn").click(function(){

    var s =  $("#searchtext").val();
    //alert(s);
    $.ajax({
            url:"${pageContext.request.contextPath}/officer/search.html",
            type:"GET",
            data:{searchtext:s},
            dataType:"html",
            success:function(data){
                alert("data is"+data),
                $("result").html(data);
            }   
    })

})

`控制器

@RequestMapping(value="/search")
public String search(@RequestParam("searchtext") String strtosearch,HttpSession hs,Model m)
{


    ArrayList<Application> all=(ArrayList<Application>)service.searchbyApplicationID(strtosearch);
    return "Home";
}

【问题讨论】:

标签: ajax spring spring-mvc spring-data spring-aop


【解决方案1】:

我强烈建议你在这里阅读这个详细的答案JQuery, Spring MVC @RequestBody and JSON - making it work together

您应该在控制器方法中使用注解@ResponseBody,以便它返回JSON 字符串而不是html。此外,您需要使用 Jackson 或 gson 等库将您的数组列表转换为 JSON。但是如果你的类路径中有Jackson(并且有一个&lt;mvc:annotation-driven&gt; 设置),Spring 会将返回的对象序列化为JSON(如果你添加了@ResponseBody 注释)。所以浏览器/客户端会看到这个 JSON 结果。

@RequestMapping(value="/search")
@ResponseBody
public String search(@RequestParam("searchtext") String strtosearch,HttpSession hs,Model m)
{

    ArrayList<Application> all=(ArrayList<Application>)service.searchbyApplicationID(strtosearch);

// Convert ArrayList to JSON 

//  return jsonString;
}

JAVA对象转JSON的详细教程可以看here

获得响应后,您无法直接将 json 添加到您的 html 页面。 JSON 对象不是 html。

【讨论】:

    【解决方案2】:

    在您的控制器中,您应该返回您的 ArrayList。

    控制器:

    @RequestMapping(value="/search")
    @ResponseBody
    public ArrayList search(@RequestParam("searchtext") String strtosearch,HttpSession hs,Model m)
    {
    ArrayList<Application> all=(ArrayList<Application>)service.searchbyApplicationID(strtosearch);
    return all;
    }
    

    然后你可以在你的 ajax 中访问 ArrayList

    success:function(responseData){
    var entity_obj = responseData.responseJSON;
    $.each(entity_obj,
        function(key, val) {
        console.log(val);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多