gpt4 book ai didi

java - 使用@RequestParam时不支持请求方法 'POST'

转载 作者:行者123 更新时间:2023-12-01 19:47:48 24 4
gpt4 key购买 nike

我正在使用 Spring MVC。并收到此错误:不支持请求方法“POST”

Java

@RequestMapping(value = "/jdbcInsertGuest", method = RequestMethod.POST)
public void jdbcInsertGuest(@RequestParam(value = "guestName") String guestName, @RequestParam(value="comment") String comment) {
Guest guest = new Guest();
guest.setGuestName(guestName);
guest.setComment(comment);
jdbcExample.insertGuest(guest);
}

JSP

<form name="jdbcInsertGuest" method="POST">
<table>
<tr>
<td><b>Name: </b></td>
<td><input type='text' name='guestName'/></td>
</tr>
<tr>
<td><b>Comment: </b></td>
<td><input type='text' name="comment"/></td>
</tr>
</table>

<button>Send</button>
</form>

当我将方法更改为 GET 时,出现此错误:所需的字符串参数“guestName”不存在

如何解决这个问题?

最佳答案

进行以下更改,

  1. 在表单中添加action="/URL"属性,该属性将表单事件与spring mvc Controller 中的相关方法映射
  2. 将表单name (jdbcInsertGuest)更改为guest,此数据模型传递给post方法
  3. 使用@ModelAttribute,该注解将表单数据与相关模型绑定(bind)

JSP,

<form name="guest" action="/jdbcInsertGuest" method="POST">
<table>
<tr>
<td><b>Name: </b></td>
<td><input type='text' name='guestName'/></td>
</tr>
<tr>
<td><b>Comment: </b></td>
<td><input type='text' name="comment"/></td>
</tr>
</table>

<button>Send</button>

MVC Controller ,

@RequestMapping(value = "/jdbcInsertGuest", method = RequestMethod.POST)
public void jdbcInsertGuest(@ModelAttribute("guest") Guest guest) {
jdbcExample.insertGuest(guest);
}

POJO(Guest.java),

public class Guest {

private String guestName;
private String comment;

public String getGuestName() {
return guestName;
}
public void setGuestName(String guestName) {
this.guestName = guestName;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}

谢谢

关于java - 使用@RequestParam时不支持请求方法 'POST',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com