SPRINGMVC return JSON data and file upload, filter static resources

Source: Internet
Author: User
Tags button type

Return JSON data

In today's front and back end of the trend of separation, the back end basically do not need to care about the front page of things, only need to handle the data well and through the corresponding interface to return data to the front. In Springmvc, we can use @responsebody annotations to return JSON data or XML data.

The effect of this annotation is that the object returned by the Controller method is converted to the specified format by the appropriate converter and written to the body area of the response object, which is the content body of the HTTP response, which is generally used to return the JSON data, because the default is to convert in JSON format.

It is important to note that, after using this annotation, the view parser is not taken, but the data is written directly to the output stream, and his effect is equivalent to outputting the data in the specified format using the Response object.

Because this annotation relies on Jackson, so to use this annotation, we first need to configure the Jackson package, which depends on the following configuration:

    <dependency>      <groupId>com.fasterxml.jackson.core</groupId>      <artifactId>jackson-databind</artifactId>      <version>2.9.4</version>    </dependency>

And in the spring configuration file, you need to add a sentence configuration to open the @responsebody annotation:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p" xmlns:mvc= "Http://www.springframework.org/schema/mvc" XSI:SC hemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/    Spring-mvc.xsd "> <context:annotation-config/> <context:component-scan base-package=" org.zero01 "/> <!--need to add a sentence to open @responsebody annotations-<mvc:annotation-driven/> <bean class= "Org.springframework.web.serv Let.view.InternalResourceViewResolver "p:prefix="/web-inf/pages/"p:suffix=". JSP "/></beans> 

@ResponseBody annotations can be written on a class or method, written on a class that takes effect on all methods in that class, and the code example is as follows:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@ResponseBody@Controllerpublic class Test {    @RequestMapping("/test.do")    public Student test() {        Student student = new Student();        student.setSname("zero");        student.setAge(16);        student.setAddress("USA");        return student;    }}

Written on the method is only valid for this method, the code example is as follows:

package org.zero01.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class Test {    @RequestMapping("/test.do")    @ResponseBody    public Student test() {        Student student = new Student();        student.setSname("zero");        student.setAge(16);        student.setAddress("USA");        return student;    }}

Because the data is written directly to the output stream, the effect of the above code is equivalent to the following code:

@RequestMapping("/login")public void test(HttpServletResponse response){    Student student = new Student();    student.setSname("zero");    student.setAge(16);    student.setAddress("USA");  response.getWriter.write(JSONObject.fromObject(user).toString());}

With postman access, the returned data is as follows:

The above only uses a common Pojo object as the return data of the presentation, in addition to @responsebody annotations, you can convert the following types of data into JSON format:

    • Basic data types, such as Boolean, String, int, etc.
    • MAP type Data
    • Collection or array
    • Entity objects
    • Entity Object Collection

If you need @ResponseBody annotations to function on a class, we can use @RestController annotations directly, which is equivalent to @responsebody + @Controller annotations, so we don't need to write two annotations, example:

package org.zero01.test;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class Test {    @RequestMapping("/test.do")    public Student test() {        Student student = new Student();        student.setSname("zero");        student.setAge(16);        student.setAddress("USA");        return student;    }}

With postman access, the returned data is as follows:

Since the data can be sent to the client, then the relative can receive the data sent by the client, and the @requestbody annotations can receive the JSON data sent by the client, and bind to the corresponding method parameters, such as the following example:

package org.zero01.test;import org.json.JSONObject;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class Test {    @RequestMapping("/test.do")    public void test(@RequestBody  Student student) {        System.out.println(new JSONObject(student));    }}

With postman access, the JSON data is sent as follows:

The console prints the following results:

{"address":"USA","sname":"Json","age":20}
File Upload

File upload is a very common need, especially such as forums, blogs and other sites often need to upload pictures or something, such as uploading a user avatar or article map. If we use Java IO to complete the file upload is very laborious, need to write more code. But in Springmvc, it helps us encapsulate the details of the read and write of the file's cross IO. So that we can easily complete the file upload code to write, the following is a brief introduction of how to use SPRINGMVC to complete the file upload.

The implementation of file upload in Springmvc is dependent on the FileUpload package, so we need to configure the dependencies as follows:

<dependency>  <groupId>commons-fileupload</groupId>  <artifactId>commons-fileupload</artifactId>  <version>1.3.3</version></dependency>

