首页 > 解决方案 > 如何在 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")) 中配置的页面。如何让第一个方法调用第二个方法并重定向到视图?

标签: springspring-mvcmodel-view-controller

解决方案


让第一个方法返回一个字符串并返回一个重定向到第二个方法,如下所示:

@PostMapping("**/filtrarprodutospreco")
public String preprocessamentoprodutos(Pageable pageable, FiltroProdutosDto filtro) {
    filtro.setFiltrarPor("1");
    filtro.setItensPorPag("12");      
    filtrarProdutos(pageable, filtro);        
    return "redirect:/filtrarprodutos";
}

推荐阅读