Configuration of Spring MVC and JSON using Jackson - java

I'm using Spring MVC with Jackson. It requires <mvc:annotation-driven />. It works with it but it brings other issues. For example, after adding <mvc:annotation-driven />, Locale Change interceptor is not working:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
I don't need it except for Jackson, is it possible to use it without <mvc:annotation-driven />? If so, how?
Thanks

try using mvc namespace to declare your interceptor
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>

Related

Spring java based configuration for ByteArrayHttpMessageConverter

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list>
<bean id="byteArrayMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
</util:list>
</property>
</bean>
I'm new to the Spring java configuration to create a bean. Can some one help me with the java configuration for the above xml configuration. I have an requirement to send image to client through my rest spring controller.

Convert string with commas to double number in spring MVC

i am currently using MappingJacksonHttpMessageConverter in my Dispatcher-Servlet.xml. In my application when the user enters a currency, commas are itself attached to the value. When that value is passed to the controller it is unable to convert the string with commas to a double value. throws pare error. I am using this value for other calculations so i cannot change its type to string in the modal class.
Is there a way we can can use MappingJacksonHttpMessageConverter to make the controller ignore the commas and read the value.
This is part of my servlet.xml file.
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="order" value="1" />
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
Any help would be appreciated
You can do this by creating custom conversion service in spring by implementing Converter interface.
For info on this see http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html
and
http://log4aj.blogspot.in/2012/08/spring-converterconversionservice.html.

Is there a way to get all registered message-converters?

I would like to somehow inject all HttpMessageConverter instances registered in Spring-MVC. I can successfully inject all that have been registered via.
private HttpMessageConverter[] converters;
#Autowired
public void setConverters(HttpMessageConverter[] converters) {
this.converters = converters;
}
However this only injects if the converter was registered inside the context (i.e. if defined outside of <annotation-driven>).
I did figure I would try using <beans:ref inside the <annotation-driven><message-converters> but it is not supported in spring-web 3.1.
Is there some class I can inject that may have a property I could use to get converters? Ideally I'd like to see the order in the filter chain they are registered in too.
You are right, the message converters are directly instantiated within the RequestMappingHandlerAdapter registered using the <mvc:annotation-driven/> xml tag, and the message-converters subtag explicitly expect the bean to be defined inline.
However, a workaround is to define the handler adapter and inject in the converters this way:
<bean name="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService"></property>
<property name="validator">
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
</property>
</bean>
</property>
<property name="messageConverters">
<list>
<ref bean="byteArrayConverter"/>
<ref bean="jaxbConverter"/>
<ref bean="jsonConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
</list>
</property>
</bean>
<bean name="byteArrayConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<bean name="jaxbConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
<bean name="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useSuffixPatternMatch" value="false"></property>
</bean>
Spring puts all the converters behind an implementation of org.springframework.core.convert.ConversionService . You need to inject an instance of that interface into your class, you can read more in the spring documentation (including an example of how to inject it).
You can try injecting a bean of type RequestMappingHandlerAdapter but depending on your configuration, you might not have an instance!

Using the Flash scope ( and RedirectAttributes ) without <mvc:annotation-driven /> in Spring MVC 3.1

