题目
Spring MVC中如何定义一个处理HTTP GET请求的方法?
信息
- 类型:问答
- 难度:⭐
考点
控制器定义,请求映射注解,HTTP方法映射
快速回答
在Spring MVC中处理GET请求需要:
- 使用
@Controller或@RestController标记类 - 在方法上添加
@GetMapping注解指定URL路径 - 方法返回值可以是视图名称(字符串)或直接响应数据
原理说明
Spring MVC通过注解将HTTP请求映射到Java方法:@Controller标识类为控制器,@GetMapping将GET请求与方法绑定。DispatcherServlet根据请求URL找到对应方法执行。
代码示例
@Controller // 或 @RestController(返回JSON时)
@RequestMapping("/products")
public class ProductController {
// 处理 /products/list 的GET请求
@GetMapping("/list")
public String listProducts(Model model) {
model.addAttribute("products", productService.getAll());
return "product-list"; // 返回视图名称
}
// REST风格示例
@GetMapping("/{id}")
@ResponseBody // 若类用@Controller需此注解返回数据
public Product getProduct(@PathVariable Long id) {
return productService.findById(id);
}
}最佳实践
- 优先使用
@GetMapping而非通用@RequestMapping(method=GET) - 类级别用
@RequestMapping定义公共路径 - REST API推荐使用
@RestController免写@ResponseBody - 使用
@PathVariable获取URL参数
常见错误
- 忘记添加
@Controller导致类不被扫描 - 在
@Controller类中返回JSON时漏写@ResponseBody - URL路径冲突(如两个方法映射相同URL)
- 混淆
@RequestParam(查询参数)和@PathVariable(路径参数)
扩展知识
- 其他HTTP方法:
@PostMapping,@PutMapping,@DeleteMapping - 参数绑定:
@RequestParam获取查询参数,@RequestBody接收JSON - 视图技术:返回字符串时默认使用Thymeleaf等模板引擎解析
- 注解组合:
@RestController = @Controller + @ResponseBody