【SpringMVC】SpringMVC通過Ajax給前端返回JSON


在SpringMVC項目中,使用JS靜態資源,需要對該靜態資源的請求放行。

只需要在springmvc.xml中配置:

    <mvc:default-servlet-handler></mvc:default-servlet-handler>

即啟用了Tomcat默認的處理Servlet,當沒有在@RequestMapping中找到對應的請求路徑時,會直接訪問該路徑的資源。

使用JSON,還需要添加JSON相關的Jar包。jackson-databind.jar、jackson-annotations.jar、jackson-core.jar

使用maven很簡單,添加jackson-databind.jar依賴,會自動下載其余兩個:

pom.xml

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>

 

  • 前端使用Jquery的$.post()
<script src="${pageContext.request.contextPath}/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#testJson").click(function () {
            $.post(
                "handler/testJson",
                function (datas) {
                    for (let i = 0; i < datas.length; i++) {
                        console.log(datas[i].id + "\n");
                    }
                }
            );
        });
    });
</script>
<button id="testJson">testJson</button>
  • 后台使用一個學生類(Student)測試,使用注解@ResponseBody返回的不再時一個視圖,不會被視圖解析器解析為頁面

返回的是一個List,傳統的方式需要再JS中用eval()方法,將返回的數據轉化為JavaScript可以處理的數據遍歷輸出。再SpringMVC中,僅僅返回List,前端就可以正常的遍歷輸出。

    @ResponseBody
    @RequestMapping("testJson")
    public List<Student> testJson() {
        List<Student> students = new ArrayList<Student>();
        Student stu1 = new Student(1, "zs");
        Student stu2 = new Student(2, "ls");
        Student stu3 = new Student(3, "ww");
        students.add(stu1);
        students.add(stu2);
        students.add(stu3);
        return students;
    }

前端輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM