Passing parameters from JSP to Controller in Spring MVC

前端 未结 2 721
情深已故
情深已故 2020-12-03 11:28

I am trying out a sample project using Spring MVC annotated Controllers. All the examples I have found online so far bind the JSP to a particular model and the controller us

相关标签:
2条回答
  • 2020-12-03 12:15

    Just remove the "path" from the jsp input tag and use HttpServletRequest to retrieve the remaining data.

    For example I have a bean like

    public class SomeData {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    Then in the jsp i will have the additional data fields to be send in normal html tag

    <form:form method="post" action="somepage" commandName="somedata">
        <table>
        <tr>
            <td>name</td>
            <td><form:input path="name" /></td>
        </tr>
        <tr>
            <td>age</td>
            <!--Notice, this is normal html tag, will not be bound to an object -->
            <td><input name="age" type="text"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="send"/>
            </td>
        </tr>
    </table>
    </form:form>
    

    Notice, the somedata bean has the name field the age is not. So the age field is added without "path". Without the path attribute the object property wont be bound to this field.

    on the Controller i will have to use the HttpServletRequest like,

    @RequestMapping("/somepage")
    public String someAction(@ModelAttribute("somedata") SomeData data, Map<String, Object> map,
                                    HttpServletRequest request) {
    
           System.out.println("Name=" + data.getName() + " age=" + request.getParameter("age"));
    
           /* do some process and send back the data */
            map.put("somedata", data);
            map.put("age", request.getParameter("age"));
    
            return "somepage";
       }
    

    while accessing the data on the view,

    <table>
        <tr>
            <td>name</td>
            <td>${somedata.name}</td>
        </tr>
        <tr>
            <td>age</td>
            <td>${age}</td>
        </tr>
     </table>
    

    somedata is the bean which provides the name property and age is explicitly set attribute by the controller.

    0 讨论(0)
  • 2020-12-03 12:20

    If one doesn't want to create another class (bean) though it should be there, then apart from @ModelAttrbute one can also use @RequestParam.

    public String someAction(@RequestParam("somedata") String data)
    {
    ------
    }
    
    0 讨论(0)
提交回复
热议问题