Errors using Spring 4.1 #RestController - spring-mvc

I'm trying to return JSON when using the #RestController. I'm using Spring 4.1.
Here's the exception I'm getting when calling listrestsites.html using a GET request.
I have the fasterxml Jackson core and databind jars in my build path.
Output of the accept from #requestheader = accept: application/json, text/javascript, /; q=0.01
Any help is appreciated. Thank you,
[DEBUG,ExceptionHandlerExceptionResolver] Resolving exception from
handler [public java.util.List
com.amci.spring3.controller.SitesRestController.listRestSites(java.lang.String)]:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
find acceptable representation [DEBUG,DefaultListableBeanFactory]
Returning cached instance of singleton bean
'exceptionControllerAdvice' [DEBUG,ExceptionHandlerExceptionResolver]
Invoking #ExceptionHandler method: public
org.springframework.web.servlet.ModelAndView
Here's my Restcontroller class:
#RestController
public class SitesRestController {
#Autowired
private AssetService assetService;
#RequestMapping("/listrestsites.html")
public List<Asset> listRestSites(#RequestHeader(value="accept") String accept) {
System.out.println(getLogLevel());
System.out.println("accept: " + accept);
return assetService.findAssets();
}
}
Also, snippet from my spring.xml:
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>

Please make sure that you have the following in your Spring xml file:
<context:annotation-config/>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
and all items of your POJO should have getters/setters. Hope it helps
Credit answer to this question

Related

org.hibernate.validator.constraints not picking reloaded messages

