Dropdown value binding in Spring MVC

前端 未结 1 837
情话喂你
情话喂你 2021-01-04 21:49

I am new to Spring MVC. I am writing an app that uses Spring, Spring MVC and JPA/Hibernate I don\'t know how to make Spring MVC set a value coming from a dropdown into a mod

相关标签:
1条回答
  • 2021-01-04 22:16

    The trick as you have already noted is to register a custom converter which will convert the id from the drop down into a Custom instance.

    You can write a custom converter this way:

    public class IdToCustomerConverter implements Converter<String, Customer>{
        @Autowired CustomerRepository customerRepository;
        public Customer convert(String id) {
            return this.customerRepository.findOne(Long.valueOf(id));
        }
    }
    

    Now register this converter with Spring MVC:

    <mvc:annotation-driven conversion-service="conversionService"/>
    
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
           <list>
              <bean class="IdToCustomerConverter"/>
           </list>
        </property>
    </bean>
    
    0 讨论(0)
提交回复
热议问题