Thomas
Thomas

Reputation: 2767

Is it possible to have a spring model object as the value of spring form?

I basically have the following jsp which retrieves the advertisement objects which came with the spring model advertisement list ${myAdverts}.

And I would like that when one of those is clicked, a post request is submitted back to my controller but with an instance of the advertisement object. Is that somehow possible?

here is my JSP code:

<xc:forEach var="advertisement" items="${myAdverts}" varStatus="stats">
    <li>

    <a class="furtherinfo-link" onclick="javascript:submitJoin(${stats.count})" >${advertisement.getName()}</a>
    </li>
</xc:forEach>
<form:form id="myform" method="POST" action="form_submit.html" commandName="myForm" name="MyForm">
 <form:input id="advertisementObj" path="advertisementObj" type="hidden"/>
 </form:form>

here is my attempt to send the post back with javascript inspired by the handling of autopopulating lists in spring MVC and javascript:

javascript code

 <script src="js/webmenu_nav.js"></script>

<script type="text/javascript">
      function submitJoin(position){
        $('#advertisementObj').val("myAdverts["+position+"]");

        document.MyForm.submit();
      }

</script>

The current behavior of that code is that I always get an empty advertisementObj on my post method in my Controller object.

The controller object is very simple, but just in case here it is part of its code:

@Controller
public class MyController {

@RequestMapping(value="/show_advertisements.html",method = RequestMethod.GET)
public ModelAndView showAdv(@RequestParam(value="response", required=false) String incomingResponse) {

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("response", incomingResponse);

    List<AdvertisementRecord> adverts = methodThatReturnsList();
    model.put("myAdverts", adverts);

    MyForm jform = new MyForm();
    model.put("myForm", jform);

    return new ModelAndView("show_advertisements", model) ;
}

@RequestMapping(value = "/form_submit.html", method = RequestMethod.POST)
public ModelAndView formSubmit(MyForm myForm,  BindingResult result, Map model){


    if(null != myForm.getAdvertisement())
        return showPage("adver " + myForm.getAdvertisement().getId());
    else
        return showPage("null advertisement on join");


}

 }

Solution!!

snippets of the solution code

JSP code:

<xc:forEach var="advertisement" items="${myAdverts}" varStatus="stats">
    <li>
    <a class="furtherinfo-link" onclick="javascript:submitForm(${stats.count})" >${advertisement.getName()}</a>
    </li>
</xc:forEach>
<form:form method="POST" id="theForm" action="form_submit.html" modelAttribute="myAdverts" name="MyForm">
</form:form>    

javascript:

<script src="js/webmenu_nav.js"></script>

    <script type="text/javascript">
          function submitForm(position){
           $('#theForm').attr("action","form_submit.html?position="+position);

            document.MyForm.submit();
          }

    </script>

</head> 

controller:

 @Controller
 @SessionAttributes("myAdverts")
public class MyController {

@RequestMapping(value="/show_advertisements.html",method = RequestMethod.GET)
public ModelAndView showAdv(@RequestParam(value="response", required=false) String incomingResponse) {

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("response", incomingResponse);

    List<AdvertisementRecord> adverts = methodThatReturnsList();
    model.put("myAdverts", adverts);

    //MyForm jform = new MyForm();
    //model.put("myForm", jform);

    return new ModelAndView("show_advertisements", model) ;
}

@RequestMapping(value = "/form_submit.html", method = RequestMethod.POST)
public ModelAndView formSubmit(@RequestParam("position") final int position, @ModelAttribute("adverts") @Valid List<AdvertisementRecord> adverts,  BindingResult result, Map model){


    if(null != adverts && null != adverts.get(position))
        return showPage("adver " + adverts.get(position).getId());
    else
        return showPage("null advertisement ");


}

 }

Be aware on the code above, that it is important to have the request param coming first in the signature as Im calling "form_submit.html?position="+position"

Upvotes: 1

Views: 4305

Answers (2)

Yevgeniy
Yevgeniy

Reputation: 2694

objects you put in your model are only there for the current request by default. It means your myAdverts list is not there any more in the second request (i.e. the POST request). However you can use @SessionAttribute annotation to tell spring mvc to store objects in the http-session, so you can access them in further requests.

your controller could look like this:

@Controller
@SessionAttributes("myAdverts")
public class MyController {
    @RequestMapping(value="...", method=RequestMethod.GET)
    public void get(ModelMap model){
        List myAdverts = // get your list of adverts.
        model.put("myAdverts", myAdverts)
    }

    @RequestMapping(value="...", method=RequestMethod.POST)
    public void post(@RequestParam("position") final int position, @ModelAttribute("myAdverts") List myAdverts,SessionStatus sessionStatus){
        myAdverts.get(position);
        // ...

        // tell spring to remove myAdverts from session
        sessionStatus.setComplete();
    }
}

for more information on @SessionAttribute take a look here.

Upvotes: 2

Boris Treukhov
Boris Treukhov

Reputation: 17774

If advertisements have some kind of unique id and stored in a DAO(or there's another way to get an Advertisement from id), you can implement a converter that will take String argument and converts it back to the Advertisement

public class StringToAdvertisementConverter implements Converter<String, Advertisement> {

    private AdvertisementRepository advertisementRepository

    @Autowired
    public setAdvertisementRepository(AdvertisementRepository repository){
        this.advertisementRepositort = repository;
    }

    @Override
    public Advertisement convert(String id) { 

         return advertisementRepository.lookup(id);
    }

}

after registering converter in the conversion service

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService"
      class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="my.StringToAdvertisementConverter"/>
        </set>
    </property>

your controller will be able to accept Advertisement class as a parameter of the @RequestParam and similar annotations:

    @RequestMapping(method = RequestMethod.POST, value = "/SomeMapping")
    public String handleSomething(@RequestParam(required = false) Advertisement advert,
        ModelMap model) {}

As an alternative, you can achieve the same results with PropertyEditors, there's a good question on topic with a lot of links to the Spring documentation.

Upvotes: 0

Related Questions