首页 > 解决方案 > 使用 Spring 获取 URL 参数

问题描述

我有 Spring 应用程序,我想在 URL 中设置参数并转发到 URL。例如,我点击 index.html 中的“显示详细信息”。然后转到 /employees/show/1111。ShowController.java 得到 1111。现在我点击“显示详细信息”,结果是白页错误。我设置了断点 ShowController.java,断点不能不工作。我应该在哪里修复它?

控制器

@Controller
@RequestMapping("/employees/show/{employee.empId}/")
public class ShowController {

    @Autowired
    EmployeeService empService;

    @GetMapping
    public String details(@RequestParam("empId") String empId, Model model) {
        Employee employee = empService.getEmployeeInfo(Long.parseLong(empId)); // break point at this row
        model.addAttribute("employee", employee);
        return "view/show";
    }

索引.html

<body>
    <table>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th></th>
        </tr>
        <tr th:each="employee : ${employees}">
            <td th:text="${employee.empId}"></td>
            <td th:text="${employee.empName}"></td>
            <td><a th:href="@{'/employees/show/' + ${employee.empId}}">Show detail</a></td>
        </tr>
    </table>
    <br>
</body>

显示.html

<body>
            <div th:text="${employee.empId}"></div>
            <div th:text="${employee.empName}"></div>
</body>

这个文件夹结构。 在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

标签: javaspringthymeleaf

解决方案


问题是网址。您正在/employees/show/{employee.empId}/用作基本网址。并且@GetMapping没有映射到任何 url,因此它从@RequestMapping("/employees/show/{employee.empId}/").

@RequestParam是从请求中提取查询参数、表单参数,甚至是文件,while@PathVariable用于告诉 Spring URI 路径的一部分是你想要传递给你的方法的值。

因此,在您的情况下,它看起来很复杂,您使用@RequestParam的是@PathVariable.

@Controller
@RequestMapping("/employees/show/{employee:.*}/") //since spring will skip anything after a dot(.)
....

@GetMapping
public String details(@PathVariable("empId") String empId, Model model) {....}

推荐阅读