如何使用RequestMapping将窗体映射到控制器中的两种不同方法?

时间:2014-09-30 04:26:35

标签: java spring jsp spring-mvc web

所以我的Spring MVC项目主页在表单中有两个输入字段。

用户可以输入卷号或名称。

Jsp

<form action="search" method="GET" >
        <div style="text-align: center;">
            <input  type="text" id="regNo" name="regNo" size="30" maxLength="50" "></input> or 
            <input  id="studentName" type="text" size="30" maxLength="50" "></input>
</form>

在我的控制器中,我有两个方法映射到两个输入字段。

@RequestMapping(value ="/search", method = RequestMethod.GET)
    public String getStudent(String regNo, ModelMap model){

        return "A";
    }

    @RequestMapping(value="/search", method = RequestMethod.GET)
    public String searchStudentByName(String studentName, ModelMap model){

        return "B";
    }

由于两个输入字段都是String,我不知道如何将它们映射到控制器中的两种不同方法?

1 个答案:

答案 0 :(得分:2)

你想要这样的东西:

@RequestMapping(method= RequestMethod.GET,value = "/search/r/regNo={regNo}")
public String getStudent(@PathVariable String regNo){

}

表示studentName:

@RequestMapping(method= RequestMethod.GET,value = "/search/s/studentName={studentName}")
public String getStudent(@PathVariable String studentName){

}

然后您需要在不同的form tag中添加两个请求,&amp;在动作标签提供:

如果regNo发送:

/search/r/

代表studentName

/search/s/

Jsp:

<form action="search/r" method="GET" >
        <div style="text-align: center;">
            <input  type="text" id="regNo" name="regNo" size="30" maxLength="50" "></input> 
            <input type="submit" name="approve" value="RegNo" />
</form>    
<form action="search/s" method="GET" >
        <div style="text-align: center;">
            <input  id="studentName" type="text" size="30" maxLength="50" "></input>
            <input type="submit" name="approve" value="StudentName" />
</form>

或第二种方式:

<form action="search" method="GET" >
                <input  type="text" id="regNo" name="regNo" size="30" maxLength="50" "></input> 
                <input  id="studentName" type="text" size="30" maxLength="50" "></input>

                <input type="submit" name="regno" value="regno" />
                <input type="submit" name="studentName" value="studentName" />
</form>

控制器:

@RequestMapping(value = "/search", method = RequestMethod.GET, params = { "regno" })
public String getRegno(@RequestParam String regno) {

}

@RequestMapping(value = "/search", method = RequestMethod.GET, params = { "studentName" })
public String getStudent(@RequestParam String studentName) {

}

发帖给我。