显示表单时未调用 Spring @InitBinder =>自定义编辑器未定义

发布于 2024-08-29 01:39:06 字数 1150 浏览 8 评论 0原文

我有以下(简化为骨干)控制器:

@Controller  
public class TestController  {

@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(final ModelMap map) {
    final TestFilter filter = new TestFilter();
    filter.setStartDate(new Date(System.currentTimeMillis()));
    map.addAttribute("reportPerResourceForm", filter);
    return "test";
}

@InitBinder
public void initBinder(final WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
}

}

jsp:

<form:form commandName="reportPerResourceForm" id="reportForm">
    <form:input path="startDate" />
</form:form>

这是我快速创建的一个控制器,用于测试我在另一个视图控制器中遇到的问题。正如您在控制器中看到的,定义了 CustomeDateEditor。在我的实际控制器中,该编辑器工作正常;例如,当您在表单字段中输入 11/01/2010 时,编辑器会很好地将其转换为日期;当返回表单时,日期再次很好地转换回字符串。

但是,当我(如在 TestController 中)想要在表单上设置默认日期时,这只会在表单字段中显示 Date.toString(),而不是使用 CustomDateEditor.getAsText() 返回的值!经过一些调试后,我了解到当 RequestMethod == GET 时,不会调用我的 InitBinder 方法。这是正常的吗?

我确信我可以通过不使用来解决这个问题

感谢您的帮助,
斯泰因

I have following (simplified to the bone) Controller:

@Controller  
public class TestController  {

@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(final ModelMap map) {
    final TestFilter filter = new TestFilter();
    filter.setStartDate(new Date(System.currentTimeMillis()));
    map.addAttribute("reportPerResourceForm", filter);
    return "test";
}

@InitBinder
public void initBinder(final WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
}

}

The jsp:

<form:form commandName="reportPerResourceForm" id="reportForm">
    <form:input path="startDate" />
</form:form>

This is a controller I quickly created to test out an issue I had with another view-controller. As you can see in the Controller a CustomeDateEditor is defined. In my actual controller this editor is working fine; when you enter for instance 11/01/2010 in the form field this is nicely converted into a Date by the editor; also when going back to the form the Date was again nicely converted back to a String.

However, when I (as in TestController) want to set a default date on the form then this gets simply displayed a Date.toString() in the form field instead of using the returned value from CustomDateEditor.getAsText()! After some debugging I learned that my InitBinder method is not called when RequestMethod == GET. Is this normal?

I'm sure I could workaround this by not using

Thanks for your help,
Stijn

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凉月流沐 2024-09-05 01:39:06

在转发到页面之前使用 @ModelAttribute 设置域。

当你处理 Spring 时,请小心使用 new ,它只会在 Spring 上下文之外创建一个新的对象实例,并且你不能使用 Spring 的任何功能(例如 Web 绑定、验证等)。

示例:

@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(@ModelAttribute yourDomain, final ModelMap map)

在您的域中您可以使用:

@DateTimeFormat(pattern="dd/MM/yyyy")
private Date balance = new Date(System.currentTimeMillis());

use @ModelAttribute to setup domain before forwarding to page.

carefully to use new when you deal with spring, it will just create a new instance of object outside spring context and you cannot use any of spring capability (such as web binding, validation, etc).

example :

@RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public String showForm(@ModelAttribute yourDomain, final ModelMap map)

and at your domain you can use :

@DateTimeFormat(pattern="dd/MM/yyyy")
private Date balance = new Date(System.currentTimeMillis());
林空鹿饮溪 2024-09-05 01:39:06

我不确定,但 registerCustomEditor 方法中的第二个参数设置为 null。这个参数是设置你想要与编辑器关联的字段名称,所以我不知道当它设置为空时会发生什么。如果您想将此编辑器与特定类型的所有字段一起使用,则存在不带此参数的相同方法:

public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor)

我会尝试使用此方法,但我不确定这是否可以解决问题。

binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));

希望有帮助。

I'm not sure but the second argument in registerCustomEditor method is set to null. This argument is to set the field name you want to associate the editor with, so I don't know exactly what it is going to happen when it's set to null. If you want to use this editor with all fields of a specific type it exists the same method without this parameter:

public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor)

I would try with this, though I'm not sure this will solve the problem.

binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));

Hope it helps.

庆幸我还是我 2024-09-05 01:39:06

为了解决这个问题,我自己在控制器中有以下代码:



        @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(Category.class, new CategoryEditor(categoryService));
        }

        @ModelAttribute("categoryList") // Populate reference-data (EG select-lists) in the view. (p. 390-

    391).
        public List<Category> populateCategoryList() {
            return categoryService.list();
        }

        // Note: without adding "BindingResult result" to the following prototype
        // (and preceding it with a @ModelAttribute("categoryList") -
        // my initBibder() method does not get called!
        // I discovered and added this hokum in response to the following links:
        // http://forum.springsource.org/showthread.php?46837-InitBinder-not-called
        // http://forum.springsource.org/showthread.php?46876-Custom-date-format-on-GET-requests&p=154820
        @RequestMapping("/site/list.htm")
        @ModelAttribute("sites")  // 20110819
        public ModelAndView listSite(
                @ModelAttribute("category") Category category,
                BindingResult result
                )
        {
    //        List<Site> sites = siteService.list();
            List<Site> sites = new ArrayList<Site>(); // = siteService.list();
            return new ModelAndView("siteList", "sites", sites);
        }
    }


我的问题是我的“Category”类未被识别,因为 @InitBinder 未被调用。
这里的“秘密”是修改我的“@RequestMapping”方法以在其原型中包含 2 个参数

我不需要:

@ModelAttribute("category") 类别类别,

BindingResult结果

这解决了一切(我知道这不是魔法,只是烟雾、镜子和 Java 反射 - 但我希望

印刷和在线文献将适当地解决像这样的简单用例)。

这是我对应的JSP文件中的相关代码:



        <div>
        Select a category: 
        <form:select path="category">
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name" 

    />
        </form:select>
        </div>

To solve this, I myself have following code in my Controller:



        @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(Category.class, new CategoryEditor(categoryService));
        }

        @ModelAttribute("categoryList") // Populate reference-data (EG select-lists) in the view. (p. 390-

    391).
        public List<Category> populateCategoryList() {
            return categoryService.list();
        }

        // Note: without adding "BindingResult result" to the following prototype
        // (and preceding it with a @ModelAttribute("categoryList") -
        // my initBibder() method does not get called!
        // I discovered and added this hokum in response to the following links:
        // http://forum.springsource.org/showthread.php?46837-InitBinder-not-called
        // http://forum.springsource.org/showthread.php?46876-Custom-date-format-on-GET-requests&p=154820
        @RequestMapping("/site/list.htm")
        @ModelAttribute("sites")  // 20110819
        public ModelAndView listSite(
                @ModelAttribute("category") Category category,
                BindingResult result
                )
        {
    //        List<Site> sites = siteService.list();
            List<Site> sites = new ArrayList<Site>(); // = siteService.list();
            return new ModelAndView("siteList", "sites", sites);
        }
    }


My issues was with my "Category" class not being recognized, because @InitBinder was not being called.
The "secret" here was to modify my "@RequestMapping" method to include - in it's prototype - 2 parameters

which I do not need:

@ModelAttribute("category") Category category,

BindingResult result

This solved everything (I know it's not magic, just smoke, mirrors and Java reflection - but I wish the

printed and online literature would address simple use-cases like this appropriately).

Here's the relevant code in my corresponding JSP file:



        <div>
        Select a category: 
        <form:select path="category">
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name" 

    />
        </form:select>
        </div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文