spring - 如何在 Spring MVC 中同一控制器的另一个方法中调用同一控制器的方法
问题描述
我有这个方法映射
@PostMapping("**/filtrarprodutospreco")
public void preprocessamentoprodutos(Pageable pageable, FiltroProdutosDto filtro) {
filtro.setFiltrarPor("1");
filtro.setItensPorPag("12");
filtrarProdutos(pageable, filtro);
}
处理完数据后,我想使用第二种方法的参数的这些对象(可分页和过滤器)调用此其他方法:
@PostMapping("**/filtrarprodutos")
public ModelAndView filtrarProdutos(Pageable pageable, FiltroProdutosDto filtro) {
ModelAndView model = new ModelAndView("product");
Categoria categoria = categoriaRepository.findById(filtro.getCategoriaId()).get();
if(filtro.getPrecoDe() == null) {
filtro.setPrecoDe(0D);
}
if(filtro.getPrecoAte() == null) {
filtro.setPrecoAte(1000000000D);
}
if(filtro.getFiltrarPor().contains("1")){
model.addObject("produtos", produtoRepository.filtroProdutos(categoria, filtro.getPrecoDe(), filtro.getPrecoAte(), PageRequest.of(0, Integer.parseInt(filtro.getItensPorPag()), Sort.by("nome"))));
}else {
model.addObject("produtos", produtoRepository.filtroProdutos(categoria, filtro.getPrecoDe(), filtro.getPrecoAte(), PageRequest.of(0, Integer.parseInt(filtro.getItensPorPag()), Sort.by("precoNovo"))));
}
model.addObject("id", filtro.getCategoriaId());
model.addObject("categorias", categoriaRepository.findAll());
model.addObject("filtro", filtro);
return model;
}
第二种方法使用 ModelAndView 来重定向页面,所以我想被第一种方法调用。Spring 使用对象调用第二个方法,第二个方法获取这些对象并返回到 (ModelAndView model = new ModelAndView("product")) 中配置的页面。如何让第一个方法调用第二个方法并重定向到视图?
解决方案
让第一个方法返回一个字符串并返回一个重定向到第二个方法,如下所示:
@PostMapping("**/filtrarprodutospreco")
public String preprocessamentoprodutos(Pageable pageable, FiltroProdutosDto filtro) {
filtro.setFiltrarPor("1");
filtro.setItensPorPag("12");
filtrarProdutos(pageable, filtro);
return "redirect:/filtrarprodutos";
}
推荐阅读
- shutdown - 关闭并重新启动后如何从停止的位置启动程序
- applescript - 如果没有输入操作,如何在超时后自动执行带有 2 个按钮的对话框输入?
- jquery - 如果字符串包含 0 或负值更改文本
- javascript - 响应式菜单在网站上不起作用
- c# - 检查两个值的空字符串或空字符串 C#
- javascript - Jquery选择特定的表格单元格并填充列表
- rest - AppSync 批量调用嵌套属性
- python-3.x - 不断收到错误“OSError:[WinError 193] %1 不是有效的 Win32 应用程序”
- android - Android:从矢量 xml 中提取 android:pathData
- python - 有没有办法从所有 30 个数据框中只提取一列?