我要在表单中有2个按钮。一个添加孩子的按钮,另一个按钮应该创建家庭,然后转到另一个模板。我的控制器看不到@RequestParam String action
我有这样的东西:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Add Child</title>
</head>
<body>
<p>Add Child or Children</p></br>
<form method="post" action="/addChild">
First Name <input type="text" name="first_name"></br>
Second Name <input type="text" name="second_name"></br>
Sex <input type="text" name="sex"></br>
Pesel <input type="text" name="pesel"></br>
<input type="submit" name= "Add child"value="Add child" ></input>
<input type="submit" name="Create family" value="Create family"></input>
</form>
</body>
</html>
和控制器
@PostMapping(value="addChild", params = "Add child")
public String addChild(@RequestParam("first_name") String firstName,
@RequestParam("second_name") String secondName,
@RequestParam ("sex") String sex,
@RequestParam ("pesel") String pesel,
@RequestParam String action){
if(action.equals("Add child")) {
ChildForm childForm = new ChildForm();
childForm.setFirstName(firstName);
childForm.setSecondName(secondName);
childForm.setSex(sex);
childForm.setPesel(pesel);
childService.addChildToDB(childForm);
return "AddChild";
}else if(action.equals("Create family")){
return "basic";
}
return "AddChild";
}
答案 0 :(得分:0)
每个submit
按钮都会执行<form>
标记中指定的操作。基本上,您添加了两个将执行相同操作的按钮。
您可以为第二个提交按钮(不与第一个共享参数)创建另一个表单元素:
<form method="post" action="/createFamily">
<input type="submit" name="Create family" value="Create family"></input>
</form>
OR
<input type="button" onclick="location.href='/createFamily';" value="Create family" />
OR
<a href="/createFamily" class="button">Create family</a>
在服务中创建另一个入口点,不要将2个端点混合在一起。您正在打破单一职责设计原则,将来会伤害您:
@PostMapping(value="addChild")
public String addChild(@RequestParam("first_name") String firstName,
@RequestParam("second_name") String secondName,
@RequestParam ("sex") String sex,
@RequestParam ("pesel") String pesel){
ChildForm childForm = new ChildForm();
childForm.setFirstName(firstName);
childForm.setSecondName(secondName);
childForm.setSex(sex);
childForm.setPesel(pesel);
childService.addChildToDB(childForm);
return "AddChild";
}
@PostMapping(value="createFamily")
public String createFamily(){
return 'basic';
}