首先要加入三个JAR包:
其次在Controller中:
<span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cgf.springmvc.crud.dao.EmployeeDao; import com.cgf.springmvc.crud.entities.Employee; @RequestMapping(value="/springmvc") @Controller public class MyJson { @Autowired private EmployeeDao employeeDao; <span style="color:#ff0000;">@ResponseBody</span> @RequestMapping(value="/testJSON") public Collection<Employee> testJson(){ return employeeDao.getAll(); } }</span>
在index.jsp中:
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(function(){ $("#test_json").click(function(){ var url=this.href; var args={}; $.post(url,args,function(data){ for(var i=0;i<data.length;i++){ var id=data[i].id; var lastName=data[i].lastName; alert(id+"---"+lastName); } }); return false; }); }) </script>
<h2>SpringMVC JSON</h2> <a href="springmvc/testJSON" id="test_json">Test Json</a><br>
时间: 2024-09-28 03:14:29