spring-boot - 如何解决控制器配置问题?
问题描述
我的 Spring Boot 项目中的类控制器中的注释有问题。我应该使用什么方法?
@Controller
@RequestMapping("/products")
public class ProductController {
/**
* Only a Test
*/
@Autowired
private ProductService productService;
解决方案
您可能至少应该拥有 CRUD 方法,例如:
@GetMapping
public String index(Model model) {
List<Product> products = productService.searchAll();
model.addAttribute("products", products);
return "product/index";
}
@GetMapping("/addProduct")
public String add(Product product, Model model) {
logger.info("Creating new 'Product' on data source");
this.productService.inserir(product);
return "product/addProduct";
}
@GetMapping("/editProduct/{id}")
public String edit(@PathVariable("id") Long id, Model model) {
logger.info("Find 'Product' Id: {} on data source", id);
Product product = this.productService.searchById(id);
model.addAttribute("product", product);
return "product/editProduct";
}
@GetMapping("/deleteProduct/{id}")
public String delete(@PathVariable("id") Long id, Model model) {
logger.info("Deleting 'Product' Id:{} from data source", id);
this.productService.deletar(id);
return index(model);
}
@PostMapping("/saveProduct")
public String save(@Valid Product product, BindingResult result, Model model) {
if (result.hasErrors()) {
return add(product, model);
}
if (product.getId() != 0) {
logger.info("Updating 'Product' Id: {} on data source", product.getId());
this.productService.atualizar(product);
} else {
logger.info("Creating new 'Product' on data source");
this.productService.inserir(product);
}
return index(model);
}
推荐阅读
- c++ - Pre 8.x 相当于 CUDA 中的 __reduce_max_sync()
- python - 合并 Dask 和 Pandas 时的时区错误
- python - 在单元格中匹配多个单词,而不是始终匹配一个单词
- reactjs - 如何在 React 中使用 useRef 更新高度道具?
- javascript - v-for in array route // vuejs
- node.js - 节点:package.json 中的 Exports 字段不起作用
- python - 对于 pandas DataFrame 列中的每个唯一值,如何随机选择一定比例的行?
- haskell - 关于函数中的返回名称
- typescript - 带有TypeScript的Vue js 3找不到模块'xxxxxx'或其相应的类型声明
- javascript - 猫鼬如何发送交易多个集合