manu
manu

Reputation: 77

how to pass a value from jsp to controller

I have some code in JSP as below:

<c:iterate name="list" id="payment" index="idx">
<tr class="gRowEven"
  _paid="<c:write name="payment" property="paid"/>">

Now my problem is that I want to call a method in a controller based on the variable _paid. I can do a request.setAttribute("_paid", _paid)

I am assuming it would work. But I am not supposed to do it that way. So I was wondering if there is any other way to do it?

Upvotes: 1

Views: 33618

Answers (1)

su-
su-

Reputation: 3166

You can pass that value to a hidden input field (on form submit)

<form action='your controller' method='POST'>
    ...
    <input type='hidden' id='newfield' name='newfield' value=''/>
</form>

then you controller can retrieve its value (using request.getParameter('newfield'), or a MVC framework provided method)


Or simply append to the URL if your controller takes GET request


By the way,

request.setAttribute("_paid",_paid);

probably won't work for you. Because this call is only executed when page is loaded, not when you submit the page. Also, when you submit a page, it will have a new fresh request


Edit: (this is what I meant by saying 'pass that value to a hidden input field (on form submit)')

<script type='text/javascript'>
    function updateHiddenField() {
        var trPaid = document.getElementById('trPaid'); //assume tr field's id is trPaid
        //if tr doesn't have an id, you can use other dom selector function to get tr 
        //element, but adding an id make things easier
        var value = trPaid.getAttribute('_paid');
        document.getElementById('newfield').value = value;
        document.getElementById('form1').submit();
        return false;
    }
</script>

<form action='your controller' id='form1' method='POST'  
        onsubmit='javascript:updateHiddenField();'>
    ...
</form>

Then _paid's value will be passed with request in newfield parameter


And here's how you get the parameter when you are using Spring MVC

@Controller
@RequestMapping("/blah")
public class MyController {

    @RequestMapping(value="/morepath" method = RequestMethod.POST)
    public ModelAndView test(@RequestParam("newfield") int paid) {
        logger.debug("here's the value of paid: " + paid);
    }
 ...

Upvotes: 5

Related Questions