In my Spring MVC 3.1 application, I think I can't use "<mvc:annotation-driven />". Why? Because I want to apply an interceptor to all mappings except to the "<mvc:resources" elements. So I can't use :
<mvc:annotation-driven />
<mvc:resources order="-10" mapping="/public/**" location="/public/" />
<mvc:resources order="-10" mapping="/favicon.ico" location="/public/favicon.ico" />
<mvc:resources order="-10" mapping="/robots.txt" location="/public/robots.txt" />
<mvc:resources order="-10" mapping="/humans.txt" location="/public/humans.txt" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.my.Interceptor" />
</mvc:interceptor>
</mvc:interceptors>
Because I don't want the interceptor to apply to the resources and there is no way (I think) to specify a path for the mapping which would apply the interceptor to everything except this and that.
So I have to add my own RequestMappingHandlerMapping to be able to specify the interceptor on it, and not globally. Because of this and this, it seems I can't simply define my own RequestMappingHandlerMapping while keeping the <mvc:annotation-driven /> element!
So... With some help, I've been able to get rid of the <mvc:annotation-driven /> element and pretty much everything works well now. I have my interceptor applied on everything but my resources. Everything works well, except the flash scope!
#RequestMapping(value="/test", method=RequestMethod.POST)
public String test(Model model, RedirectAttributes redirectAttrs)
{
redirectAttrs.addFlashAttribute("myKey", "my message");
return "redirect:test2";
}
#RequestMapping(value="/test2")
public String test2(Model model, HttpServletRequest request)
{
Map<String, ?> map = RequestContextUtils.getInputFlashMap(request); // map is NULL
System.out.println(model.containsAttribute("myKey")); // Prints FALSE
}
The flash map is NULL and my model doesn't contain my variable. When I try with the <mvc:annotation-driven /> element it works well! So my question is: what is missing from my context to make the flash scope work?
I also did try to set "org.springframework.web" to a DEBUG logging level, and after the redirect there is nothing logged related to a FlashMap or FlashMapManager. It seems some required bean is definitely missing.
Here are the interesting parts of my context file:
<!-- commented! -->
<!-- <mvc:annotation-driven /> -->
<bean id="baseInterceptor" class="com.my.Interceptor" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="order" value="0" />
<property name="interceptors">
<list>
<ref bean="conversionServiceExposingInterceptor" />
<ref bean="baseInterceptor" />
</list>
</property>
</bean>
<bean id="myRequestMappingHandlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
<property name="validator" ref="validator" />
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
<bean id="conversionServiceExposingInterceptor" class="org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor">
<constructor-arg ref="conversionService" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:/messages/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean>
<mvc:resources order="-10" mapping="/public/**" location="/public/" />
<mvc:resources order="-10" mapping="/favicon.ico" location="/public/favicon.ico" />
<mvc:resources order="-10" mapping="/robots.txt" location="/public/robots.txt" />
<mvc:resources order="-10" mapping="/humans.txt" location="/public/humans.txt" />
What is missing for the flash scope to work?
UPDATE : See my answer for the solution... Nothing was missing actually. Only the Session was not working correctly and I found a way to make it work.
I finally found what was missing for the flash scope to work!
In the action where I access the flash variables (on the page the redirect leads to), I have to use this:
public String test2(Model model, HttpServletRequest request, HttpSession session)
instead of this :
public String test2(Model model, HttpServletRequest request)
It seems that this makes the Session to work correctly and therefore makes the flash scope to work correctly too! Why? I don't know...
It looks like all you need to do is to register a flash map manager with a bean name of flashMapManager and it should get automatically initialized and used by your Dispatcher Servlet:
<bean name="flashMapManager" class="org.springframework.web.servlet.support.DefaultFlashMapManager/>

<mvc:annotation-driven /> with un-annotated controllers

My project includes older un-annotated controllers together with newer annotation-based controllers.
I am using the latest Spring jars (3.0.5) and in my dispatcher-servlet.xml there's <mvc:annotation-driven />.
The problem is that <mvc:annotation-driven /> causes the request mapping (through the name property of the controller beans in the dispatcher-servlet.xml) to my un-annotated controllers not to work... each time I direct the request to an un-annotated controller I am getting an error message such as:
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/some_path/some_page.htm] in DispatcherServlet with name 'dispatcher'
How can I keep the un-annotated controllers as they are but tell spring to recognize their (old style) mapping?
I am looking for solutions with minimum change to the Java code of the controllers that I already have.
Thanks!
When you add <mvc:annotation-driven /> to your config, it replaces the default set of handler mappings and handler adapters, and those defaults were the ones that handled the old-style controllers.
You have 2 options. First thing to try is to remove <mvc:annotation-driven />. You can still use annotated controllers without this. It does add extra features like Jackson JSON support, but if you don't need those extra features, then you don't need it. So try your app without <mvc:annotation-driven /> and see if it still works.
Failing that, you can reinstate the mappings and adapters for your old controllers. You didn't say how your controllers used to have their URLs mapped, but try adding these to your config:
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.handler.ControllerClassNameHandlerMapping"/>
If you used SimpleUrlHandlerMapping, then that should be working already.
You also need to add the HandlerAdapter back in:
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
Don't just add these in blindly. Try them individually, and see what the minimal set is to get your old controllers working alongside the new ones.
I found that by exploding the mvc:annotation-driven into it's actual replacement, it was easier to figure out.
<mvc:annotation-driven /> explodes to this:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="0" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
</list>
</property>
</bean>
<!-- Configures a validator for spring to use -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="messageInterpolator">
<bean class="com.eps.web.spring.validation.SpringMessageSourceMessageInterpolator" />
</property>
</bean>
<bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
Once the magic was gone, I got this error trying to load an "Old" controller:
javax.servlet.ServletException: No adapter for handler [org.springframework.web.servlet.mvc.ParameterizableViewController#
From that point, I added
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
And all my old controllers worked.

Categories

Resources