一、处理JSON
JSON知识:
JSON 有两种格式:
① Json 对象:{key:value,key:value….},②Json数组:[value1, value2…]
Json 对象解析方式: 对象.key; Json 数组的解析方式:for循环遍历
java对象转Json: ① Bean 和 map —》Json 对象;② List —》 json数组
1、 返回JSON
加入 jar 包:
下载地址:地址
注意: 请根据自己的Spring版本下载最新的jar,否则有肯能会报错。
报错异常可以参考这篇博客:解决方案
SpringMVC处理json四个条件
① 导入jackson的jar
② 在springMVC的配置文件中开启MVC驱动,
<mvc:annotation-driven />
注意:
③ 在处理ajax请求的方法上加上注解@ResponseBody
④ 将要转换为json且响应到客户端的数据,直接作为该方法的返回值返回
代码演示:
index:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>测试json</title>
<script type="text/javascript" src="${request.servletContext.contextPath}/test01_json/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="<c:url value='/test01_json/jquery-1.6.4.min.js'/>"></script>
</head>
<body>
request.servletContext.contextPath= ${pageContext.request.servletContext.contextPath}<br/>
request.contextPath= ${pageContext.request.contextPath}<br/>
<input type="button" value="响应是Json" onclick="getJson();"/><br/>
<script type="text/javascript">
function getJson(){
$.ajax({
data:"sid=1", /*请求参数*/
type:"POST", /*请求方式*/
dataType:"json",/*期待服务器端的响应数据的格式*/
url:"<c:url value='/test01/jsonMethod1.action'/>",/*请求的url*/
async:true,/*是否异步*/
success:function(data){/*成功回调函数*/
alert(data.sid+":"+data.sname+":"+data.score+":"+data.sex);
}
});
}
</script>
<input type="button" value="请求是Json" onclick="sendJson1();"/><br/>
<script type="text/javascript">
function sendJson1(){
var studentJson='{"sid":101,"sname":"韩梅梅","sex":"女","score":12.5}';
$.ajax({
data:studentJson, /*请求参数*/
contentType: "application/json;charset=UTF-8",
type:"POST", /*请求方式*/
dataType:"text",/*期待服务器端的响应数据的格式*/
url:"<c:url value='/test01/jsonMethod2.action'/>",/*请求的url*/
async:true,/*是否异步*/
success:function(data){/*成功回调函数*/
alert(data);
}
});
}
</script>
<input type="button" value="请求是Json" onclick="sendJson2();"/><br/>
<script type="text/javascript">
function sendJson2(){
var studentJson='{"sid":102,"sname":"韩梅梅","sex":"女","score":12.5}';
//alert(studentJson);
//alert(studentJson.sid+"::"+studentJson.sname);
$.ajax({
data:studentJson, /*请求参数*/
contentType: "application/json;charset=UTF-8",
type:"POST", /*请求方式*/
dataType:"text",/*期待服务器端的响应数据的格式*/
url:"<c:url value='/test01/jsonMethod3.action'/>",/*请求的url*/
async:true,/*是否异步*/
success:function(data){/*成功回调函数*/
alert(data);
}
});
}
</script>
<input type="button" value="请求和响应都是Json" onclick="sendAndGetJson();"/><br/>
<script type="text/javascript">
function sendAndGetJson(){
var studentJson='{"sid":102,"sname":"韩梅梅","sex":"女","score":12.5}';
$.ajax({
data:studentJson, /*请求参数*/
contentType: "application/json;charset=UTF-8",
type:"POST", /*请求方式*/
dataType:"json",/*期待服务器端的响应数据的格式*/
url:"<c:url value='/test01/jsonMethod4.action'/>",/*请求的url*/
async:true,/*是否异步*/
success:function(data){/*成功回调函数*/
alert(data);
alert(data.sid+":"+data.sname+":"+data.score+":"+data.sex);
}
});
}
</script>
<input type="button" value="响应是Json--map" onclick="getJson5();"/><br/>
<script type="text/javascript">
function getJson5(){
$.ajax({
data:null, /*请求参数*/
type:"POST", /*请求方式*/
dataType:"json",/*期待服务器端的响应数据的格式*/
url:"<c:url value='/test01/jsonMethod5.action'/>",/*请求的url*/
async:true,/*是否异步*/
success:function(data){/*成功回调函数*/
alert(data);
alert(data.count);
}
});
}
</script>
controller:
@Controller
@RequestMapping("/test1")
public class JsonController {
@RequestMapping("/method1.action")
@ResponseBody//把相应的java对象转换成json返回给前端
public Student method1(int sid){
System.out.println("sid"+sid);
Student student = new Student("小脑斧",1,"男",92f);
return student;
}
@RequestMapping("/jsonMethod2.action")
//@ResponseBody
public void jsonMethod02(@RequestBody Student s,HttpServletResponse res) throws Exception{
//@RequestBody用对象Student接受请求的json对象
System.out.println(s);
res.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
res.getWriter().print("success1");
}
@RequestMapping("/jsonMethod3.action")
@ResponseBody//响应的是字符串
public String jsonMethod03(@RequestBody Student s) throws Exception{
//@RequestBody用对象Student接受请求的json对象
System.out.println(s);
return "success2";
}
@RequestMapping("/jsonMethod4.action")
@ResponseBody//响应的是字符串
public Student jsonMethod04(@RequestBody Student s) throws Exception{
//@RequestBody用对象Student接受请求的json对象
System.out.println(s);
Student ss=new Student("韩梅2", 22, "男", 22.5f);
return ss;
}
@RequestMapping("/jsonMethod5.action")
@ResponseBody//指定响应是json:::把响应的java对象转换为json串
public Map<String, Object> jsonMethod05() {
Map<String, Object> map=new HashMap<String, Object>();
map.put("count", 11);
return map;
}
}
文件上传:
导入jar包:
在springmvc的核心装配文件中配置:
创建jsp::post提交+设置enctype+file
创建action:通过multipartfile来接受file域
MultipartFile的方法:
创建action:
@RequestMapping(value = "/up" ,method = RequestMethod.POST)
public String up (String desc, MultipartFile uploadFile, HttpSession session) throws IOException {
// 获取上传文件的名称
String filename = uploadFile.getOriginalFilename();
String path = session.getServletContext().getRealPath("phone") + File.separator + filename;
// 获取输入流
InputStream is = uploadFile.getInputStream();
// 获取输出流
File file = new File(path);
OutputStream fos = new FileOutputStream(file);
byte[] bt = new byte[1024];
int len;
while((len = is.read(bt)) != -1){
fos.write(bt, 0, len);
}
is.close();
fos.close();
return "success";
}
@RequestMapping(value = "/up",method = RequestMethod.POST)
public String up (MultipartFile uploadFile, HttpSession session) throws IOException {
// 获取上传文件的名称
String filename = uploadFile.getOriginalFilename();
String finalFileName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
String path = session.getServletContext().getRealPath("phone") + File.separator + finalFileName;
File file = new File(path);
uploadFile.transferTo(file);
return "success";
}
在web.xml中设置初始化参数 指定文件保存的路径
文件下载:
Jsp:
Web.xml:
Action:
@RequestMapping(value = "/down")
public ResponseEntity<byte[]> down(HttpSession session) throws Exception {
// 获取下载文件的路径
String realPath = session.getServletContext().getRealPath("img");
String finalPath = realPath + File.separator + "2.jpg";
InputStream is = new FileInputStream(finalPath);
// available():获取输入流所读取的文件的最大字节数
byte[] bt = new byte[is.available()];
is.read(bt);
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename=zzz.jpg");//这里可以动态加文件名字
// 设置响应状态
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<>(bt, headers, status);
return entity;
}
拦截器
1、 自定义拦截器
Spring MVC 也可以使用拦截器对请求进行拦截处理,用户可以自定义拦截器来实现特定的 功 能 , 自 定 义 的 拦 截 器 可 以 实 现 HandlerInterceptor 接 口 , 也 可 以 继 承 HandlerInterceptorAdapter 适配器类 。
preHandle():这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求request 进行处理。如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器,或者是业务处理器去进行处理,则返回 true;如果程序员决定不需要再调用其他的组件去处理请求,则返回 false。
postHandle(): 这个方法在业务处理器处理完请求后,但是 DispatcherServlet 向客户端返回响应前被调用,在该方法中对用户请求 request 进行处理。
afterCompletion():这个方法在 DispatcherServlet 完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作。
`
配置拦截器:
过滤器和拦截器的区别
相同之处: 基本功能相似
都可以对指定的请求进行拦截 进行预处理、权限管理、日志记录等操作
都是aop编程思想的体现
不同之处:1 实现接口不同
过滤器Filter实现接口:javax.servlet.Filter接口
拦截器Interceptor实现接口:org.springframework.web.servlet.HanderInteceptor接口
2 是否依赖web容器
Filter是servlet规范 需要web应用服务器解析
Interceptor由spring容器支持 不依赖web容器
3 实现原理不同
Filter是函数回调
Interceptor是反射和动态代理
4 适用的项目不同
Filter只使用于web项目
Interceptor使用于所有项目中
其他总结: