springboot获取路径上的id

本文详细介绍了SpringMVC框架中实现员工信息删除功能的方法,通过使用@PathVariable注解来捕获URL路径中的参数,进而调用DAO层的删除方法,完成数据的更新操作。
//员工删除
    @RequestMapping("/emp1/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

@PathVariable(“id”)用这个就可以获取路径上的id变量,并赋值给后面的Integer id

在 Spring Boot 应用中,可以通过多种方式获取 URL 路径中的查询参数。例如,对于 URL `http://localhost:8080/user/modify?userId=12` 中的 `userId=12` 查询参数,可以使用以下方法进行提取: ### 通过 `HttpServletRequest` 获取 可以在 Controller 的方法中注入 `HttpServletRequest` 对象,并调用其 `getParameter()` 方法来获取查询参数: ```java import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/user") public class UserController { @RequestMapping("/modify") public String modifyUser(HttpServletRequest request) { String userId = request.getParameter("userId"); return "Received userId: " + userId; } } ``` ### 通过 `@RequestParam` 注解直接绑定 Spring Boot 提供了更简洁的方式,可以直接通过 `@RequestParam` 注解将查询参数映射到方法参数中: ```java import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user") public class UserController { @RequestMapping("/modify") public String modifyUser(@RequestParam("userId") String userId) { return "Received userId: " + userId; } } ``` 如果希望参数为可选,可以设置 `required=false`,例如: ```java @RequestParam(name = "userId", required = false) String userId ``` ### 获取路径变量和查询参数组合 如果 URL 包含路径变量(Path Variable)和查询参数(Query Parameter)的组合,也可以分别提取: ```java import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @GetMapping("/{id}/modify") public String modifyUser( @PathVariable("id") String id, @RequestParam("userId") String userId) { return "Path variable id: " + id + ", Query parameter userId: " + userId; } } ``` 在这个例子中,访问 `/user/55/modify?userId=12` 将会同时提取路径中的 `id=55` 和查询参数中的 `userId=12`。 ### 处理多个相同名称的查询参数 如果存在多个相同名称的查询参数,例如 `http://localhost:8080/user/modify?userId=12&userId=15`,可以使用数组或集合接收: ```java @GetMapping("/modify") public String modifyUser(@RequestParam("userId") String[] userIds) { return "Received userIds: " + String.join(", ", userIds); } ``` 这些方法适用于大多数场景,并且能够很好地与 Spring Boot 的 MVC 架构集成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值