E 'possibile specificare la sottoclasse che è necessario associare. Devi aggiungere un parametro aggiuntivo (input nascosto) nel tuo modulo che specifica il tipo a cui devi essere associato. Questo campo deve avere lo stesso nome dell'attributo del modello in questo caso.È quindi necessario implementare un convertitore che converte questo valore del parametro stringa per l'istanza effettivo che avete bisogno di legarsi a
Le seguenti sono le modifiche che è necessario implementare
1) Nel tuo jsp aggiungere l'input nascosto all'interno del vostro
<form:form action="/submit" commandName="shape" method="post">
<input type="hidden" name="shape" value="round"/>
//other form tags
</form:form>
2) Implementare un convertitore per convertire da stringa a una forma
public class StringToShapeConverter implements Converter<String,Shape>{
public Shape convert(String source){
if("round".equalsIgnoreCase(source)){
return new Round();
}
//other shapes
}
}
3) quindi registrare il convertitore in modo che Spring MVC ne è a conoscenza. Se si utilizza Java config è necessario estende WebMvcConfigurerAdapter e l'override del metodo addFormatters
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addFormatters(FormatterRegistry registry){
registry.addConverter(new StringToShapeConverter());
}
}
Se si sta utilizzando la configurazione XML è possibile utilizzare il MVC: elemento annotation-driven per specificare la conversione-servizio da utilizzare. Quindi registrare il convertitore utilizzando 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>
fonte
2016-06-03 08:01:48
Il tipo statico è Shape indipendentemente da ciò che si fa. Questo non ha nulla a che fare con Spring; questo è un problema con la tipizzazione statica/dinamica. Puoi lanciare o creare un factory/virtual constructor. – duffymo
perché non puoi inviare un 'Round' dal modulo – Priyamal
@Priyamal ci sono più forma e stessa forma per ogni forma. – ssm