2012-04-25 18 views
0

我使用我和春天有一个客观化关键对象子模型 - “键父”正在加载窗体时弹簧3 PropertyEditorSupport setAsText不调用的客观化客户编辑

的getAsText打印好的,但是当表单提交,setAsText被跳过。任何原因?当它到达控制器时parentType为空。它是表单问题还是控制器还是编辑器?

(侧轨道:是否有一个客观化的关键<写的编辑 - >字符串映射?)

jsp的

<form:hidden path="parentType" /> 

控制器

@InitBinder 
    protected void initBinder(HttpServletRequest request, 
      ServletRequestDataBinder binder) throws Exception { 


     /** Key Conversion **/ 
     binder.registerCustomEditor(com.googlecode.objectify.Key.class, new KeyEditor()); 
} 
@RequestMapping(value = "/subtype-formsubmit", method = RequestMethod.POST) 
    public ModelAndView subTypeFormSubmit(@ModelAttribute("productSubType") @Valid ProductSubType productSubType, 
      BindingResult result){ 
     ModelAndView mav = new ModelAndView(); 

     //OK, getting the value 
     log.info(productSubType.getType()); 

      //NOT OK, productSubType.getParentType() always null, and setAsText is not called?! 
     log.info(productSubType.getParentType().toString()); 

     return mav; 
    } 

KeyEditor.java

public class KeyEditor extends PropertyEditorSupport { 

private static final Logger log = Logger 
     .getLogger(KeyEditor.class.getName()); 

public KeyEditor(){ 
    super(); 
} 

@Override 
public String getAsText() { 
    Long id = ((Key) getValue()).getId(); 
    String kind = ((Key) getValue()).getKind(); 
    log.info(kind + "." + id.toString()); 
    return kind + "." + id.toString(); 
} 

@Override 
public void setAsText(String text) throws IllegalArgumentException { 
    log.info(text); 
    String clazz = text.substring(0, text.indexOf(".")); 
    Long id = Long.parseLong(text.substring(text.indexOf("."))); 
    log.info(clazz+":"+id); 
    Class c=null; 
    Key<?> key=null; 
    try { 
     c = Class.forName(clazz); 
     key = new Key(c, id); 
    } catch (Exception ex) { 
     log.info("ex" + ex.toString()); 
     ex.printStackTrace(); 
    } 

    setValue(key); 
} 

}

回答

0

您需要拨打Class.forName并填写完整的班级名称,包括包裹。

我认为Key#getKind()返回没有包的简单类名。此外text.substring(0, text.indexOf("."));(在setAsText)告诉我有在clazz没有点,这样你就不会喂正确输入Class.forName

选项:

  • ,如果所有的类都在同一个包,然后就因为你必须注册所有实体(ObjectifyService.register(YourEntity.class);),那么你可以同时创建一个从种类到完整的类名称的地图,然后在setAsText中使用它。

但有可能是更好的选择......

+0

,而不是写我自己的客观化关键<->串机制。我发现我可以做 String keyString =((Key)getValue())。getString(); // key to string - Key key = Key.create(text); // String to key so key现在是web安全字符串。当它在视图层中使用时 – 2012-06-16 08:38:40