java 如何将参数从jsp传递到spring mvc控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31790426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:07:24  来源:igfitidea点击:

how to pass param from jsp to spring mvc controller

javaspringjspspring-mvc

提问by MdC

My spring mvc controller has a method:

我的 spring mvc 控制器有一个方法:

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public ModelAndView search(@RequestParam("cn") String cn) {
    //do stuff
    return mav;
}

And I have a JSP page, where I'd like to send the value of the string cn:

我有一个 JSP 页面,我想在其中发送字符串 cn 的值:

<html>
 <head><title>Search Entry</title></head>
 <body>
  <h3>Search entry</h3>
  <a href="search"><input type="text" name="cn" value="search">
   <button type="submit">Search</button>
  </a>
  </body>
</html>

I'm sure the jsp has something wrong, now the status message says:

我确定 jsp 有问题,现在状态消息说:

"Request method 'GET' not supported".

“不支持请求方法‘GET’”。

If I delete method = RequestMethod.POST it says:

如果我删除 method = RequestMethod.POST 它说:

"Required String parameter 'cn' is not present; description: The request sent by the client was syntactically incorrect"

“Required String parameter 'cn' is not present;描述:客户端发送的请求在语法上不正确”

回答by Paulius Matulionis

I can see that your are using Spring annotations so what you need to do is to modify your JSP to have a form instead of a link like this:

我可以看到您正在使用 Spring 注释,因此您需要做的是修改您的 JSP 以拥有一个表单而不是这样的链接:

<html>
<head><title>Search Entry</title></head>
<body>
<h3>Search entry</h3>
<form action="search" method="post">
    <input type="text" name="cn" value="search">
    <button type="submit">Search</button>
</form>
</body>
</html>

If you want a GET method to work you need to modify your controller's method to accept GET and change your JSP like this:

如果您希望 GET 方法起作用,您需要修改控制器的方法以接受 GET 并像这样更改您的 JSP:

<html>
<head><title>Search Entry</title></head>
<body>
<h3>Search entry</h3>
  <a href="search?cn=search">
     Search
  </a>
</body>
</html>

If you want your parameter to be not mandatory you can modify your @RequestParamannotation like this:

如果您希望您的参数不是强制性的,您可以像这样修改您的@RequestParam注释:

@RequestParam(value = "cn", required = false) String cn

回答by Paulius Matulionis

you need to Define action="search"inside form tag that should be work

你需要定义action="search"应该工作的内部表单标签

回答by Anand Dwivedi

Change your HTML :

更改您的 HTML :

<html>
<head><title>Search Entry</title></head>
<body>
<h3>Search entry</h3>
<a href="search"><input type="text" name="cn" value="search" action="search">
 <button type="submit">Search</button>
</a>
</body>
 </html>

or else follow this link:

或者点击这个链接: