@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
不加@RequestParam
保存成功
还有一种情况
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";
}