在 Spring 控制器中获取参数的简便方法?
Easy way to get parameters in Spring controller?
我在 Spring 应用程序中有一个控制器,我想用它处理一个 HTML 表单来更改 CSS。所以我将表单的操作设为 "changeCSS" 并且控制器从那里接管。我的问题是:我实际上如何获得我在表单中提交的值?我在网上找到的资源都过于复杂,要我创建我并不真正需要的模型对象。
我正在寻找的值称为 color1、color2 等,它们应该替换 String.format() 方法中的硬编码颜色值。
@RequestMapping(value = "changeCSS", method = RequestMethod.GET)
public String changeCss() {
BufferedWriter writer;
try {
String colorNewSettings3 = String.format(colorSettings.get("3"), "#000");
String colorNewSettings4 = String.format(colorSettings.get("4"), "#fff");
String path = context.getRealPath("/static/css/custom.css");
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(colorNewSettings3+colorNewSettings4);
out.close();
} catch (IOException e) {
e.printStackTrace(); //Use a Logger here
}
return "settings";
}
获取表单参数最简单的方法如下例所示。这需要您创建一个 Model 对象,在我看来,这并不过分。
https://spring.io/guides/gs/handling-form-submission/
现在,如果您不想这样做并坚持使用 GET 选择每个值,下面的代码片段可以做到这一点。
http://localhost:8080/changeCSS?color1=green&color2=red
@RequestMapping(value = "/changeCSS", method = RequestMethod.GET)
public String changeCss(@RequestParam("color1") String color1, @RequestParam("color2") String color2) {
....
}
我在 Spring 应用程序中有一个控制器,我想用它处理一个 HTML 表单来更改 CSS。所以我将表单的操作设为 "changeCSS" 并且控制器从那里接管。我的问题是:我实际上如何获得我在表单中提交的值?我在网上找到的资源都过于复杂,要我创建我并不真正需要的模型对象。
我正在寻找的值称为 color1、color2 等,它们应该替换 String.format() 方法中的硬编码颜色值。
@RequestMapping(value = "changeCSS", method = RequestMethod.GET)
public String changeCss() {
BufferedWriter writer;
try {
String colorNewSettings3 = String.format(colorSettings.get("3"), "#000");
String colorNewSettings4 = String.format(colorSettings.get("4"), "#fff");
String path = context.getRealPath("/static/css/custom.css");
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(colorNewSettings3+colorNewSettings4);
out.close();
} catch (IOException e) {
e.printStackTrace(); //Use a Logger here
}
return "settings";
}
获取表单参数最简单的方法如下例所示。这需要您创建一个 Model 对象,在我看来,这并不过分。
https://spring.io/guides/gs/handling-form-submission/
现在,如果您不想这样做并坚持使用 GET 选择每个值,下面的代码片段可以做到这一点。
http://localhost:8080/changeCSS?color1=green&color2=red
@RequestMapping(value = "/changeCSS", method = RequestMethod.GET)
public String changeCss(@RequestParam("color1") String color1, @RequestParam("color2") String color2) {
....
}