I am trying to use Spring's ReloadableResourceBundleMessageSource for LocalValidatorFactoryBean so that when I update an error message it should reflect without requiring the server to be restarted. I am using Spring 4.1.4, hibernate-validator 4.3.2.Final.
Below are the code details -
context.xml -
<mvc:annotation-driven validator="validator" />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>file:../conf/fileapplication</value> <!-- Messages here will override the below properties file-->
<value>/WEB-INF/application</value>
</list>
</property>
<property name="cacheSeconds" value="10"></property> <!-- Will check for refresh every 10 seconds -->
</bean>
<bean name="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource">
<ref bean="messageSource"/>
</property>
</bean>
Model -
import org.hibernate.validator.constraints.NotBlank;
public class InputForm {
#NotBlank ( message = "{required.string.blank}")
String requiredString;
Controller -
#RequestMapping(value = "/check/string", method = RequestMethod.POST)
public String checkString(
#ModelAttribute("formModel") #Valid InputForm inputForm ,
BindingResult result, Model model, HttpServletResponse response,
HttpServletRequest request) {
if (result.hasErrors()) {
model.addAttribute("formModel", inputForm);
return "userInput";
}
// Do some backend validation with String
result.reject("string.not.valid",
"String is Invalid");
model.addAttribute("formModel", inputForm);
return "userInput";
}
application.properties (in /WEB_INF/ folder)
required.string.blank=Please enter the required string.
string.not.valid=Please enter a valid string.
fileapplication.properties (in /conf/ folder. Will override above file)
required.string.blank=You did not enter the required string. #Does not reflect when I change here
string.not.valid=You did not enter a valid string. #Reflects when I change here
Now the problem I am facing is, when I update "string.not.valid" in fileapplication.properties it reflects at runtime and I see the updated message. But when I update "required.string.blank" in fileapplication.properties it does not reflect at runtime.
Note that the overriding part is working fine for both messages upon application start up. But the "reloading" part is not working fine for "required.string.blank".
This is what I figured out based on my research - We need to create our own MessageInterpolator and add it as dependency to the validator instead of message source. Because when we add a messageSource as dependency, it is cached by default by the validator and any message reloads spring does won't take effect in the validator's cached instance of messageSource.
Below are the details:
In context.xml, add the custom MessageInterpolator as dependency to LocalValidatorFactoryBean instead of messageSource:
<mvc:annotation-driven validator="validator" />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>file:../conf/fileapplication</value> <!-- Messages here will override the below properties file-->
<value>/WEB-INF/application</value>
</list>
</property>
<property name="cacheSeconds" value="10"></property> <!-- Will check for refresh every 10 seconds -->
</bean>
<bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="messageInterpolator">
<ref bean="messageInterpolator"/>
</property>
</bean>
<bean name="messageInterpolator"
class="com.my.org.support.MyCustomResourceBundleMessageInterpolator">
<constructor-arg ref="messageSource" />
</bean>
Create your custom MessageInterpolator by extending Hibernate's org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.
public class MyCustomResourceBundleMessageInterpolator extends
ResourceBundleMessageInterpolator {
public MyCustomResourceBundleMessageInterpolator(MessageSource messageSource)
{
// Passing false for the second argument
// in the super() constructor avoids the messages being cached.
super(new MessageSourceResourceBundleLocator(messageSource), false);
}
}
Model, Controller and properties file can be same as in the question.

Spring MVC Converters doesn't work at all

I'm very new to Spring MVC and Java EE at all (I came from PHP+Zend2). My english is poor too. I use NetBeans.
My problem is that my custom converter does not work. Here's some code:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="universalDAO" class="dao.UniversalDAO"/>
<bean id="sessionManager" class="utils.SessionManager"/>
<bean id="idToEntityConverterFactory" class="utils.IdToEntityConverterFactory">
<property name="dao" ref="universalDAO"/>
</bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<ref bean="idToEntityConverterFactory" />
<bean id="temp" class="utils.TempConverter" />
</list>
</property>
</bean>
<bean name="universalService" class="service.UniversalService">
<property name="universalDAO" ref="universalDAO"/>
</bean>
<bean name="sessionApplicationService" class="service.SessionApplicationService">
<property name="universalDAO" ref="universalDAO"/>
<property name="sessionManager" ref="sessionManager"/>
</bean>
<bean name="systemUserApplicationService" class="service.SystemUserApplicationService">
<property name="universalDAO" ref="universalDAO"/>
</bean>
<aop:aspectj-autoproxy />
<bean id="loggerAspect" class="aspect.LoggerAspect"/>
</beans>
I also have tried version with:
class="org.springframework.format.support.FormattingConversionServiceFactoryBean"
IdToEntityConverterFactory is a ConverterFactory created with this tutorial but it is not important now. I wrote simpler one not to do mess.
TempConverter.java
package utils;
import entity.Role;
import org.springframework.core.convert.converter.Converter;
public class TempConverter implements Converter<String, Role> {
#Override
public Role convert(String id) {
return new Role();
}
}
Here is .jsp fragment:
<form:select path="${names[item.index]}" items="${valueOptions[names[item.index]]}" />
When I submit the form there appears an error:
Failed to convert property value of type java.lang.String[] to required type java.util.List for property roleList; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [entity.Role] for property roleList[0]: no matching editors or conversion strategy found
I found solution to similar problem here . It has something to do with
<mvc:annotation-driven>
but I don't use such tag anywhere in my application (should I?).
My question is how to make any converter work while binding form data to Java object.
EDIT:
I figured out some workaround. I have overriden initBinder method in my Controller:
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.setConversionService(conversionService);
}
conversionService had to be previously set in Controller of course:
private ConversionService conversionService;
//...
public void setConversionService(ConversionService conversionService) {
this.conversionService = conversionService;
}
dispatcher-servlet.xml:
<bean class="controller.SystemUserFormController" p:applicationService-ref="systemUserApplicationService" p:sessionManager-ref="sessionManager" p:conversionService-ref="conversionService" />
It works now but it is kind of inconvenience because:
I have to add extra code p:conversionService-ref="conversionService" in every Controller I need converter to be used.
It works out-of-the-box in every toutorial I found on the internet but not for me. I am just curious what am I doing different.
Kindest regards!
Your questions:
I have to add extra code p:conversionService-ref="conversionService" in every Controller I need converter to be used.
You can use #Autowired to inject ConversionService.
You can implement common parent class for your controllers with #InitBinder
You can use abstract parent bean definition <bean abstract="true" ...>
It works out-of-the-box in every toutorial I found on the internet but not for me. I am just curious what am I doing different.
Just use <mvc:annotation-driven>. This easy-to-use configuration is there so that you don't need to configure stuff manually.
How to do it
You can implement WebBindingInitializer. This bean needs to be set up on handler adapter.
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="yourBindingInitializer" />
</bean>
However this approach is kind of painful if you are not already defining hanlder adapter yourself. When you define this bean it disables some DispatcherServlet's default behavior. So you might need to do a bit more than to define this bean.
Off-topic advice
Problem with Spring is that the internet is full of obsolete tutorials. Please use the official guide and reference app. Start using namespace (or even Java) config, autowiring, #Controller components and #RequestMapping.
I belive there is not such think as mvc:annotation-config. There are 2 other things:
context:annotation-config
mvc:annotation-driven
Please tell me if I am wrong
I have tried both and both doesn't work. Here's what what have I done:
Removed p:conversionService-ref="conversionService" from my Controller bean
Added #Autowired annotation to my setter
#Autowired
public void setConversionService(ConversionService conversionService) {
this.conversionService = conversionService;
}
Added context:annotation-config/ (or mvc:annotation-driven/) to applicationContext.xml
Unfortunately setter has never been executed!
My source is here
Quote: "When Spring finds an #Autowired annotation used with setter methods, it tries to perform byType autowiring on the method."
I also have tried using setter with exactly the same type as bean class - still nothing.

