Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

java - Passing parameters from JSP to Controller in Spring MVC

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 uses @ModelAttribute to retrive the model object in the handler method.

How do I go about passing other parameters (not present in the Model object) from the JSP to Controller? Do I use JavaScript to do this? Also can someone clarify what the HttpServletRequest object should be used for.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...