springMVC_04 Ajax请求 @RequestBody,@ResponseBody 处理JSON格式
springMVC处理Ajax请求,返回JSON格式数据
加入对jackson的依赖,springMVC使用jackson进行JSON数据转换
<!-- json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.10</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.10</version> </dependency>
Controller
package com.gc.springmvc.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.gc.springmvc.model.User; @Controller public class AjaxController { @RequestMapping(value="listUser") public @ResponseBody List<User> listUser() throws Exception { List<User> users = new ArrayList<User>(); users.add(new User("张三2", "zs")); users.add(new User("李四", "ls")); return users; } }
页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div> <div> <a href="javascript:void(0)" onclick="sendAjaxReq()">Ajax请求,返回JSON数据</a> </div> <div id="users" style="margin-left:50%;font-weight:bold;color:red"></div> </div> <!-- Ajax --> <script type="text/javascript"> function createAjaxObj() { var req; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else { req = new ActiveXObject("Msxml2.XMLHTTP"); //ie } return req; } function sendAjaxReq() { var req = createAjaxObj(); req.open("get", "listUser?name=王五&time="+Math.random()); req.setRequestHeader("accept", "application/json"); req.onreadystatechange = function() { if(req.readyState=4 && req.status==200) { var result = eval("(" + req.responseText +")"); var divNode = document.getElementById("users"); divNode.innerHTML = ""; for(var index in result) { var name = result[index].name; if(index>0) { name = "<br/>" + name; } divNode.innerHTML += name; } } } req.send(null); } </script> </body> </html>
JSP页面中访问服务器上的静态资源,如js脚本文件
必须配置resource资源,否则按请求一个Controller进行映射处理,导致无法下载
<!-- 配置对静态资源文件的访问不被拦截,如js脚本--> <mvc:resources location="/script/" mapping="/script/**"/>
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05