2016-06-02 34 views
6

I HaveCome associare oggetto sottoclasse in forma primavera presentare come modelAttribute

Class Shape { 
     //Implementation 
} 
Class Round extends Shape{ 
     //Implementation 
} 

controller I Have

@Requestmapping(value="/view/form") 
public ModelAndView getForm(){ 
ModelAndView mav=new ModelAndView(); 
mav.addObject("shape",new Round()); 
} 


@RequestMapping(value="/submit", method = RequestMethod.POST)  
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape){ 
     if(shape instanceof Round){ //**Not giving positive result** 

     } 
    } 

in JSP

<form:form action="/submit" commandName="shape" method="post"> 

//form tags 

</form:form> 

quando mi inviate il formulario con rotonda oggetto. A lato controller ModelAttribute non fornisce l'istanza di Round. il suo esempio di dare solo forma. Come fare questo

+0

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

+0

perché non puoi inviare un 'Round' dal modulo – Priyamal

+0

@Priyamal ci sono più forma e stessa forma per ogni forma. – ssm

risposta

1

Non è possibile farlo. Perché quelli sono due diversi cicli di vita delle richieste.

@Requestmapping(value="/view/form") 
public ModelAndView getForm(){ 
ModelAndView mav=new ModelAndView(); 
mav.addObject("shape",new Round()); 
} 

Quando sopra richiesta viene eseguita, anche se si è aggiunto Round oggetto in mav, è stato convertito in risposta html e rispedito al cliente.

Quindi quando viene richiesta di seguito quando si invia il modulo, è una richiesta completamente separata e Spring non ha modo di identificare quale tipo di oggetto è stato aggiunto per la richiesta precedente.

@RequestMapping(value="/submit", method = RequestMethod.POST)  
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape){ 
     if(shape instanceof Round){ //**Not giving positive result** 

     } 
    } 

Ma si può provare ad esplorare @SessionAttributes, usando questo si potrebbe essere in grado di mantenere lo stesso oggetto attraverso diverse richieste

3

questo non funzionerà mai

<form:form action="/submit" commandName="shape" method="post"> 

si sta presentando un shape dal modulo e in attesa di un nel metodo controller

public ModelAndView submitForm(@ModelAttribute("shape") Shape shape) 

che non fornirà mai un oggetto Round.

Invia semplicemente un oggetto Round dal modulo e utilizzalo.

<form:form action="/submit" commandName="round" method="post"> 
public ModelAndView submitForm(@ModelAttribute("round") Round round) 

cura: -

hanno un tipo hiddenInput nella forma che dirà controller il tipo di Shape sta passando, è possibile modificare il valore di tag nascosto dinamicamente su richiesta dell'utente.

<input type="hidden" name="type" value="round"> 

ottenere il valore del tipo all'interno contoller e utilizzarlo per cast l'Shape oggetto

 public ModelAndView submitForm(
    @ModelAttribute("shape") Shape shape, 
    @RequestParam("type") String type) 
    { 
    if(type.equals("round")){ 
     //if type is a round you can cast the shape to a round 
     Round round = (Round)shape; 
     } 
    } 
0

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>