我想创建一个控制器方法,可以从 html 表单或使用 resttemplate 的独立客户端调用。
该方法具有以下签名:
@RequestMapping(method = RequestMethod.POST)
public ModelAndView save(@RequestBody @ModelAttribute(value = "itemCreateRequest")
ItemCreateRequest request, Model model) throws NoSuchMethodException,
SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
...
}
问题是,如果我使用 HTML 表单,一切正常,但是当我尝试使用独立客户端时,请求参数中的值为空。
ItemCreateRequest icr = new ItemCreateRequest();
icr.setItem(new ItemDTO(null, "23", "bla", "bla bla"));
restTemplate.postForLocation("http://localhost:8080/ims_ui/items.xml", icr);
如果我尝试没有 @ModelAttribute 的方法,则独立客户端可以工作,但 HTML 表单不能。
这是我的 servlet-context.xml 的配置
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<beans:bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<beans:property name="marshaller" ref="marshaller"/>
<beans:property name="unmarshaller" ref="marshaller"/>
</beans:bean>
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<beans:bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="order" value="0" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="jsp" value="application/html" />
<beans:entry key="xml" value="application/xml" />
</beans:map>
</beans:property>
<beans:property name="defaultViews">
<beans:list>
<!-- XML View -->
<beans:bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<beans:constructor-arg ref="marshaller" />
</beans:bean>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<beans:property name="contextPaths">
<beans:array>
<beans:value>net.franciscovillegas.summa.ims.dto</beans:value>
<beans:value>net.franciscovillegas.summa.ims.service.requests</beans:value>
</beans:array>
</beans:property>
</beans:bean>
提前致谢!