欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring 注解面面通 之 @RequestPart

程序员文章站 2022-03-04 22:58:58
...

  @RequestPart用于将multipart/form-data类型数据映射到控制器处理方法的参数中。除了@RequestPart注解外,@RequestParam同样可以用于此类操作。

  注解解析

  ① value:

    绑定的参数名称,参数值为String类型。

  ② name:

    绑定的参数名称,参数值为String类型。namevalue可以同时使用,但两者的值需一致,否则会出现错误。

attribute 'name' and its alias 'value' are present with values of [XXX] and [XXX], but only one is permitted
1

  ③ required:

    请求头中是否必须包含指定的值,默认值为true

    requiredtrue时,如果请求头中缺少指定的值,则会抛出异常。

    requiredfalse时,如果请求头中缺少指定的值,则会返回null

  注解示例

  方法参数可以使用@RequestPart@RequestParam注释,参数类型可使用org.springframework.web.multipart.MultipartFilejavax.servlet.http.Part

  javax.servlet.http.PartServlet 3.0提供的类,需在Web中进行配置:

  ① 引入Servlet-api3.0版本。

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

  ② web.xml中,首先需配置web.xml版本,然后配置multipart-config标签。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1" metadata-complete="true">
    
    ......
    
    <servlet>
        <servlet-name>springMVCServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath*:/spring/applicationContext.mvc.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <!-- 多部分请求配置 -->
        <multipart-config>
            <maxFileSize>20480000</maxFileSize>
        </multipart-config>
    </servlet>
    
    ......
    
</web-app>

  ③ 配置Spring的多部分请求解析器,例如applicationContext.mvc.xml中增加配置。

<bean id="multipartResolver"
		class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</bean>

  1)Controller,用来演示@RequestPart@RequestParam使用方法。

package com.arhorchin.securitit.webannotations;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Securitit.
 * @note 演示@RequestPart使用方法.
 */
@Controller
@RequestMapping("/WebAnnotations")
public class RequestPartController {

    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(RequestPartController.class);

    /**
     * 跳转页面.
     */
    @RequestMapping(
            value = "/RequestPart.html",
            method = RequestMethod.GET)
    public ModelAndView requestPartHtml(HttpServletRequest req, HttpServletResponse res, ModelMap modelMap)
            throws Exception {
        return new ModelAndView("webannotations/RequestPart", modelMap);
    }

    /**
     * RequestPart-MultipartFile接收参数.
     */
    @ResponseBody
    @RequestMapping(
            value = "/requestPartMultipartFile.do",
            method = RequestMethod.POST)
    public String requestPartMultipartFile(@RequestPart("file") MultipartFile multipartFile) throws Exception {
        logger.info("Current value of RequestPart [MultipartFile] : name is [" + multipartFile.getOriginalFilename()
                + "], file length is [" + multipartFile.getSize() + "]");
        return "Current value of RequestPart [MultipartFile] : name is [" + multipartFile.getOriginalFilename() + "], file length is ["
                + multipartFile.getSize() + "]";
    }

    /**
     * RequestPart-Part接收参数.
     */
    @ResponseBody
    @RequestMapping(
            value = "/requestPartPart.do",
            method = RequestMethod.POST)
    public String requestPartPart(@RequestPart("file") Part part) throws Exception {
        logger.info(
                "Current value of RequestPart [Part] : name is [" + part.getName() + "], file length is [" + part.getSize() + "]");
        return "Current value of RequestPart [Part] : name is [" + part.getName() + "], file length is [" + part.getSize() + "]";
    }
    
    /**
     * RequestParam-MultipartFile接收参数.
     */
    @ResponseBody
    @RequestMapping(
            value = "/requestParamMultipartFile.do",
            method = RequestMethod.POST)
    public String requestParamMultipartFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        logger.info("Current value of RequestParam [MultipartFile] : name is [" + multipartFile.getOriginalFilename()
                + "], file length is [" + multipartFile.getSize() + "]");
        return "Current value of RequestParam [MultipartFile] : name is [" + multipartFile.getOriginalFilename() + "], file length is ["
                + multipartFile.getSize() + "]";
    }

    /**
     * RequestParam-Part接收参数.
     */
    @ResponseBody
    @RequestMapping(
            value = "/requestParamPart.do",
            method = RequestMethod.POST)
    public String requestParamPart(@RequestParam("file") Part part) throws Exception {
        logger.info(
                "Current value of RequestParam [Part] : name is [" + part.getName() + "], file length is [" + part.getSize() + "]");
        return "Current value of RequestParam [Part] : name is [" + part.getName() + "], file length is [" + part.getSize() + "]";
    }

    /**
     * Part接收参数.
     */
    @ResponseBody
    @RequestMapping(
            value = "/part.do",
            method = RequestMethod.POST)
    public String part(HttpServletRequest req) throws Exception {
        Part part = req.getPart("file");
        logger.info(
                "Current value of Part : name is [" + part.getName() + "], file length is [" + part.getSize() + "]");
        return "Current value of Part : name is [" + part.getName() + "], file length is [" + part.getSize() + "]";
    }

}

  2)html,用来演示RequestPartController示例。

