Its possible to specify the subclass that you need to bind to. You have to add an additional parameter (hidden input) in your form which specify the type that needs to be bound to. This field must have the same name as the model attribute in this case shape. You then need to implement a converter that converts this string parameter value to the actual instance that you need to bind to
The following are the changes that you need to implement
1)In your jsp add the hidden input inside your
<form:form action="/submit" commandName="shape" method="post">
<input type="hidden" name="shape" value="round"/>
//other form tags
</form:form>
2)Implement a Converter to convert from String to a Shape
public class StringToShapeConverter implements Converter<String,Shape>{
public Shape convert(String source){
if("round".equalsIgnoreCase(source)){
return new Round();
}
//other shapes
}
}
3) Then register your converter so that Spring MVC knows about it. If you are using Java config you need to extends WebMvcConfigurerAdapter and override the addFormatters method
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addFormatters(FormatterRegistry registry){
registry.addConverter(new StringToShapeConverter());
}
}
If you are using xml configuration you can use the mvc:annotation-driven element to specify the conversion-service to use. Then register your converter using the FormattingConversionSErviceFactoryBean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="some.package.StringToShapeConverter"/>
</set>
</property>
</bean>
</beans>
Round
from the form – Mug