【问题标题】:Easy way to get parameters in Spring controller?在 Spring 控制器中获取参数的简单方法?
【发布时间】:2019-06-13 19:13:30
【问题描述】:

我在 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";
}

【问题讨论】:

    标签: java spring forms servlets


    【解决方案1】:

    获取表单参数的最简单方法如下例所示。这需要您创建一个 Model 对象,在我看来这并不过分。

    https://spring.io/guides/gs/handling-form-submission/

    现在,如果您不想这样做并坚持使用 GET 选择每个值,下面的 sn-p 会这样做。

    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) {
    
    
         ....
    
    }
    

    参考:https://www.baeldung.com/spring-requestmapping

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多