java - 使用 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>
解决方案
问题是网址。您正在/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) {....}
推荐阅读
- audio - iphone语音备忘录中的m4a文件已损坏
- android-studio - Android Studio 无法初始化类 com.gradle.scan
- windows - Prometheus 从 Windows 抓取 - 无效的指标名称/“INVALID”不是有效的开始令牌
- javascript - 使用 lodash 的“合并”合并(生成 YUP)对象时的意外行为
- c# - 使用 dbcontext 时如何避免 ASP.NET MVC 中的代码冗余
- javascript - 单击按钮时从输入中获取值
- javascript - 使用 JS 提交表单时无限页面重新加载
- r - 为什么 R barplot 可以工作,但 geom_bar 不行?
- automated-tests - 在 create-react-app 中使用 IndexedDB 进行自动化测试
- usrp - 错误:RuntimeError:参考时钟 PLL 未能锁定到内部源