spring mvc form:select tag

前端 未结 1 2027
庸人自扰
庸人自扰 2021-02-03 09:58

I have a Model that holds a list of Countries (List) and a user object that holds a Country object. I have a view that the user can select his country.
This is snippet of

1条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 10:35

    You need to somehow tell Spring to convert a String to a Country. Here is an example :

    @Component
    public class CountryEditor extends PropertyEditorSupport {
    
        private @Autowired CountryService countryService;
    
        // Converts a String to a Country (when submitting form)
        @Override
        public void setAsText(String text) {
            Country c = this.countryService.findById(Long.valueOf(text));
    
            this.setValue(c);
        }
    
    }
    

    and

    ...
    public class MyController {
    
        private @Autowired CountryEditor countryEditor;
    
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(Country.class, this.countryEditor);
        }
    
        ...
    
    }
    

    0 讨论(0)
提交回复
热议问题