[英]Get URL parameter using Spring
我有 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}/")
獲取確切的 url。
@RequestParam
是從請求中提取查詢參數、表單參數甚至文件,而@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) {....}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.