Java Novice Learning Guide [day37]---SpringMVC Advanced&JSON

1、Hello JSON

  • In actual development, it is usually necessary to exchange data with other systems. The format of data exchange usually includes XML and JSON;
  • JSON (JavaScript Object Notation: JavaScript Object Notation) is a lightweight data exchange format open based on JavaScript grammar, using js grammar to describe data objects;
  • JSON is a lightweight data format. Compared with XML, JSON has smaller documents, clear and concise structure, and higher reading and writing efficiency.

2. How does SpringMVC return JSON format data

Dynamic web project---->Set up SpringMVC environment (Spring-mvc.xml file configuration)---->Import JSON jar package---->Annotate @ResponseBody on the return value---->Will not go View resolver, directly transfer data to the foreground

1. Date object return format

When returning the time and date to the browser, the format is a timestamp, and what we want is a date string that specifies the rules, so when transferring from the background to the foreground, you need to add a formatting tag to the getter property of the date@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

; When transferring from the foreground to the background, an annotation needs to be added to the setter method@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")

4. Realize file upload

1. Preparation

  • The form must be a post request, and large data needs to be transmitted
  • enctype = multipart/form-dataw3cSchoole-html-form form enctype attribute value lookup
<%@ 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>
	<!-- enctype="multipart/form-data":告诉浏览器表单中有复杂表单项 -->
	<form action="/file/upload" method="post" enctype="multipart/form-data">
	 	<h2>演示头像上传</h2>
	 	用户:<input name="name" value="name"/> <br/> <br/><!-- 普通表单项 -->
	 	头像:<input type="file" name="photo"/><br/> <br/><!-- 复杂表单项 -->
	 	<input type="submit" value="提交"/>
	</form>
</body>
</html>

2. Background code

  • To import the jar com.springsource.org.apache.commons.photo-1.2.0.jar

    com.springsource.org.apache.commons.io-1.4.0.jar

  • Configure Spring-mvc.xml file parser

<!-- 配置文件上传解析器:将表单中的复杂表单项解析成一个MultipartFile对象 -->
<bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件的最大尺寸为1MB -->
		<property name="maxUploadSize">
			<value>#{1024*1024}</value>
		</property>
</bean>
  • Code behind
/**
 * @author wang
 *获取前台传输的文件,下载到本地
 *下列可能出现的问题
 *①用户如果没有上传文件
  ②获取服务器所在磁盘真实路劲保存文件
  ③服务器上传文件路劲不存在
  ④文件名重复
 */