Spring: how to get the app's directory path during a bean construction time?

I have a bean as follows:
<bean id="myBean" class="MyBeanClass">
<constructor-arg value="\WEB-INF\myfile.dat"/>
</bean>
In the bean's contructor, I need to build the file's full path. To do that, I have to first find the app's root path first.
Thanks and regards.
Update
Per Michael-O's suggestion, here is my solution (so easy).
Spring bean:
<bean id="myBean" class="MyBeanClass">
<constructor-arg value="/myfile.dat"/> <!--under WEB-INF/classes-->
</bean>
Java:
public MyBeanClass(String path) throws Exception {
ClassPathResource file = new ClassPathResource(path);
lookup = new LookupService(file.getFile().getPath(), LookupService.GEOIP_MEMORY_CACHE);
}
Michael, thanks!!!
Use Spring's Resource class in your bean and spring will do the rest for you.
After seeing #curious1's edit, there is a better solution to his answer. Please do not use that. Go with this one:
beans.xml:
<!-- START: Improvement 2 -->
<context:annotation-config />
<bean id="service" class="LookupService">
<constructor-arg value="classpath:/myfile.dat"/> <!--under WEB-INF/classes-->
<constructor-arg>
<util:constant static-field="LookupService.GEOIP_MEMORY_CACHE"/>
</constructor-arg>
</bean>
<!-- END: Improvement 2 -->
<!-- Spring autowires here -->
<bean id="myBean" class="MyBeanClass" />
<!-- START: Improvement 1 -->
<bean id="myBean" class="MyBeanClass" />
<constructor-arg value="classpath:/myfile.dat"/> <!--under WEB-INF/classes-->
</bean>
<!-- END: Improvement 1 -->
Java:
public MyBeanClass(Resource path) throws Exception {
lookup = new LookupService(path.getInputStream(), LookupService.GEOIP_MEMORY_CACHE);
}
This is source-agnostic, does not rely on files and is the Spring way.
Edit 2: Rethinking my code, it can be even better:
public class MyBeanClass {
#Autowired
LookupService service;
}
and configure LookupService in your beans.xml.
Maybe you should consider using:
getClass().getClassLoader().getResourceAsStream()
inside constructor. This will use your classpath, so you "WEB-INF\myfile.dat", will be visible. Next think is use resource directory to put all resources in one directory (default: under root directory in WAR file)

replacing AnnotationMethodHandlerAdapter with RequestMappingHandlerAdapter issue

