数据绑定,不使用spring taglib作为变量,以下划线“_”开头

时间:2013-01-04 13:40:09

标签: html spring data-binding spring-mvc

我的html是在不使用spring taglib的情况下构建的,现在我想将表单的参数绑定到控制器中的对象。 我有一个问题绑定属性开始与下划线“_”

目前我的表单看起来像这样

<form method="post" action="${pageContext.request.contextPath}/test.form">
          <input type="text" name="_NumeroPage" />
      <input type="text" name="_Tri" />
      <input type="text" name="_SensTri" />
      <input type="text" name="codePays" />
</form>

我的目标的相关部分是

Class TestForm{
private String _NumeroPage;
private String _Tri;
private String _SensTri;
private String codePays ;
// getter and setter
}

我的控制器是

@RequestMapping(value={"/test","/test.form"})
public String paginerSequencesSuiviMulticanal(TestForm formulaire, Model model, HttpSession session){

        model.addAttribute("_NumeroPage", formulaire.get_NumeroPage());
        model.addAttribute("_Tri", formulaire.get_Tri());
        model.addAttribute("_SensTri", formulaire.get_SensTri());
        model.addAttribute("codePays", formulaire.getCodePays());

    return "/result";
}

如何绑定它。目前,_NumeroPage,_Tri, SensTri不会发生绑定,但它确实绑定了codePays。 是否存在将属性开头与下划线字符“”绑定的工作?

2 个答案:

答案 0 :(得分:1)

你可以深入研究Spring中的bean属性访问器代码并找出原因(在粗略检查代码或文档时找不到任何东西),但似乎更容易解决 not 在数据绑定涉及的类和字段中使用带有前导下划线的名称。

答案 1 :(得分:-1)

您可以尝试创建ServletRequestDataBinder的自定义子类,该子类将以下划线开头的请求参数映射到没有下划线的字段。然后,您必须创建一个自定义的ServletRequestDataBinderFactory来创建一个子类。接下来,您需要创建RequestMappingHandlerAdapter的自定义子类并将其注册到Spring MVC。这将允许您继续在HTML中使用下划线,而不必在POJO字段名称中使用下划线。

自定义ServletRequestDataBinder:

public class MyCustomServletRequestDataBinder extends
  ExtendedServletRequestDataBinder {
  public MyCustomServletRequestDataBinder(Object target) {
    super(target);
  }

  public MyCustomServletRequestDataBinder(Object target, String objectName) {
    super(target, objectName);
  }

  @Override
  protected void addBindValues(MutablePropertyValues mpvs,
      ServletRequest request) {
    super.addBindValues(mpvs, request);

    addUnderscoreBindValues(mpvs, request);
  }

  protected void addUnderscoreBindValues(MutablePropertyValues mpvs,
      ServletRequest request) {
    // go through each parameter and check if it starts with an underscore (_)
    // if it starts with an underscore, add it to mpvs under the name without
    // the underscore
    @SuppressWarnings("unchecked")
    Map<String, Object> parameterMap = request.getParameterMap();
    for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
      if (StringUtils.startsWith(entry.getKey(), "_")) {
        mpvs.add(StringUtils.removeStart(entry.getKey(), "_"), entry.getValue());
      }
    }
  }
}

自定义ServletRequestDataBinderFactory:

public class MyCustomServletRequestDataBinderFactory extends
    ServletRequestDataBinderFactory {
  /**
   * Create a new instance.
   * @param binderMethods one or more {@code @InitBinder} methods
   * @param initializer provides global data binder initialization
   */
  public MyCustomServletRequestDataBinderFactory(
      List<InvocableHandlerMethod> binderMethods,
      WebBindingInitializer initializer) {
    super(binderMethods, initializer);
  }

  /**
   * Returns an instance of {@link MyCustomServletRequestDataBinder}.
   */
  @Override
  protected ServletRequestDataBinder createBinderInstance(Object target,
      String objectName, NativeWebRequest request) {
    return new MyCustomServletRequestDataBinder(target, objectName);
  }
}

自定义RequestMappingHandlerAdapter:

public class MyCustomRequestMappingHandlerAdapter extends
    RequestMappingHandlerAdapter {
  public MyCustomRequestMappingHandlerAdapter() {
    super();
  }

  /**
   * {@inheritDoc} Creates an instance of
   * {@link MyCustomServletRequestDataBinderFactory}.
   */
  @Override
  protected ServletRequestDataBinderFactory createDataBinderFactory(
      List<InvocableHandlerMethod> binderMethods) throws Exception {
    return new MyCustomServletRequestDataBinderFactory(binderMethods,
        getWebBindingInitializer());
  }
}

然后注册自定义HandlerAdapter:

@Configuration
@Import(ValidationConfiguration.class)
@ComponentScan(basePackageClasses = ControllerScanMarker.class)
public class MyCustomHandlerConfig extends WebMvcConfigurationSupport {
  /**
   * {@inheritDoc} Returns the subclass
   * {@link MyCustomRequestMappingHandlerAdapter} in place of the default
   * {@link RequestMappingHandlerAdapter}.
   */
  @Override
  @Bean
  public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
    ...
    RequestMappingHandlerAdapter adapter = new MyCustomRequestMappingHandlerAdapter();

    // set additional adapter fields here...
    ...
    return adapter;
  }
}

我很确定在默认请求参数绑定期间可能有更简单的方法来修改/添加其他值,但我不记得其他挂钩在哪里。