controller要写什么
时间: 2024-03-15 09:44:39 浏览: 14
针对上面的Service层代码,我们可以编写一个Controller层的代码,来处理请求并返回数据给前端。
具体实现如下:
```
import com.example.demo.entity.Category;
import com.example.demo.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping("/list")
public List<Category> getAllCategories() {
return categoryService.getAllCategories();
}
}
```
在上述代码中,我们使用了@RestController注解声明了一个RestController,同时使用@RequestMapping注解声明了请求路径为"/category"。接着,我们编写了一个getAllCategories方法,并使用@GetMapping注解声明了请求路径为"/list",用于获取所有的分类数据。在方法中,我们调用Service层的getAllCategories方法,并将查询结果返回给前端。