@RequestParam案例、简单介绍

@RequestParam案例

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>

    <form action="/upload" method="post" enctype="multipart/form-data">
        姓名: <input type="text" name="username"><br>
        年龄: <input type="text" name="age"><br>
        头像: <input type="file" name="image"><br>
        <input type="submit" value="提交">
    </form>

</body>
</html>

UploadController.java

package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
public class UploadController {
    
    

    //
    @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile image) throws IOException {
    
    
        log.info("姓名:{},年龄:{},图片:{}", username, age, image);
//        将上传文件保存/Users/haoran/Desktop/Java web/image
//        获取原始文件名
        String originalFilename = image.getOriginalFilename();
        image.transferTo(new File("/Users/haoran/Desktop/Java web/image/" +originalFilename));
        return Result.success();
    }
}

添加@RequestParam

image-20230512165447836 image-20230512165859959 image-20230512165617992

不加@RequestParam

image-20230512170134214 image-20230512170147594 image-20230512170310408 image-20230512170336611

保存成功

还有一种情况

4、参数名称不一致

index.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
  <title>JSP - Hello World</title>
</head>
<body>
<h1><%= "Hello World!" %></h1>
  <h3>4、参数名称不一致解决方案</h3>
  <form action="${pageContext.request.contextPath}/four.action">
    name:<input type="text" name="name"><br/>
    age:<input type="text" name="age"><br/>
    <input type="submit" value="提交">
  </form>
</body>
</html>

controller.java

	@RequestMapping(value = "/four")
	public String dataSubmit4(@RequestParam("name") String name4,@RequestParam("age") Integer age4){
    
    
		System.out.printf(name4 +","+age4);
		return "login";
	}

猜你喜欢

转载自blog.csdn.net/weixin_45864704/article/details/130646476