I Have
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>
when I submit the form with Round object. At controller side ModelAttribute is not giving instance of Round . its giving instance of shape only. How to do this
One of the most important Spring MVC annotations is the @ModelAttribute annotation. @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view.
@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.
Method level ModelAttribute annotation cannot be mapped directly with any request. Let's take a look at the following example for better understanding. We have 2 different methods in the above example.
As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments.
this will never work
<form:form action="/submit" commandName="shape" method="post">
you are submitting a shape
from the form and expecting a shape
in the controller method
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape)
which will never give you an Round
object.
simply submit a Round object from the form and use that.
<form:form action="/submit" commandName="round" method="post">
public ModelAndView submitForm(@ModelAttribute("round") Round round)
edited :-
have a hiddenInput
type in the form which will tell controller
the type of Shape
it is passing, you can change the value of hidden tag dynamically
upon user request.
<input type="hidden" name="type" value="round">
get the value of the type inside contoller
and use it to cast
the Shape
object
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With