spring框架:如何用两个post请求控制html页面?post请求不会返回正确的html页

wgeznvg7  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(300)

我试图从一个数据库中获取一个雇员的信息,该数据库在html页面中有一个用户输入的id号 hello.html 并在另一个html文件中显示该信息 helloResponseDB.html ,但似乎当我提交id号时,它会引导我进入不同的html页面 helloResponse.html ,显示用户输入的单词。你能帮我吗?
控制器代码:

import org.springframework.stereotype.Controller;

    import org.springframework.ui.Model;

    import org.springframework.web.bind.annotation.GetMapping;

    import org.springframework.web.bind.annotation.PostMapping;

    import org.springframework.web.bind.annotation.RequestParam;

    import org.springframework.beans.factory.annotation.Autowired;

    @Controller

    public class HelloController {

        @Autowired
        private HelloService helloService;

        @GetMapping("/hello")
        public String getHello() {
            return "hello";
        }

        @PostMapping("/hello") 
        public String 
        postRequest(@RequestParam(name="text1",required=false)String str, Model model) {
            model.addAttribute("sample",str);
            return "helloResponse";
        }

        @PostMapping("/hello/db")
        public String 
        postDbRequest(@RequestParam(name="text2")String str, Model model) {
            int id = Integer.parseInt(str);
            Employee employee = helloService.findOne(id);
            model.addAttribute("id",employee.getEmployeeId());
            model.addAttribute("name",employee.getEmployeeName());
            model.addAttribute("age",employee.getAge());
            return "helloResponseDB";
        }
    }

您好.html:

<!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <metacharset="UTF8"></meta>
        <title>Hello World</title>
    </head>
    <body>
        <h1>Hello World</h1>

        <form method="post" action="/hello">
            Enter a word:
            <input type="text" name="text1 th:value="${text1_value}"/>
            <input type="submit" value="Click"/>
        </form>

        <br/>

        <form method="post" actioin="/hello/db">
            Enter Employee's ID:
            <input type="number" name="text2" th:value="${text2_value}"/>
            <input type="submit" value="Click"/>
        </form>

    <body>
    </html>
3pvhb19x

3pvhb19x1#

首先,你在你的第二个表格中纠正动作拼写 hello.html 同时使用 th:action 就像你用的一样。此外,您还没有关闭 name="text1" 以你的第一种形式。即

<input type="text" name="text1 th:value="${text1_value}"/>

把它改成

<input type="text" name="text1" th:value="${text1_value}"/>
<form th:action="@{/hello}" method="post">
            Enter a word:
            <input type="text" name="text1" th:value="${text1_value}">
            <input type="submit" value="Click">
        </form>

        <br/>

        <form  th:action="@{/hello/db}" method="post" >
            Enter Employee ID:
            <input type="number" name="text2" th:value="${text2_value}" >
            <input type="submit" value="Click" >
        </form>

相关问题