繁体   English   中英

形式为SpringMVC的两个按钮

[英]Two buttons in form SpringMVC

我要在表单中有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";
}

每个submit按钮将执行<form>标记中指定的操作。 基本上,您添加了两个将执行相同操作的按钮。

您可以为第二个提交按钮创建另一个表单元素(它与第一个提交按钮不共享参数):

<form method="post" action="/createFamily">
    <input type="submit" name="Create family" value="Create family"></input>
</form>

要么

<input type="button" onclick="location.href='/createFamily';" value="Create family" />

要么

<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';    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM