简体   繁体   English

Spring MVC 3.0 下划线绑定请求参数

[英]Binding request parameters with underscores in Spring MVC 3.0

Consider the following requirement: request parameters have to be bound to objects using Spring MVC 3.0.考虑以下要求:请求参数必须使用 Spring MVC 3.0 绑定到对象。 The request parameters contain underscores (eg http://myurl:80/x?param_one=1&param_two=2 ).请求参数包含下划线(例如http://myurl:80/x?param_one=1&param_two=2 )。 These parameters should be bound to the following object:这些参数应绑定到以下 object:

class MyObject {
    private Integer paramOne;
    private Integer paramTwo;

    ...
}

How would you go about doing this?您 go 会怎么做?

Important note: consider that there may be a substantial amount of parameters and objects like this and that it's not considered good practice to define setter methods on the objects that include underscores.重要提示:考虑到可能有大量这样的参数和对象,并且在包含下划线的对象上定义 setter 方法被认为不是好的做法。

Rajith's answer is for controller methods specifically, and doesn't address your question originally asking how to bind underscore parameters to an object. Rajith的答案特别针对控制器方法,并没有解决您最初询问如何将下划线参数绑定到对象的问题。

The hacky solution I currently have in place is to accomplish what you are actually asking is to name my setters in this style: 我目前所拥有的hacky解决方案是完成您实际要求的是以这种方式命名我的二传手:

public void setProject_ids(List<Long> project_ids) {

Note that RequestParam cannot be applied to methods, and it does not have an effect when applied to the argument of this setter. 请注意,RequestParam不能应用于方法,并且在应用于此setter的参数时不起作用。

You can do this using @RequestMapping attribute 您可以使用@RequestMapping属性执行此操作

@RequestParam(value = "param_One") String paramOne,@RequestParam(value = "param_two") String paramTwo

Add this into method signature 将其添加到方法签名中

But for best practice its better to pass same variable name 但是对于最佳实践,最好传递相同的变量名称

Nine-years-later... I cleaner solution is to use constructor injection and annotate it with @ConstructorProperties .九年后......我更干净的解决方案是使用构造函数注入并用@ConstructorProperties注释它。 This way you can keep the class immutable and use Java naming convention.这样您就可以保持 class 不变并使用 Java 命名约定。

@Value
class MyObject {
  Integer paramOne;
  Integer paramTwo;

  @ConstructorProperties({"param_one", "param_two"})
  MyObject(Integer paramOne, Integer paramTwo) {
    this.paramOne = paramOne;
    this.paramTwo = paramTwo;
  }

Even if you have a very long list of fields, you can generate the constructor and only need to write the annotation.即使你有一个很长的字段列表,你也可以生成构造函数,只需要写注解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM