Multiple requestmapping value with path variables

前端 未结 4 1891
北海茫月
北海茫月 2021-02-03 10:08
@RequestMapping(value = {\"/abcd\", \"/employees/{value}/{id}\"})
public String getEmployees(
      @PathVariable(value = \"value\") String val, 
      @PathVariable(val         


        
4条回答
  •  灰色年华
    2021-02-03 10:45

    Just found a way to do this without using multiple methods.

    First create a simple class to hold the path variables:

    public class EmployeesRequest {
      private String value;
      private String id;
    
      public String getValue() {
        return this.value;
      }
    
      public void setValue(String value) {
        this.value = value;
      }
    
      public String getId() {
        return this.id;
      }
    
      public void setId(String id) {
        this.id = id;
      }
    }
    

    Then define your controller method like this:

    @RequestMapping(value={
      "/abcd",
      "/employees/{value}/{id}"
    })
    public String getEmployees(@RequestParam(value="param", required=false) String param,
                               EmployeesRequest request) {
      if (request.getValue() != null) {
        // do something
      } else {
        // do something else
      }
    }
    

    Spring will automatically map any path variables available to the EmployeesRequest class. Spring will also do this for any request parameters so you can simplify things further by adding the request parameter to EmployeesRequest:

    public class EmployeesRequest {
      private String value;
      private String id;
      private String param;
    
      public String getValue() {
        return this.value;
      }
    
      public void setValue(String value) {
        this.value = value;
      }
    
      public String getId() {
        return this.id;
      }
    
      public void setId(String id) {
        this.id = id;
      }
    
      public String getParam() {
        return this.param;
      }
    
      public void setParam(String param) {
        this.param = param;
      }
    }
    

    And then finally:

    @RequestMapping(value={
      "/abcd",
      "/employees/{value}/{id}"
    })
    public String getEmployees(EmployeesRequest request) {
      if (request.getValue() != null) {
        // do something
      } else {
        // do something else
      }
    }
    

    An added benefit of this solution is that now you can support both variables or request parameters. Meaning all of these would be valid:

    • /abcd
    • /abcd?param=123
    • /abcd?value=123&id=456¶m=789
    • /employees/123/456
    • /employees/123/456?param=123

提交回复
热议问题