@Controller
@RequestMapping("/file")
public class LoadController {
    
    
	@RequestMapping("/upload")
	public void uploadFile(MultipartFile photo,String name,HttpServletRequest req) throws IOException{
    
    
		System.out.println(name);
		System.out.println(photo);//图片已经放进对象里面了,现在要在本地进行获取
		
		// 0.上传表单信息:注意MultipartFile对象的名称必须与上传表单项的name属性值一致
		System.out.println("上传文件是否为空:" + photo.isEmpty());
		System.out.println("上传文件的大小(字节):" + photo.getSize());
		System.out.println("上传文件的类型:" + photo.getContentType());
		System.out.println("上传表单name属性值:" + photo.getName());
		String filename = photo.getOriginalFilename();//上传的文件名
		System.out.println("上传文件名:" + photo.getOriginalFilename());
		//获取文件真是路径
		String realPath = req.getServletContext().getRealPath("/img");
		File parent = new File(realPath);
		//判断文件夹不存在
		if (!parent.exists()) {
    
    //文件夹不存在,需要创建文件夹
			parent.mkdirs();
		}
		//解决文件名重复的情况,使用随机数
		filename = UUID.randomUUID().toString().replaceAll("-", "")+"_"+filename;
		//如果存在,就输出
		File file = new File(parent, filename);
		// 1、先获取输入流
		InputStream in = photo.getInputStream();
		// 2、获取输出流
		FileOutputStream ou = new FileOutputStream(file);
		// 3、边读边保存(可以用到IOUtil工具)
		IOUtils.copy(in, ou);
		// 关流
		ou.close();
		in.close();
	}

5. File download

1. Preparation

<%@page import="java.net.URLEncoder"%>
<%@ 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>
	<ul>
		<h1>文件下载</h1><br/>
		<li><a href="file/download?name=1.jpg">1.jpg</a></li>
		<!-- 处理IE浏览器不能够显示中文 -->
		<li><a href="file/download?name=<%=URLEncoder.encode("嘿嘿.jpg", "UTF-8") %>">嘿嘿.jpg</a></li>
		<li><a href="file/download?name=abc.mp4">abc.mp4</a></li>
		<li><a href="file/download?name=<%=URLEncoder.encode("嘿嘿.7z", "UTF-8") %>">嘿嘿.7z</a></li>
	</ul>
</body>
</html>

2. Background code implementation

@Controller
@RequestMapping("/file")
public class LoadController {
    
    
//文件下载
	@RequestMapping("/download")
	public void downloadFile(String name ,HttpServletRequest req , HttpServletResponse resp) 
			throws IOException{
    
    //这里的名字要和xml里面的保持一致
		System.out.println(name);
		//找寻文件在服务器的绝对路径
		String path = req.getServletContext().getRealPath("/img")+"/"+name;
		//1、先获取输入流
		FileInputStream in = new FileInputStream(path);
//-----------------响应,对浏览器进行判断区分-------------------------------------------------------------	
		//在找到文件后,进行转码
		//转码的方式获取默认编码是ISO-8859-1后台代码utf-8
		//name = new String(name.getBytes("UTF-8"),"ISO-8859-1");
		if(req.getHeader("User-Agent").toUpperCase().indexOf("TRIDENT")!=-1){
    
    //IE
			name = URLEncoder.encode(name, "utf-8");
		}else if(req.getHeader("User-Agent").toUpperCase().indexOf("EDGE")!=-1){
    
    //电脑自带edge【edʒ】浏览器	
			name = URLEncoder.encode(name, "utf-8");
		}else{
    
    //其他浏览器
			name = new String(name.getBytes("UTF-8"),"ISO-8859-1");//转码的方式获取默认编码是ISO-8859-1后台代码utf-8
		};
//----------------------------------------------------------------------------------
		//设置相应头,告诉浏览器需要下载,这里是下载的内容
		resp.setHeader("Content-Disposition", "attachment; filename=" + name);
		//2、获取输出流,给客户端,会知晓向哪个客户端进行输出
		ServletOutputStream ou = resp.getOutputStream();
		//3、进行拷贝
		IOUtils.copy(in, ou);
		//关流
		ou.close();
		in.close();
	}
}

6, SpringMVC interceptor

(1) The filter belongs to the web program and is configured in web.xml, which intercepts the request object

(2) The interceptor belongs to SpringMVC and should be configured in Spring-mvc.xml: it intercepts the request method of [controller object]

(3) Create an interceptor

//HandlerInterceptor   处理器 拦截器
public class MyInterceptor implements HandlerInterceptor{
    
    
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {
    
    
		System.out.println("请求完成DispatcherServlet请求响应完成之后执行...可以对资源做一些清理");
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
    
    
		System.out.println("在controller处理器执行之后执行.但在DispatcherServlet向客户端返回响应之前,对reuqest处理");
	}
	//preHandle -- pre【prevoius】 在...之前   post在...之后
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
    
    
		System.out.println("在controller处理器执行之前执行...");
//return false;//阻止了
		return true;//放行
	}
}

Configure the interceptor in spring-mvc.xml

<!-- 配置拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 拦截所有请求   /*拦截一级请求    /**拦截所有请求  -->
			<mvc:mapping path="/**"/>
			<!-- 不拦截哪些请求 -->
			<mvc:exclude-mapping path="/upload"/>
			<mvc:exclude-mapping path="/download"/>
			<bean class="cn.xxxx.interceptor.MyInterceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>

7. SpringMVC execution process [interview questions]

image-20201209110635293

  1. Send request to DispatcherServlet

  2. Find the mapper manager HandleMapping according to the xml annotation and return to the execution chain

  3. HandleAdapter data validation process data

  4. Controller execution method processing encapsulated into ModelAndView

  5. The view resolver parses the ViewResolver parses the response response

Guess you like

Origin blog.csdn.net/WLK0423/article/details/111060583