Spring MVC 之 Restful 风格请求⽀持
    		       		warning:
    		            这篇文章距离上次修改已过425天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@RestController
@RequestMapping("/api/items")
public class ItemController {
 
    // 假设这是一个服务组件,用于处理业务逻辑
    @Autowired
    private ItemService itemService;
 
    // 获取所有商品列表(Restful风格的查询所有)
    @GetMapping
    public ResponseEntity<List<Item>> queryAllItems() {
        List<Item> items = itemService.queryAll();
        if (items.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(items, HttpStatus.OK);
    }
 
    // 根据关键字查询商品列表(Restful风格的查询)
    @GetMapping("/search")
    public ResponseEntity<List<Item>> searchItemsByKeyword(@RequestParam String keyword) {
        List<Item> items = itemService.searchByKeyword(keyword);
        if (items.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(items, HttpStatus.OK);
    }
 
    // 根据ID查询商品详情(Restful风格的查询单个)
    @GetMapping("/{id}")
    public ResponseEntity<Item> queryItemById(@PathVariable("id") Integer id) {
        Item item = itemService.queryById(id);
        if (item == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(item, HttpStatus.OK);
    }
}这个代码示例展示了如何在Spring MVC中使用@RestController和@GetMapping注解来创建支持Restful风格的控制器。它提供了三个基本的Restful操作:获取所有商品列表、根据关键字查询商品列表和根据ID查询商品详情。对于查询操作,它返回了相应的HTTP状态码,如HttpStatus.OK或HttpStatus.NO_CONTENT,以表示请求的结果。
评论已关闭