<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="Author" content="Securitit">
		<meta name="Keywords" content="-">
		<meta name="Description" content="Securitit @RequestPart 测试页面">
		<title>@RequestPart 测试页面</title>
	</head>
	<body>
		<div style="float: left; width: 520px; border: 1px solid #d8b1b1; padding: 20px 20px;">
			<h1 style="margin-top: -10px; text-align: center;">@RequestPart注解</h1>
			<div style="border: 1px solid #d8b1b1; padding: 10px 10px; padding-bottom: 30px; width: 500px;">
				<h1>RequestPart-MultipartFile 接收参数</h1>
				<form action="http://localhost:9199/spring-annotations/WebAnnotations/requestPartMultipartFile.do"
					method="post" enctype="multipart/form-data">
					<input type="file" name="file"/>
					<input type="submit" style="width: 100px; background-color: #e6dddd; margin-top: 30px; margin-left: 200px;"/>
				</form>
			</div>
			<div style="border: 1px solid #d8b1b1; padding: 10px 10px; padding-bottom: 30px; width: 500px; margin-top: 50px;">
				<h1>RequestPart-Part 接收参数</h1>
				<form action="http://localhost:9199/spring-annotations/WebAnnotations/requestPartPart.do"
					method="post" enctype="multipart/form-data">
					<input type="file" name="file"/>
					<input type="submit" style="width: 100px; background-color: #e6dddd; margin-top: 30px; margin-left: 200px;"/>
				</form>
			</div>
		</div>
		<div style="float: left; width: 520px; border: 1px solid #d8b1b1; padding: 20px 20px; margin-left: 50px;">
			<h1 style="margin-top: -10px; text-align: center;">@RequestParam注解</h1>
			<div style="border: 1px solid #d8b1b1; padding: 10px 10px; padding-bottom: 30px; width: 500px;">
				<h1>RequestParam-MultipartFile 接收参数</h1>
				<form action="http://localhost:9199/spring-annotations/WebAnnotations/requestParamMultipartFile.do"
					method="post" enctype="multipart/form-data">
					<input type="file" name="file"/>
					<input type="submit" style="width: 100px; background-color: #e6dddd; margin-top: 30px; margin-left: 200px;"/>
				</form>
			</div>
			<div style="border: 1px solid #d8b1b1; padding: 10px 10px; padding-bottom: 30px; width: 500px; margin-top: 50px;">
				<h1>RequestParam-Part 接收参数</h1>
				<form action="http://localhost:9199/spring-annotations/WebAnnotations/requestParamPart.do"
					method="post" enctype="multipart/form-data">
					<input type="file" name="file"/>
					<input type="submit" style="width: 100px; background-color: #e6dddd; margin-top: 30px; margin-left: 200px;"/>
				</form>
			</div>
		</div>
	</body>
</html>

  3) 启动服务,访问http://localhost:9199/spring-annotations/WebAnnotations/RequestPart.html页面。

Spring 注解面面通 之 @RequestPart

  ① @RequestPart注解-RequestPart-MultipartFile 接收参数

Spring 注解面面通 之 @RequestPart

  ② @RequestPart注解-RequestPart-Part 接收参数

Spring 注解面面通 之 @RequestPart

  ③ @RequestParam注解-RequestPart-MultipartFile 接收参数

Spring 注解面面通 之 @RequestPart

  ④ @RequestParam注解-RequestPart-Part 接收参数

Spring 注解面面通 之 @RequestPart

​  总结

  @RequestPart@RequestParam都可以处理multipart/form-data类型数据,本质上并没有区别,使用任何一个都能达到期望的效果。文件上传在实际应用中也是必不可少的。

  若文中存在错误和不足,欢迎指正!