在HTML表单中传递字符串数组并提交给Java Spring Controller,可以通过以下步骤实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Submission</title>
</head>
<body>
<form action="/submit" method="post">
<label for="strings">Enter strings (comma separated):</label>
<input type="text" id="strings" name="strings" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class FormController {
@PostMapping("/submit")
public String submitStrings(@RequestParam("strings") String input) {
// Split the input string by comma to create an array of strings
List<String> strings = Arrays.asList(input.split(","));
// Process the list of strings as needed
StringBuilder result = new StringBuilder();
for (String str : strings) {
result.append(str).append("\n");
}
return "Submitted strings:\n" + result.toString();
}
}
原因:可能是由于表单字段名称与Controller中的参数名称不匹配。
解决方法:确保表单字段名称与Controller中的@RequestParam
注解中的名称一致。
原因:URL编码问题。 解决方法:在客户端对输入进行URL编码,在服务器端进行解码。
// 客户端JavaScript代码
const input = document.getElementById('strings').value;
const encodedInput = encodeURIComponent(input);
window.location.href = `/submit?strings=${encodedInput}`;
// 服务器端Java代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
@RestController
public class FormController {
@GetMapping("/submit")
public String submitStrings(@RequestParam("strings") String input) {
// Decode the input string
String decodedInput = URLDecoder.decode(input, StandardCharsets.UTF_8);
// Split the input string by comma to create an array of strings
List<String> strings = Arrays.asList(decodedInput.split(","));
// Process the list of strings as needed
StringBuilder result = new StringBuilder();
for (String str : strings) {
result.append(str).append("\n");
}
return "Submitted strings:\n" + result.toString();
}
}
通过以上步骤,你可以实现从HTML表单传递字符串数组并提交给Java Spring Controller。
领取专属 10元无门槛券
手把手带您无忧上云