2014-11-21 114 views
0

這裏是我的@ControllerSpring MVC的數據綁定:綁定參數爲對象場不同的名稱

@RequestMapping(value = "/add") 
    public void addMember(Member member) { 
     // ... ... 
    } 

這裏是Member類:

class Member { 
    private Integer id; 
    private String username; 

    // ... ... 
} 

,這裏是請求的URL:

/add?memberId=1&username=bruce 

如何將memberId參數綁定到Member.id f ield? 謝謝!

+0

你不能至少在沒有實現自己的'DataBinder'。 – 2014-11-21 13:02:21

回答

2

如果你不想使用

@RequestMapping(value = "/add") 
public void addMember(@RequestParam(value = "username") String username, ...) { 
    Member member = new Member(username, ...) 
    // ... 
} 

可以實現HandlerMethodArgumentResolver:

public class MemberHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { 
    @Override 
    public boolean supportsParameter(MethodParameter parameter) { 
     return Member.class.equals(parameter.getParameterType()); 
    } 

    @Override 
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, 
     NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { 
     String username = webRequest.getParameter("username"); 
     ... 
     return new Member(username, ...); 
    } 
} 

而且在配置:

<mvc:annotation-driven> 
    <mvc:argument-resolvers> 
     <bean id="memberResolver" class="com.company ... MemberHandlerMethodArgumentResolver"/> 
    </mvc:argument-resolvers> 
</mvc:annotation-driven> 

或JavaConfi G:

@Configuration 
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter { 
... 
    @Override 
    public void addArgumentResolvers(List<Handlermethodargumentresolver> argumentResolvers) { 
     argumentResolvers.add(new MemberHandlerMethodArgumentResolver()); 
    } 
} 
+0

感謝您的回答。我相信這是解決問題的標準方法 – Neo 2014-11-22 02:09:10

0

您可以使用@JsonProperty它的註釋。如下所示。

class Member { 
    @JsonProperty("memberId") 
    private Integer id; 
    private String username; 

    // ... ... 
} 
2

恕我直言,這樣做最簡單的方法是Member類使用額外的二傳手:

class Member { 
    private Integer id; 
    private String username; 

    public Integer getId() { 
     return id; 
    } 
    public void setId(Integer id) { 
     this.id = id; 
    } 
    public void setMemberId(Integer memberId) { // this one should to the trick 
     this.id = memberId; 
    } 

    // ... ... 
} 
+0

感謝您的回答,您的解決方案是最簡單的解決方案。 – Neo 2014-11-22 02:07:47