I recently upgraded to spring 3.2 and noticed that AnnotationMethodHandlerAdapter had been deprecated in favor of RequestMappingHandlerAdapter. So I reconfigured to use the new class, complete with a custom MessageConverter I need. All fine and good.
However, when attempting to hit a URL supported by an annotated Controller, I'm getting an error:
[java] javax.servlet.ServletException: No adapter for handler [my.company.TagController#1c2e7808]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
[java] at org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1128)
[java] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:903)
[java] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
When debugging the dispatcher, and in particular, the Dispatcher.getHandlerAdapter() method, it's finding my HandlerAdapter, but the AbstractHandlerMethodAdapter.supports() that is invoked wants a MethodHandler:
public final boolean supports(Object handler) {
return handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler);
}
and the controller is not a HandlerMethod. The AnnotatedMethodHandlerAdapter's support method is.. well, different (and works still!)
public boolean supports(Object handler) {
return getMethodResolver(handler).hasHandlerMethods();
}
So I apparently cannot simply upgrade to the new class... I'm missing some additional configuration, but the documentation isn't really helping me out. Any ideas?
Thanks.
Use "<mvc:annotation-driven/>" in the spring configuration file instead of writing your own implementation of WebMvcConfigurationSupport
example
<mvc:annotation-driven/>
<context:component-scan base-package="com.springapp.mvc"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
So as it turns out, simple switching the bean definition doesn't work due to the fact that the RequestMappingHandlerAdapter is depending on a whole host of entities being created and configured. Spring, by default, is using a WebMvcConfigurationSupport entity to do all this default configuration, but simply creating my own bean version doesn't help because spring creates its own.
My approach ended up being something along the lines of below, where I left basically all of the configuration up to spring's default, but then added my own converter. The only drawback is that it's switching xml configuration to javaconfig, but in my case, it's ok. There's an article here that describes something similar.
#Configuration
public class WebConfig extends WebMvcConfigurationSupport {
#Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter handlerAdapter = super.requestMappingHandlerAdapter();
handlerAdapter.getMessageConverters().add(0, getProtobufJsonMessageConverter());
return handlerAdapter;
}
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
#Configuration
public class WebConfig extends WebMvcConfigurationSupport {
#Override
protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
return new XXXXRequestMappingHandlerAdapter();
}
}

How do I restrict route extensions in #RequestMapping paths for Spring MVC controllers?

I have a fairly simple task that I want to accomplish, but can't seem to find information for Spring MVC routing about it. I have a very simple controller that routes a path to a view:
#Controller
#RequestMapping(value = "/help")
public class HelpController {
private static final String HELP = "help";
#RequestMapping(method = RequestMethod.GET)
public String help(Model model, Locale locale) {
model.addAttribute("locale", locale);
return HELP;
}
}
I would like to throw a 404 if http://mysite.com/help.some.extension.is.entered, but Spring seems to resolve the example to /help. The javadoc says that the #RequestMapping annotation is just a servlet URI mapping, but I thought /help means it needs to be an exact match. Any clarification would be appreciated.
For Spring 4 it's pretty easy to solve:
<mvc:annotation-driven>
<mvc:path-matching suffix-pattern="false" />
</mvc:annotation-driven>
So you still can use mvc:annotation-driven for your config.
You can mention it in the #RequestMapping annotation
it is same as Servlet URL pattern only.
#Controller
public class HelpController {
private static final String HELP = "help";
#RequestMapping(value = "/help" method = RequestMethod.GET)
public String help(Model model, Locale locale) {
model.addAttribute("locale", locale);
return HELP;
}
#RequestMapping(value = "help/*" method = RequestMethod.GET)
public String helpWithExtraWords() {
return "error";
}
}
The best way I can think of is to configure your RequestMappingHandlerMapping explicitly to not consider suffixpaths, this way:
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useSuffixPatternMatch" value="false"></property>
</bean>
However, if you have configured your Spring MVC using mvc:annotation-driven, this will not work, you will have to expand out the entire handlerAdapter definition, which is not that difficult to do, along these lines(this is not complete, you can look through org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser for the entire definition):
<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>
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<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>
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useSuffixPatternMatch" value="false"></property>
</bean>
With Spring 3.0.X You can use the useDefaultSuffixPattern property.
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="useDefaultSuffixPattern" value="false" />
</bean>
You will need to remove </mvc:annotation-driven>
Refer URL Pattern Restricting in SPRING MVC

Resources