Reputation: 2997
in a spring3 Controller I can create an action-method with several Parameters witch will be set by spring
@RequestMapping(value="/updateTemplate")
public void doStuff(HttpServletRequest request, Locale locale) {
assert request != null;
assert locale != null;
}
How can I teach Spring to fill my own defined Data-Types?
@RequestMapping(value="/updateTemplate")
public void doStuff(HttpServletRequest request, Locale locale, MyClass myClass) {
assert myClass != null;
}
Upvotes: 3
Views: 344
Reputation: 1065
you should use WebArgumentResolver
public class MyClassWebArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter param, NativeWebRequest req) throws Exception {
if (param.getParameterType().equals(MyClass.class)) {
MyCLass obj = new MyClass();
....
return obj;
}
return UNRESOLVED;
}
}
and register it to springmvc:
<mvc:annotation-driven >
<mvc:argument-resolvers>
<bean class="com.xxx.MyClassWebArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
then you can use it in your controller
@RequestMapping(value="/updateTemplate")
public void doStuff(HttpServletRequest request, Locale locale, MyClass myClass) {
assert myClass != null;
}
Upvotes: 2
Reputation: 42849
Spring has a class called HttpMessageConverter
that will do just this for you. It will take various members of the incoming HttpServletRequest
and use them to create an object that will then be passed to your Controller
methods. The best part is that it will do this automatically for you if you have the HttpMessageConverter
's added into the ApplicationContext
(via the AnnotationMethodHandlerAdapter
, described here).
There are many prebuilt implementations that exist already, and you can find a lot of them on the HttpMessageConverter
page linked above. Probably the most often helpful are MappingJacksonHttpMessageConverter
, which is used to map a JSONObject from the request body to a JavaBean, and MarshallingHttpMessageConverter
, which is used to map XML from the request body to a JavaBean.
Upvotes: 0