【问题标题】:Separating request mappings for Web and REST requests in Spring MVC在 Spring MVC 中分离 Web 和 REST 请求的请求映射
【发布时间】:2016-10-31 11:02:36
【问题描述】:

我有一个 Spring MVC Web 应用程序。现在我想使用 Spring REST 将我的服务公开为 Web 服务。为此,我想根据 URL 值处理 Web 和 REST 请求。下面我对三个控制器进行了相同的尝试,MasterController、PatientController 和 PatientRESTController 如下所示。为简洁起见,已跳过方法。

@Controller("/")
public class MasterController {

@RequestMapping("/web")
public ModelAndView webApplication(){
    return new ModelAndView("redirect:/web/patient");
}

@RequestMapping("/rest")
public ModelAndView webService(){
    return new ModelAndView("redirect:/rest/patient");
}
}

@Controller("/web/patient")
public class PatientController {

@GetMapping("")
public ModelAndView patientHome(){
    ModelAndView mv = new ModelAndView();
    mv.setViewName("patienthome");
    return mv;
}
}

@RestController("/rest/patient")
public class PatientRESTController {

@GetMapping("")
public List getAllPatientsREST(){
    return patientService.findAll();
}
}

在启动我的 Web 应用程序时出现错误:

模糊映射。无法映射“/rest/patient”方法 公共 java.util.List PatientRESTController.getAllPatientsREST() to {[],methods=[GET]}: 已经有 '/web/patient' bean 方法

如何为我的 REST 和 Web 应用程序创建不同的 url 映射?

【问题讨论】:

    标签: java spring rest spring-mvc request-mapping


    【解决方案1】:

    我认为问题出在@GetMapping("") 中的空字符串 根据抛出的异常,它不是相对映射,因为在这两种情况下,Spring 解析的映射对于您的休息控制器都是空的:

    模糊映射。无法将“/rest/patient”方法公开 java.util.List PatientRESTController.getAllPatientsREST() 到 {[],methods=[GET]}: 已经有 '/web/patient' bean 方法

    您应该在 getMapping 注释中指定一个值。你可以试试那个或其他的:

    @RestController
    public class PatientRESTController {
    
     @GetMapping("/rest/patients")
     public List getAllPatientsREST(){
        return patientService.findAll();
     }
    }
    

    就个人而言,我会这样声明我的RestController

    @RestController
    @RequestMapping("/rest/patients")
    public class PatientRESTController {
    
      @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getAll(HttpServletRequest request, HttpServletResponse response) {
         ...
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 2012-07-02
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多