Bind Path variables to a custom model object in spring

前端 未结 3 1753
無奈伤痛
無奈伤痛 2020-11-30 07:39

I have a class that models my request, something like

class Venue {
    private String city;
    private String place;

    // Respective getters and setters         


        
3条回答
  •  悲哀的现实
    2020-11-30 08:12

    You could provide an implementation of the HandlerMethodArgumentResolver interface. This interface is mainly used to resolve arguments to your controller methods in ways that Spring can't (which is essentially what you are trying to do). You accomplish this by implementing these two methods:

    public boolean supportsParameter(MethodParameter mp) {
        ...
    }
    
    public Object resolveArgument(mp, mavc, nwr, wdbf) throws Exception {
        ...
    }
    

    You can inject your implementation into the Spring context via:

    
        
            
        
    
    

    When Spring encounters a parameter it can't resolve, it will call your method supportsParameter() to see if your resolver can resolve the parameter. If your method returns true, then Spring will call your resolveArgument() method to actually resolve the parameter. In this method, you have access to the NativeWebRequest object, which you can use to grab the path beyond the contextPath. (in your case it would be: /venue/{city}/{place}) you can parse through the request path and attempt to get the city/place Strings to populate in your Venue Object.

提交回复
热议问题