簡體   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