– JSON
-
In the actual development, it is usually necessary to exchange data with other systems, and the format of data exchange usually includes XML and JSON.
-
XML: Is an extended markup language that allows us to exchange data with other systems, but it has obvious drawbacks
-
XML file format Large files have complex formats and occupy bandwidth for transmission
-
Parsing XML takes a lot of code on both the server and client sides, however complex and difficult to maintain the server and client code becomes
-
Different browsers on the client side parse XML differently, requiring a lot of repetitive code
-
Parsing XML on both the server and client sides takes resources and time
-
-
XML represents one object and multiple objects
<! XML represents an object -->
<user>
<username>Zhang SAN</username>
<age>16</age>
<sex>true</sex>
<dept>
<id>001</id>
<name>Development department</name>
</dept>
</user>
<! -- XML represents multiple objects -->
<users>
<username>Zhang SAN</username>
<age>16</age>
<sex>true</sex>
<dept>
<id>001</id>
<name>Development department</name>
</dept>
<username>Li si</username>
<age>26</age>
<sex>false</sex>
<dept>
<id>003</id>
<name>The test of</name>
</dept>
<username>Cathy</username>
<age>36</age>
<sex>true</sex>
<dept>
<id>002</id>
<name>Operations department</name>
</dept>
</users>
Copy the code
-
JSON: A lightweight data interchange format that is open based on JavaScript syntax and uses THE JS syntax to describe data objects
- JSON is a lightweight data format. Compared with XML, JSON documents are smaller, simpler, and more efficient to read and write
-
JSON data format:
- One object: {“key1″:”value1″,”key2”:”value2″… }
- Multiple objects: [{” key1 “:” value1 “, “key2”, “value2″…}, {” key1 “:” value1 “, “key2”, “value2″…}, {” key1 “:” value1 “, “key2” : “value2″…}]
Note: The JSON data format is in the form of “key”:value. The key must be wrapped in “”, and if the value is a string, it must also be wrapped in “”. If it is not a string, it can be written normally
- JSON represents one object and multiple objects
JSON represents an object: {"username":"Zhang"."age":16."sex":true."dept": {"id":001."name":Development department}} After formatting: {"username":"Zhang"."age":16."sex":true."dept": {"id":001."name":Development department}} JSON represents multiple objects: [{"username":"Zhang"."age":16."sex":true."dept": {"id":001."name":Development department}},
{"username":"Bill"."age":26."sex":false."dept": {"id":003."name":"Testing department"}},
{"username":"Fifty"."age":36."sex":true."dept": {"id":002."name":Operation and Maintenance Department}}]Copy the code
– SpringMVC returns JSON
- If you want to convert Java objects to JSON, you need third-party support:
-
Jackson:jackson.codehaus.org/
-
JSON-lib:json-lib.sourceforge.net/
-
Gson:code.google.com/p/google-gs…
-
FastJson Ali open source
-
– SpringMVC Returns JSON Mode 1: Manual stitching
/** * springMVC response JSON data format 1: manual concatenation via HttpServletResponse, this raw method does not require the import of third-party JSONjar package *@param resop
* @throws Exception
*/
@RequestMapping("/01")
public void getJson(HttpServletResponse resop) throws Exception{
// Tell the browser how to parse my data and specify the encoding character set
resop.setContentType("application/json; charset=utf-8");
// Get the print output stream
PrintWriter writer = resop.getWriter();
// Set the printed string, manually concatenate the JSON string
writer.write("{\" name \ ": \" zhang SAN \ ", \ "age \" : 18}");
}
Copy the code
– SpringMVC Returns JSON. Method 2: Returns an object using an annotation
- Convert a Java object to JSON data using the @responseBody annotation
- Add the Jackson Toolkit
/** * springMVC responds to JSON data format two: pass@ResponseBodyComment the way to respond to the object *@return* /
@RequestMapping("/02")
// Return the returned data to the browser in JSON format, but be aware that you need to import the JSONjar package
@ResponseBody
public User getUser(a) {
return new User("Two pockmarks of Wang.".17L.true.new Date());
}
/** * springMVC responds to JSON data format three: pass@ResponseBodyAnnotated returns multiple objects *@return* /
@RequestMapping("/03")
// Return the returned data to the browser in JSON format, but be aware that you need to import the JSONjar package
@ResponseBody
public List<User> getUser2(a) {
return Arrays.asList(new User("Two pockmarks of Wang.".17L.true.new Date()),
new User("King's Three Code pieces".17L.true.new Date()),
new User("Wang Sima Zi".17L.true.new Date()));
}
/** * springMVC responds to JSON data format four: pass@ResponseBodyAnnotated returns Map *@return* /
@RequestMapping("/04")
// Return the returned data to the browser in JSON format, but be aware that you need to import the JSONjar package
@ResponseBody
public HashMap<String, String> getUser3(a) {
HashMap<String,String> hashMap = new HashMap<String,String>();
hashMap.put("name"."Bill");
hashMap.put("age"."18");
return hashMap;
}
Copy the code
– Special processing of date format in Json
-
In the return object, if there is a time field, the browser displays the timestamp by default, so we need to format it
-
From the backstage to the front:
-
On the date GET property field, add a formatted annotation
-
import com.fasterxml.jackson.annotation.JsonFormat;
-
@JsonFormat(pattern=”yyyy-MM-dd HH:mm:ss”,timezone=”GMT+8″)
-
-
From the front to the back
- Add a formatted annotation to the date set attribute field or to the attribute
- @DateTimeFormat(pattern=”yyyy-MM-dd HH:mm:ss”)
-
Note:
- 406 status exception: Jar package is missing. Add Jackson jar package.
- When you use the @responseBody annotation, it doesn’t go through the view parser, which means if you don’t want to return a page or if you want to return JSON data you have to put this annotation;
- If you test in IE, the file download window will pop up. You can add the following configuration to the MVC :annotation-driven of spring-mVC. XML:
<! Enable spring support for MVC -->
<mvc:annotation-driven>
<! -- Avoid downloading files when returning JSON in IE browser -->
<mvc:message-converters>
<bean id= "mappingJackson2HttpMessageConverter"
class= "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name= "supportedMediaTypes" >
<list>
<value>text/html; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Copy the code
– SpringMVC file upload
-
File upload: The local file is copied to the server.
-
File upload in SpringMvc is the encapsulation of native file upload, the purpose is to reduce the amount of code, improve development efficiency;
– Three elements of file upload:
-
The form must be submitted as a POST request (GET request on submitted data)
-
The form must have a file upload item :<input type=”file” name=”headImg”/> The file upload item must have the name attribute and value.
-
The encType attribute of the form must have a value of multipart/form-data
– Procedure for uploading files
– Step 1: Write a file upload page
<form action= "/upload2" method= "post" enctype= "multipart/form-data" >
username:<input name= "username" type= "text"><br/> <input name="headImg" type= "file"><br/> <! <button> Submit </button> </form>Copy the code
– Step 2: Add the file upload JAR package
- Since SpringMVC does not implement file upload itself, It USES apache.com mons. Fileupload com.springsource.org.apache.commons.fileupload-1.2.0.jar - com.springsource.org.apache.commons.io-1.4.0.jarCopy the code
– Step 3: Configure the file upload parser
- SpringMVC uses MultipartFile to upload files, so we need to configure the MultipartResolver to handle files in the form. If we do not configure the MultipartResolver, we will get the following error:Copy the code
- Configure MultipartResolver: Note that id=” MultipartResolver “is invalid
<! -- Config file upload resolver -->
<! -- Notice: id can not be written in the wrong way, must be called this, otherwise upload parser will not work -->
<bean id= "multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<! -- Set maximum upload to 10MB -->
<property name= "maxUploadSize" value= "10485760" />
<! Character set -->
<property name= "defaultEncoding" value= "UTF-8" />
</bean>
Copy the code
– Step 4: The background controller handles the upload
package cn.itsource._02_upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
// Simple version of file upload
@RequestMapping("/upload")
@ResponseBody
public void upload(String username, MultipartFile headImg) throws Exception{
// System.out.println(username);
// System.out.println(headImg);
// // gets the type of the file
// String contentType = headImg.getContentType();
// // gets the name of the file
// String originalFilename = headImg.getOriginalFilename();
// // gets the name of the file in the form.
// String name = headImg.getName();
// // gets the size of the file
// long size = headImg.getSize();
// System.out.println("contentType: " + contentType);
// System.out.println("originalFilename: " + originalFilename);
// System.out.println("name: " + name);
// System.out.println("size: " + size);
// Get the file input stream
InputStream inputStream = headImg.getInputStream();
// Create a file output stream
FileOutputStream outputStream = new FileOutputStream("/Users/colin/Desktop/aaa.png");
// Copy the file to the specified location
IOUtils.copy(inputStream, outputStream);
outputStream.close();
inputStream.close();
}
/** * Full version of file upload * requirements: * 1. The uploaded attachment is saved under webApp * 2. The file name is random * 3. The file suffix is determined by the suffix of the uploaded attachment *@param username
* @param headImg
* @throws Exception
*/
@RequestMapping("/upload2")
@ResponseBody
public void upload2(String username, MultipartFile headImg,HttpServletRequest request) throws Exception{
// Get the attachment name
String originalFilename = headImg.getOriginalFilename();
// Get the attachment type suffix from the tool class
String extension = FilenameUtils.getExtension(originalFilename);
// Get the context object
ServletContext servletContext = request.getServletContext();
// Get the context path /Users/colin/ Eclipse-workspace /springMVC_JSON/webapp
String contextPath = servletContext.getRealPath("/");
String fileName = System.currentTimeMillis() + "." + extension;
// Create a file stream based on the path
File file = new File(contextPath + "upload/" + fileName);
// Check whether there is a parent file path, if not created
if(! file.getParentFile().exists()) { file.getParentFile().mkdirs(); }// Create an output stream based on the specified path
OutputStream OutputStream = new FileOutputStream(file);
// Turn the attachment into an input stream
InputStream inputStream = headImg.getInputStream();
// Copy files to localIOUtils.copy(inputStream,OutputStream); inputStream.close(); OutputStream.close(); }}Copy the code
– SpringMVC file download
- File download: is the server (displayed in the browser) of the resource download (copy) to the local disk;
– The first way:
-
Create a folder download under WebApp and place three different types of files under the folder
-
Create a JSP page and write three hyperlinks
<%@ 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>
<a href="/download/1.zip"> This is an attachment </a><br/> <a href="/download/2.png"< p style = "max-width: 100%; clear: both; min-height: 1em"/download/3.txt"> This is a text document </a> </body> </ HTML >Copy the code
- Through the test, we can find that if only using hyperlinks, the browser can parse pictures, text documents, can be directly opened, and the compressed file browser is for us to download. This is because the browser automatically recognizes whether the file can be opened or not, and then downloads it. This obviously does not meet our file download requirements, so we need to use background code to handle this
– Second way:
- Change the JSP page, because we need the background to handle the download, so we need to pass the name of the file to be downloaded to the background
The < %@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>
<a href="/download? fileName=1.zip"> This is an attachment </a><br/> <a href="/download? fileName=2.png"< p style = "max-width: 100%; clear: both; min-height: 1em"/download? fileName=3.txt"> This is a text document </a><br/> </body> </ HTML >Copy the code
- Create DownloadController class
package cn.itsource.download;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class DownloadController {
@RequestMapping("/download")
@ResponseBody
public void download(HttpServletResponse response,HttpServletRequest request,String fileName) throws Exception {
// Set the request header to tell the browser the name of the file to be downloaded
// attachment: tell the browser to open my attachment as a box
response.setHeader("Content-Disposition"."attachment; filename=" + fileName);
// Get attachments from context objects
ServletContext servletContext = request.getServletContext();
// Obtain the download absolute path from the context object
String realPath = servletContext.getRealPath("/download");
// Get the file stream based on the parent path and the name of the file to download
File file = new File(realPath,fileName);
// Create an input stream for FileInputStream
FileInputStream fileInputStream = new FileInputStream(file);
// Get the output stream through response
ServletOutputStream outputStream = response.getOutputStream();
// Download the core code
IOUtils.copy(fileInputStream, outputStream);
/ / close the flowoutputStream.close(); fileInputStream.close(); }}Copy the code
Note: Setting the request header is key if you want the browser to open our file as a download
– Solve Chinese problems
-
After the above steps, it seems that our download function is complete, but note that if your file name is Chinese, this will happen
-
Change the file name and the name of the download link of the text document. TXT to Chinese. TXT
- Test click Chinese download
- Because our file name is Chinese, the browser can not parse, so it becomes the above appearance, this is the mainstream browser, at this time we look at the Internet Explorer browser
-
You can find that when the file name is Chinese, the common browser file name will be empty or garbled. Internet Explorer will 400, because Internet Explorer thinks your file name just can’t be Chinese, at this time we have to do a compatible Internet Explorer operation, separate the mainstream browser and Internet Explorer from processing
-
JSP page handling
The < %@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>
<a href="/download? fileName=1.zip"> This is an attachment </a><br/> <a href="/download? fileName=2.png"> This is a picture </a><br/> <! <a href= > <a href= > <a href="/download? fileName=<%=URLEncoder.encode("Chinese. TXT","UTF-8") % >"> This is a text document </a><br/> </body> </ HTML >Copy the code
- Background processing
package cn.itsource.download;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class DownloadController {
@RequestMapping("/download")
@ResponseBody
public void download(HttpServletResponse response,HttpServletRequest request,String fileName) throws Exception {
// Get the request header. The value of this attribute can be used to determine the browser. Each browser has a unique identifier
String header = request.getHeader("User-Agent");
// The encoded name
String fileNameEncoder = "";
// Prove Internet Explorer
if(header.toUpperCase().contains("MSIE") || header.toUpperCase().contains("TRIDENT")) {// Encode Chinese
fileNameEncoder = URLEncoder.encode(fileName,"UTF-8");
}else{
// Mainstream browsers
fileNameEncoder = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
}
// Set the name of the file to download - attachments are used to download or upload the file so that the browser does not display the file directly
// attachment: tell the browser to open my attachment as a box
response.setHeader("Content-Disposition"."attachment; filename=" + fileNameEncoder);
// Get attachments from context objects
ServletContext servletContext = request.getServletContext();
// Obtain the download absolute path from the context object
String realPath = servletContext.getRealPath("/download");
// Get the file stream based on the parent path and the name of the file to download
File file = new File(realPath,fileName);
// Create an input stream for FileInputStream
FileInputStream fileInputStream = new FileInputStream(file);
// Get the output stream through response
ServletOutputStream outputStream = response.getOutputStream();
// Download the core code
IOUtils.copy(fileInputStream, outputStream);
/ / close the flowoutputStream.close(); fileInputStream.close(); }}Copy the code
Note: The biggest difference between Microsoft Edge and Internet Explorer is that Edge was introduced by Microsoft after Windows 10. Before Windows 10, Microsoft’s own browser was Internet Explorer.
– SpringMVC interceptor
- On the first day of springMVC, we learned about filters, and springMVC also provided us with an interceptor with similar functionality
– Differences and similarities between interceptors and filters
- The function is the same
- The filter is Tomcat
- The interceptor is SpringMVC
– Procedure
- Create an interceptor class that implements the HandlerInterceptor interface and implements three methods
-
PreHandle: Interceptor core method that is executed before all requests enter the target method and returns true/false, true pass, false intercept
-
PostHandle: Execute after executing the target method and before returning to the page
-
AfterCompletion: Executed after the page has been rendered but before it is displayed
-
package cn.itsource.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
// HandlerInterceptor Interface for the interceptor
public class MyInterceptor implements HandlerInterceptor{
/** * Interceptor core method, which executes before all requests enter target method * return value type: true pass false not pass */
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("Request into interceptor...");
return true;
}
/** * execute */ after executing the target method and before returning to the page
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("Enter method and execute before returning to page...");
}
/** * execute */ after the page is rendered and before the page is displayed
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("The page has been rendered and executed before returning to the page..."); }}Copy the code
- Configure interceptors in spring-mVC.xml
<! -- Configure interceptor -->
<mvc:interceptors>
<mvc:interceptor>
<! -- /* : intercepts all requests, but in springMVC interceptors it only intercepts one level of requests. One level of requests: intercepts: /a/b /b/c /c/v/n /** : Intercepts all requests, but it can intercept multiple levels of paths for example: /a /b /c /a/b /b/c /c/v/n -->
<mvc:mapping path="/ * *"/>
<bean class="cn.itsource.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
– SpringMVC executes the process
- SpringMVC is a frequent interview question, so let’s have a general understanding of its implementation process, the flow chart is as follows:
-
Process Description: Controller is the Handler
-
1. The user sends a request to the server, and the request will be uniformly handed to SpringMVC front-end control DispatcherServlet for processing;
-
2. The DispatcherServlet requests HandlerMapping to find the Handler object (including the controller and the interceptor corresponding to the Handler object) and HandlerExecutionChain object (including: Controller +2 interceptors);
-
3. The DispatcherServlet requests the HandlerAdapter and selects an appropriate HandlerAdapter to process the Handler. (Note: If the HandlerAdapter is successfully obtained, execution of the interceptor’s preHandler(…) begins at this point.) Methods);
-
4. Extract the model data from the request, fill in the Handler input parameter, and run Handler (Controller). Depending on your configuration, Spring will do some extra work for you during the entry process to populate the Handler:
-
HttpMessageConveter: Converts the request message (such as Json or XML data) into an object, which is converted into the specified response information
-
Data transformation: Data transformation of the request message. Such as String to Integer, Double, and so on
-
Data formatting: Data formatting of the request message. For example, converting a string to a formatted number or a formatted date
-
Data validation: Verifies the validity of data (length, format, etc.) and stores the validation results in BindingResult or Error
-
-
5. Handler returns a ModelAndView object to DispatcherServlet after execution.
-
6. According to the returned ModelAndView, select a suitable ViewResolver (must be a ViewResolver registered in Spring container) and return it to DispatcherServlet;
-
7. ViewResolver combines Model and View to render the View (Model+View composite)
-
8. Return the rendering result to the client;
-
-
Simple description
-
1. The client sends the request to DispatcherServlet.
-
2. The DispatcherServlet sends the request to HandlerMapping for request mapping and matches the Handler of the request.
-
3. The DispatcherServlet then requests the HandlerAdapter to call the corresponding Handler to handle the request and return a ModelAndView object to the front-end controller;
-
4.DispatcherServlet delivers ModelAndView object to ViewResoler for processing and returns the specified View View;
-
5.DispatcherServlet renders the View (that is, the model data is filled into the View);
-
6.DispatcherServlet sends the page response to the user;
We’re done with SpringMVC Advanced + JSON
-