Then, in the spring configuration file, assemble the Commonsmultipartresolver class:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"          p:defaultEncoding="utf-8"  // 设置编码格式          p:maxUploadSize="10485760"  // 设置文件的总大小/>

Note that this ID value must be multipartresolver, because it corresponds to a constant value in Dispatcherservlet, such as:

After the configuration is complete, you can start writing code, the controller code is as follows:

Package Org.zero01.test;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.multipart.MultipartFile; Import Javax.servlet.http.httpsession;import java.io.File; @Controllerpublic class UploadFile {@RequestMapping (value = "/upload-file.do", method = requestmethod.post) public String uploadfile (multipartfile multipartfile, HttpSession ses        Sion) {System.out.println ("form field Name:" + multipartfile.getname ());        System.out.println ("uploaded file name:" + multipartfile.getoriginalfilename ());        System.out.println ("uploaded file type:" + multipartfile.getcontenttype ());        System.out.println ("uploaded file Size:" + multipartfile.getsize () + "byte"); System.out.println ("is the uploaded file empty:" + (Multipartfile.isempty ()?)        "Yes": "no"));            only upload. jpg image files, the true file type needs to be judged by ContentType if (!multipartfile.getcontenttype (). Equals ("Image/jpeg")) {        Session.setattribute ("ErrMsg", "only upload image files in. jpg format");    System.err.println ("File upload failed \ n");        return "error";        }//Get the absolute path of the uploadfile String Realpath = Session.getservletcontext (). Getrealpath ("UploadFile");        Place the file under this path, filename file = new file (Realpath, Multipartfile.getoriginalfilename ());        Create uploadfile directory File.getparentfile (). mkdir ();            try {//writes the uploaded file to the local Multipartfile.transferto (file);            Session.setattribute ("Imgpath", Multipartfile.getoriginalfilename ());            System.out.println ("File upload complete \ n");        return "Upload";            } catch (Exception e) {e.printstacktrace ();            System.err.println ("File upload failed \ n");            Session.setattribute ("ErrMsg", e.tostring ());        return "error"; }    }}

The contents of the upload.jsp file are as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

The contents of the error.jsp file are as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Upload file:

Upload success:

The console prints as follows:

表单字段名称:multipartFile上传的文件名称:kfc.jpg上传的文件类型:image/jpeg上传的文件大小:13327 byte上传的文件是否为空:否文件上传完成

Above we completed a single file upload, if you want to implement a multi-file upload is also very simple, on the method parameters to declare the Multipartfile array, and then use the loop to traverse the uploaded file and write to the local can, modify the controller code as follows:

Package Org.zero01.test;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.multipart.MultipartFile; Import Javax.servlet.http.httpsession;import java.io.file;import Java.util.arraylist;import java.util.List;@ Controllerpublic class UploadFile {@RequestMapping (value = "/upload-file.do", method = requestmethod.post) public S  Tring UploadFile (multipartfile[] Multipartfiles, HttpSession session) {//Get UploadFile absolute path String Realpath        = Session.getservletcontext (). Getrealpath ("UploadFile");        File File = new file (Realpath);        If the UploadFile directory does not exist, you need to create if (!file.exists ()) {File.mkdir ();            } try {list<string> fileNames = new arraylist<string> (); for (Multipartfile multipartfile:multipartfiles) {System.out.println ("form field Name:" + multiparTfile.getname ());                System.out.println ("uploaded file name:" + multipartfile.getoriginalfilename ());                System.out.println ("uploaded file type:" + multipartfile.getcontenttype ());                System.out.println ("uploaded file Size:" + multipartfile.getsize () + "byte"); System.out.println ("is the uploaded file empty:" + (Multipartfile.isempty ()?)                "Yes": "no"));                     only upload. jpg image files, the true file type needs to be judged by ContentType if (!multipartfile.getcontenttype (). Equals ("Image/jpeg")) {                    Session.setattribute ("ErrMsg", "only upload image files in. jpg format");                    System.err.println ("File upload failed \ n");                return "error";                }//Put files in the UploadFile directory file = new file (Realpath, Multipartfile.getoriginalfilename ());                Writes the uploaded file to the local Multipartfile.transferto (file);                Filenames.add (Multipartfile.getoriginalfilename ());            System.out.println ("File upload complete \ n"); } SESsion.setattribute ("FileNames", fileNames);            } catch (Exception e) {e.printstacktrace ();            System.err.println ("File upload failed \ n");            Session.setattribute ("ErrMsg", e.tostring ());        return "error";    } return "Upload"; }}

Modify the contents of the upload.jsp file as follows:

<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%><%@ taglib prefix= "C" uri= "/HTTP/ Java.sun.com/jstl/core_rt "%>

Upload file:

Upload success:

The console output results are as follows:

表单字段名称:multipartFiles上传的文件名称:1.jpg上传的文件类型:image/jpeg上传的文件大小:4816 byte上传的文件是否为空:否文件上传完成表单字段名称:multipartFiles上传的文件名称:2.jpg上传的文件类型:image/jpeg上传的文件大小:2824 byte上传的文件是否为空:否文件上传完成表单字段名称:multipartFiles上传的文件名称:3.jpg上传的文件类型:image/jpeg上传的文件大小:4836 byte上传的文件是否为空:否文件上传完成表单字段名称:multipartFiles上传的文件名称:4.jpg上传的文件类型:image/jpeg上传的文件大小:3368 byte上传的文件是否为空:否文件上传完成表单字段名称:multipartFiles上传的文件名称:5.jpg上传的文件类型:image/jpeg上传的文件大小:2379 byte上传的文件是否为空:否文件上传完成
Filtering static resources

In some cases, we may configure Dispatcherservlet in Web. XML to intercept all access under the entire root directory, so that all accesses need to be allocated by that servlet, for example:

<servlet>    <servlet-name>dispatcherServlet</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>dispatcherServlet</servlet-name>    <url-pattern>/</url-pattern></servlet-mapping>

As a result, all access requests go through Dispatcherservlet, and Dispatcherservlet only assigns access requests to the controller, and if no corresponding method of processing the request is found in the controller, a 404 error is reported. So when we need to access static resources instead of accessing the controller, we can't access it normally, for example, I created an ordinary text file in the WebApp directory:

Then access the file in the browser will be reported 404 error:

This is because the controller does not map test.txt such a URI, so the final dispatcherservlet does not find the corresponding mapping address will be reported 404 error.

To solve this problem is also very simple, only in the spring configuration file, add this sentence configuration can be:

<mvc:default-servlet-handler/>

This configuration information is equivalent to concatenation of the org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler static resource processing class on Dispatcherservlet, each access request comes, will first pass through Defaultservlethttprequesthandler to determine whether it is a static file, if it is a static file, is processed, not the release is referred to the Dispatcherservlet controller for processing.

So this is the time to access the Test.txt file in the browser:

However, this Defaultservlethttprequesthandler class can only handle ordinary static resource files, if the static resource file is stored in some of the more special directories, such as the Web-inf directory, then it can not be processed, will be reported 404 error. and its processing priority is relatively low, only when the Dispatcherservlet traverse all the controller did not find the corresponding mapping address, will be the access request to the Defaultservlethttprequesthandler class to handle. Therefore, in the case of static resource file access is very frequent, it will appear relatively slow.

But fortunately there is another tag that can be used to filter the resource file, and we usually use this tag to complete the mapping of the static resource file. For example, I put the test.txt file in the Web-inf directory:

Then, in the spring configuration file, add the &lt;mvc:resources/&gt; tag as follows:

<mvc:resources mapping="test.txt" location="/WEB-INF/test.txt"/>

The mapping property is used to specify the URI address of the map, and location is used to specify the path where the destination file resides.

Browser access is as follows:

Because the map is the URI address, so the URI can be arbitrarily add a virtual directory or something:

<mvc:resources mapping="/test/test.txt" location="/WEB-INF/test.txt"/>

If you need to map a file in the entire directory, you only need to use a wildcard character:

<mvc:resources mapping="/test/**" location="/WEB-INF/"/>

In addition to the two properties used above, there is an order property, which can specify which first is matched in the case of a file with the same name. For example, there is a test.txt file under Web-inf, and a test.txt file under the test directory, such as:

And these two files are mapped in the same/test/directory, in this case you need to specify which file priority is matched, as follows:

<mvc:resources mapping="/test/**" location="/WEB-INF/" order="1"/><mvc:resources mapping="/test/**" location="/WEB-INF/test/" order="2"/>

The smaller the number, the higher the priority, and the browser accesses the following:

SPRINGMVC return JSON data and file upload, filter static resources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.