Custom message converter and file upload in SpringMVC developed by JavaEE, javaeespringmvc

Source: Internet
Author: User

Custom message converter and file upload in SpringMVC developed by JavaEE, javaeespringmvc

In the previous blog, we talked in detail about static resource ing and server push technology in spring MVC of Java EE development. This blog is still in Java EE development, let's talk about the file upload in spring MVC and HttpMessageConverter. The message forwarder is commonly used in daily development. It can flexibly parse user-sent messages in a custom format, and then map the parsed data to a Model, the details of the custom message forwarder are shown below. After talking about the message forwarder, we will also talk about how to upload MVC files in Spring. For more information, see the following section.

 

1. Custom message Forwarder

Next we will implement a custom message forwarder. When you define a message forwarder, We need to base on the AbstractHttpMessageConverter abstract class in Springframework. This abstract class defines the methods we need to customize the message forwarder. We just need to rewrite these methods.

 

1. Create a message forwarder class

Below is the process of creating a custom message forwarder. we name it CustomMessageConverter class, as shown below:

  

 

Next, let's talk about the content in CustomMessageConverter. The code segment below is part of the CustomMessageConverter class. When inheriting a class, we specify the generic type as the StudentModel class. Then, in the constructor of this class, we create a new media type. The media type is defined by ourselves and the corresponding encoding method is specified. In the override support () method, we can determine whether the supported Class is the same as the Class of StudentModel. As follows:

  

 

The two rewriting methods below are responsible for the data input and output methods. In the readInternal () method, it is responsible for receiving the messages sent from the client and parsing them according to our custom media type. Here, we can transmit the new Enumeration type format in the "aaa-bbb-ccc" mode, that is, split parameters, during parsing, we split the object according to this rule, assign a value to the corresponding Model object, and return the object.

A parameter in the output method writeInternal () is the Model object returned by the input method above. In this method, the output value is provided based on the information provided by the user. Here, we add "hello" in front of the data provided by the data to return the data, as shown below.

  

 

2. configure a custom message forwarder in Spring

After creating the message forwarder class, we need to perform the extension configuration in the Spring configuration file. The code segment below is the configuration of the above custom message forwarder in the Spring configuration file. In the overwriteable extendMessageConverters () method, add the above custom message forwarding object, the Code is as follows.

  

 

3. Create a test controller for the above message Forwarder

The above is what our message forwarder has done. Next, we should test it. The following code snippet is the test Controller we created to test the custom message forwarder. We named it MessageConverterController. When we set the route, we set the media type to "application/x-parameter. As follows:

 1 package com.zeluli.springmvc.web; 2  3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestBody; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7  8 import com.zeluli.model.StudentModel; 9 10 @Controller11 public class MessageConverterController {12     @RequestMapping(value = "/convert", produces = {"application/x-parameter"})13     @ResponseBody14     public StudentModel converter(@RequestBody StudentModel student) {15         return student;16     }17 }

 

4. Create a test page

After creating the test class, we will create our JSP test page. Create a message_converter.jsp page to initiate a request like the Controller above. In this file, ajax in jQuery is used for the request, and it is a POST request, as shown below. The main function of the code below is to click a button to make a request, and then add the requested data to the HTML file node. The Code is as follows.

1 <% @ page language = "java" contentType = "text/html; charset = UTF-8" 2 pageEncoding = "UTF-8" %> 3 <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" http://www.w3.org/TR/html4/loose.dtd "> 4 

 

Then we need to configure routing for the preceding JSP page in the Spring Config file and route the access path to the preceding jsp page. Add the following code snippet to the addViewControllers () method in the configuration file:

registry.addViewController("/message_converter").setViewName("/message_converter");

 

After configuring the route, we can test it. Below is the final result of our test, as shown below:

  

 

 

 

Ii. File Upload

After talking about the message forwarder, let's talk about the file upload in SpringMVC. Of course, file upload in SpringMVC is relatively simple. Below, we first add the required libraries in this part of the Maven dependency library, then configure them in the Spring configuration file, then create the Controller for the uploaded file, and finally create the JSP for the uploaded page. page. For details, see the following section.

 

1. Introduce the dependent libraries for uploading files

First, we need to introduce the dependent libraries required to upload files. below is the dependency library we configured in pom. xml. One is the dependent library responsible for file upload and the other is the dependent library responsible for file IO operations. The following dependent libraries can all be found on Maven's official website, as shown below:

1 <! -- File Upload --> 2 <! -- Https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> 3 <dependency> 4 <groupId> commons-fileupload </groupId> 5 <artifactId> commons-fileupload </artifactId> 6 <version> 1.3.1 </version> 7 </dependency> 8 9 <! -- Simplify io operations --> 10 <! -- Https://mvnrepository.com/artifact/commons-io/commons-io --> 11 <dependency> 12 <groupId> commons-io </groupId> 13 <artifactId> commons-io </artifactId> 14 <version> 2.4 </version> 15 </dependency> 16

 

2. Configuration File Upload

After the corresponding dependent libraries are introduced, we have to configure them in the Spring configuration file before our file upload will take effect. Below is the file upload configuration in the Spring configuration file. The details are as follows:

  

 

3. Create a Controller for File Upload

After the dependent libraries and configurations for file upload are introduced, we should create the Controller for file upload. The Controller named UploadFileController created below is responsible for file upload. The request method below is POST, and then the request weight is @ RequestParam ("parameter name") to obtain the corresponding Upload File. After obtaining the uploaded file, we save the uploaded file to the specified directory through the file IO operation, as shown below:

  

 

4. Create a JPS page for File Upload

After the File Upload controller is created, we should create the corresponding JPS page for the uploaded file. Of course, the HTML code below is relatively simple, that is, the Form is used to upload the corresponding file. The Code is as follows:

1 <% @ page language = "java" contentType = "text/html; charset = UTF-8" 2 pageEncoding = "UTF-8" %> 3 <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" http://www.w3.org/TR/html4/loose.dtd "> 4 

 

After the JSP page is created, we still need to configure the route for the JSP page. We still use the Spring configuration file for fast routing configuration, as shown below:

 

After all the above steps are completed, we can access the file upload route configured above. The following figure shows the corresponding result, as shown below. After the upload is complete, an OK message is returned, and the user-uploaded file appears in the corresponding file, as shown below:

 

This blog is here, and the sharing address of the above example on github is: https://github.com/lizelu/SpringMVCWithMaven

 

Related Article

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.