Error:Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener [duplicate] - spring

This question already has an answer here:
Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
(1 answer)
Closed 9 years ago.
I know that question is already asked but none of the solutions worked for me.
Can anyone please help me with this. I m just a beginner in spring.
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.openid.OpenIDAuthenticationFilter#0': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/openid4java/consumer/ConsumerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:946)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:892)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:272)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:196)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.NoClassDefFoundError: org/openid4java/consumer/ConsumerException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.getDeclaredConstructor(Class.java:1985)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:64)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:939)
... 23 more
Caused by: java.lang.ClassNotFoundException: org.openid4java.consumer.ConsumerException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>WeeklySummary</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener- class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
dispatcher-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.kratin" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="order" value="1" />
<property name="messageConverters">
<list>
<!-- Default converters -->
<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>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.kratin.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
applicationContext-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http use-expressions="true">
<intercept-url pattern="/**" access="permitAll" />
<openid-login>
<attribute-exchange>
<openid-attribute name="email" type="http://axschema.org/contact/email" required="true" />
<openid-attribute name="fullname" type="http://axschema.org/namePerson" />
<openid-attribute name="first" type="http://axschema.org/namePerson/first" />
<openid-attribute name="last" type="http://axschema.org/namePerson/last" />
</attribute-exchange>
</openid-login>
<logout />
</http>
<!-- In our example we need to specify own UserService, to keep all logged-in users in the memory storage -->
<beans:bean id="org.springframework.security.authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="demoAuthenticationProvider"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="demoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"/>
<!-- property name="passwordEncoder" ref="passwordEncoder"/ -->
</beans:bean>
<beans:bean id="userDetailsService" class="com.kratin.service.InMemoryUserDetailsService"/>
<!-- Handler to receive success openId response and create new user -->
<beans:bean id="org.springframework.security.openid.ext.OpenIdAuthenticationHandler"
class="com.kratin.controller.DemoAuthenticationSuccessHandler">
<beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>
login.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring-Security-Step2 Sample Web-Application</title>
</head>
<body>
<sec:authorize access="isAnonymous()">
<h1> Login with OpenID </h1>
Login via Google<br></br>
Login via Yahoo<br></br>
<form name="myOpenIdForm" action="j_spring_openid_security_check" method="post">
<input type="hidden" name="openid_identifier" value=""/>
<input type='text' name='my_open_id' value=''/>.myopenid.com
<input name="submit"
type="submit"
class="rsButton"
value="Login via MyOpenId"
onClick="onMyOpenId();"/>
</form>
<form name="googleAppsForm" action="j_spring_openid_security_check" method="post">
Login into Google Apps Domain
<input type="hidden" name="openid_identifier" value=""/>
Google Apps Domain: <input type='text' name='google_apps_domain' value=''/>
<input name="submit"
type="submit"
class="rsButton"
value="Login into Google Apps"
onClick="onGoogleApps();"/>
</form>
<form name="openIdForm" action="j_spring_openid_security_check" method="post">
Login via any Open ID Provider
<input type='text' name='openid_identifier' value=''/>
<input name="submit" type="submit" class="rsButton" value="Login via OpenID"/>
</form>
<script>
function onMyOpenId() {
var myOpenIdName = document.myOpenIdForm.my_open_id.value;
document.myOpenIdForm.openid_identifier.value='http://' + myOpenIdName + '.myopenid.com';
}
function onGoogleApps() {
var googleAppsDomain = document.googleAppsForm.google_apps_domain.value;
document.googleAppsForm.openid_identifier.value='https://www.google.com/accounts /o8/site-xrds?hd='+googleAppsDomain;
}
</script>
</sec:authorize>
<sec:authorize access="isAuthenticated()">
DemoUserDetails currentUser = (DemoUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
<%-- OpenID: <%=currentUser.getUsername() %><br></br>
Email: <%=currentUser.getEmail() %><br></br>
Full Name: <%=currentUser.getFullName() %><br></br> --%>
Logout
</sec:authorize>
</body>
</html>

Look at the root cause :
java.lang.ClassNotFoundException: org.openid4java.consumer.ConsumerException
Add jar for this file

You are getting the Exception for Class not found in your class path.
Caused by: java.lang.ClassNotFoundException: org.openid4java.consumer.ConsumerException
You have to put openid4java jar in your class path.
you can get it from
https://code.google.com/p/openid4java/downloads/list

Related

Spring security XML configuration not protecting URLs

I have gone through a lot of questions similar to this but I couldn't find any solution.
I am using Spring-3.0.5RELEASE and Spring-security-3.1.2RELEASE.
Actually I am adding spring security to already exixsting application.
There are no errors in creating bean or filters but the urls are not protected.
spring-security.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" use-expressions="true">
<!-- <intercept-url pattern="/" access="permitAll" /> -->
<security:intercept-url pattern="/index" access="permitAll" />
<security:intercept-url pattern="/admin"
access="hasRole('Admin')" />
<security:intercept-url pattern="/dashboard" access="hasRole('Admin')
or hasRole('User')" />
<security:intercept-url pattern="/setup" access="hasRole('User')" />
<!-- access denied page -->
<security:access-denied-handler error-page="/logout" />
<security:form-login
login-processing-url="/loginAuth"
login-page="/index"
default-target-url="/dashboard"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/index"/>
<!-- enable csrf protection -->
<!-- <csrf/> -->
<http-basic />
</security:http>
<!-- Select users and user_roles from database -->
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select customerId, passcode from Users where customerId=?"
authorities-by-username-query=
"select customerId, roleName from Role where customerId=?" />
</security:authentication-provider>
</security:authentication-manager>
</beans:beans>
There is a warning here saying: Referenced bean 'dataSource' not found. I am not sure whether this may cause the problem.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/sample-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/spring-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
sample-servlet.xml
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.as.spark" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.as.spark.model.Users</value>
<value>com.as.spark.model.Role</value>
</list>
</property>
<property name="hibernateProperties">
<!-- properties -->
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I don't want to shift to java configuration because that requires a higher version of spring.
All the pages /home, /dashboard, /admin are open to all users.
How do I check whether the filter is applied? How to protect the URL?

Error: WARNING: No mapping found for HTTP request WARNING: No mapping found for HTTPrequest with URI. Help me?

I have a problem with my project. When i browser http://localhost:8080/user/form to display UserForm then occur following error:
WARNING: No mapping found for HTTP request with URI [/user/form] in
DispatcherSe rvlet with name 'userservice'
Here file userservice-servlet.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<context:component-scan base-package="edu.java.spring.service.user.controller"></context:component-scan>
<context:component-scan base-package="edu.java.spring.service.user.dao"></context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="suffix" value=".jsp" />
<property name="prefix" value="/user/" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:User.hbm.xml</value>
</list>
</property>
<property name="packagesToScan" value="edu.java.spring.service.user.model" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url"
value="jdbc:derby:D:\PROJECTSPRING\userdb;create=true" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="contentType" value="text/plain"/>
</bean>
</beans>
Here file UserRestServiceController.java
#Controller
public class UserRestServiceController {
#Autowired
private UserDao userDao;
#Autowired
private View jsonView;
#RequestMapping(value="/user/form,",method = RequestMethod.GET)
public ModelAndView user(){
// System.out.println("anh yeu em ");
return new ModelAndView("UserForm","User",new User());
}
#RequestMapping(value="/user/json/{username}")
public ModelAndView loadUser(#PathVariable("username")String name){
return new ModelAndView(jsonView,"data",userDao.loadUser(name));
}
}
Here file web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>userservice</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>userservice</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>userservice</servlet-name>
<url-pattern>*.xml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
edu.java.spring.service.user.controller.CustomContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/userservice-servlet.xml</param-value>
</context-param>
</web-app>
<property name="prefix" value="/user/" />
This means you have kept your JSPs inside webapp/user directory?
Try to move inside WEB-INF and check.
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>

Differents application Context in Spring 4

I have a login service in my application implementing UserDetailsService:
#Service
#Transactional
public class LoginService implements UserDetailsService {
#Autowired
UserService userService;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Assert.notNull(username);
UserDetails result = userService.loadUserDetailsByUsername(username);
Assert.notNull(result);
// WARNING: The following sentences prevent lazy initialisation problems!
Assert.notNull(result.getAuthorities());
result.getAuthorities().size();
return result;
}
}
The app dies with the error Exception encountered during context initialization. The start of the trace is:
Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0] ...
The end is:
Cannot resolve reference to bean 'loginService' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'loginService' is defined
So it cannot find the loginService.
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>SimpleSpringProject</display-name>
<description>All you need!</description>
<!-- Loads Spring Security config file -->
<!--
contextConfigLocation is the context parameter where we provide the spring security beans configuration file name.
It is used by ContextLoaderListener to configure authentication in our application
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-*.xml</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Creates the Spring Container shared by all Servlet and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Handles Spring requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/webmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In the contextConfigLocation I am loading 3 files: spring-security.xml, spring-datasource.xml and spring-jpa.xml.
spring-security.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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/user/**" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/role/**" access="hasRole('ROLE_ADMIN')" />
<security:form-login
login-processing-url="/login"
login-page="/loginForm"
default-target-url="/"
authentication-failure-url="/loginForm?error"
username-parameter="username"
password-parameter="password" />
<security:logout logout-url="/logout" logout-success-url="/" delete-cookies="JSESSIONID" />
<security:csrf />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="loginService"></security:authentication-provider>
</security:authentication-manager>
</beans>
spring-jpa.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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.ssp" />
</beans>
spring-datasource.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Enable #Transactional annotation -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- MySQL Datasource with Commons DBCP connection pooling -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/simplesp" />
<property name="username" value="root" />
<property name="password" value="betis000" />
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<!-- EntityManagerFactory -->
<bean
id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Transaction Manager -->
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
In the DispatcherServlet I am loading webmvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enable annotation-based Spring MVC controllers (eg: #Controller annotation) -->
<mvc:annotation-driven />
<!-- Classpath scanning of #Component, #Service, etc annotated class -->
<context:component-scan base-package="com.ssp" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<!-- Register "global" interceptor beans to apply to all registered HandlerMappings -->
<mvc:interceptors>
<!-- Set the language in variable lang -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="lang" />
</mvc:interceptors>
<!-- Resolve view name into jsp file located on /WEB-INF -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Tiles -->
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/tiles-definitions.xml</value>
</list>
</property>
</bean>
<!-- Resolves localized messages*.properties and application.properties
files in the application to allow for internationalization. The messages*.properties
files translate messages which are part of the admin interface, the application.properties
resource bundle localizes all application specific messages such as entity
names and menu items. -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basenames="i18n/messages,i18n/application" />
<!-- Store preferred language configuration in a cookie -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver"
p:cookieName="locale" p:defaultLocale="en" />
</beans>
I am thinking that I have a problem with applicationContext because if I remove the #Service annotation and define the bean LoginService in the spring-security.xml:
<bean id="loginService" class="com.ssp.service.LoginService" />
then the applications starts and when I submit a login its UserService is null, so it seems that the context of LoginService is different to the context of the beans with:
<context:component-scan base-package="com.ssp" />
If anyone wants to see the full code of the app is in https://github.com/pedrogonzalezgutierrez/simplespringproject
I think you will need wrap your loginService with userDetailsServiceWrapper, try this:
<bean id="loginService" class="path.to.LoginService" />
<bean id="preAuthenticationProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService">
<bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="loginService" />
</bean>
</property>
</bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="preAuthenticationProvider" />
</authentication-manager>
After research more and more I am sure that it was a problem with the application context. It seems that I had two differents context in my app. One of them was loaded by the contextConfigLocation and another one by the DispatcherServlet.
Just leave the param-value of the DispatcherServlet empty and load all the configurations by contextConfigLocation.
Also I updated the beans definitions to the version 3.2 except for Spring Security that requires 4.0

good old could not initialize proxy - no Session

I know this is all over SO but i'm still unable to figure it out.
I ran into this exception (could not initialize proxy - no Session) when jackson tries to json-size my classes, googled it, found the famous OpenEntityManagerInViewFilter solution, added it but nothing happens.
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Propspace API</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- <context-param> -->
<!-- <param-name>log4jConfigLocation</param-name> -->
<!-- <param-value>WEB-INF/log4j.properties</param-value> -->
<!-- </context-param> -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/security.xml
/WEB-INF/spring-servlet.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactoryRead</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- <listener> -->
<!-- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> -->
<!-- </listener> -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
And here is my servlet config:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
<!-- <import resource="mongodb-context.xml" /> -->
<context:component-scan
base-package="com.propspace.api.mongo, com.propspace.api.controller, com.propspace.api.core.service, com.propspace.api.repository, com.propspace.api.helper">
<!-- <context:include-filter type="aspectj" -->
<!-- expression="com.propspace.api.mongo" /> -->
</context:component-scan>
<!-- Persistence config -->
<!-- Read related beans -->
<bean id="permissionsAspect" class="com.propspace.api.aspect.PermissionsAspect" />
<bean id="entityManagerFactoryRead"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceXmlLocation" value="classpath:config/persistence-demo.xml"
/> -->
<property name="persistenceUnitName" value="read" />
<property name="dataSource" ref="dataSourceRead" />
<property name="packagesToScan" value="com.propspace.api.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="dataSourceRead" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="${JPA.read.jdbc.url}" />
<property name="username" value="${JPA.read.jdbc.user}" />
<property name="password" value="${JPA.read.jdbc.password}" />
<property name="partitionCount" value="5" />
<property name="maxConnectionsPerPartition" value="5" />
<property name="minConnectionsPerPartition" value="1" />
<property name="poolName" value="null" />
</bean>
<!-- Write related beans -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"
/> -->
<property name="persistenceUnitName" value="write" />
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.propspace.api.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="false" />
</bean>
</property>
<!-- <property name="jpaProperties"> <props> <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
</props> </property> -->
</bean>
<!-- Configure the data source bean -->
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="${JPA.write.jdbc.url}" />
<property name="username" value="${JPA.write.jdbc.user}" />
<property name="password" value="${JPA.write.jdbc.password}" />
<property name="partitionCount" value="5" />
<property name="maxConnectionsPerPartition" value="5" />
<property name="minConnectionsPerPartition" value="1" />
<property name="poolName" value="null" />
</bean>
<!-- Sets up our transaction manager. -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="dataSource" ref="dataSource" />
<!-- <property name="sessionFactory" ref="sessionFactory" /> -->
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- End of write related beans -->
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="defaultPersistenceUnitName" value="entityManagerFactory" />
</bean>
<bean id="sessionFactory" factory-bean="entityManagerFactory"
factory-method="getSessionFactory" />
<!-- <bean -->
<!-- class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
/> -->
<jpa:repositories base-package="com.propspace.api.repository" />
<!-- Defines our transaction manager for Transactional annotations. -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- end of persistence config -->
<mvc:annotation-driven />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*" />
<bean name="openEntityManagerInViewInterceptor"
class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">
<property name="entityManagerFactory">
<ref bean="entityManagerFactoryRead"></ref>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<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>
<property name="requireSession" value="false" />
</bean>
<context:property-placeholder location="classpath:application.properties" />
<!-- <context:annotation-config /> -->
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<!-- Most controllers will use the ControllerClassNameHandlerMapping above,
but for the index controller we are using ParameterizableViewController,
so we must define an explicit mapping for it. -->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- The index controller. -->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="index" />
</bean>
<aop:aspectj-autoproxy />
<bean id="permissions" class="com.propspace.api.aspect.PermissionsAspect" />
<!-- Customized type conversion of error Messages - Message Bundle -->
<bean
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="WEB-INF/i18n/application" />
</bean>
<!-- Cache -->
<!-- <cache:annotation-driven /> -->
<!-- Ehcache annotation config -->
<ehcache:annotation-driven cache-manager="ehCacheManager" />
<!-- <ehcache:config cache-manager="ehCacheManager"> <ehcache:evict-expired-elements
interval="60" /> </ehcache:config> -->
<bean id="ehCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>/WEB-INF/ehcache.xml</value>
</property>
<property name="shared">
<value>true</value>
</property>
</bean>
</beans>
And finally here is the full trace:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.propspace.api.core.domain.Contacts.landlordListings, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:500)
at java.lang.String.valueOf(String.java:2854)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at com.propspace.api.helper.BaseDomainSerializer.serializeMapObjects(BaseDomainSerializer.java:196)
at com.propspace.api.helper.BaseDomainSerializer.passToSerialize(BaseDomainSerializer.java:175)
at com.propspace.api.helper.BaseDomainSerializer.serialize(BaseDomainSerializer.java:268)
at com.propspace.api.helper.BaseDomainSerializer.serialize(BaseDomainSerializer.java:31)
at org.codehaus.jackson.map.ser.ContainerSerializers$IndexedListSerializer.serializeContents(ContainerSerializers.java:273)
at org.codehaus.jackson.map.ser.ContainerSerializers$IndexedListSerializer.serializeContents(ContainerSerializers.java:229)
at org.codehaus.jackson.map.ser.ContainerSerializers$AsArraySerializer.serialize(ContainerSerializers.java:130)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:587)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:245)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1145)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:203)
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:121)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:69)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:131)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1024)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

Type mismatch when I enter string for Int in one of the form parameter when I submit form in spring 3

I have a jsp form as following :
<form:form method="POST" commandName="command" action="RouteGradesGoals.html" >
<tr>
<td class="style4" colspan="2">
Goal</td>
<td colspan="2">
<form:input path="goal" type="text" id="goal" style="width:200px;" />
</td>
<td colspan="2">
<form:errors path="goal" cssClass="error" />
</td>
</tr>
<input type="submit" name="action" value="Delete" id="Button3"
class="submitButton" />
</form:form>
As you see there is only one parameter goal in the command object and it is of type int in the command object.
But when I submit the form I gets this error by passing string for int in the goal param:
{"detail":"An error has occured while processing the request: org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'command' on field 'goal': rejected value [sadfasd]; codes [typeMismatch.command.goal,typeMismatch.goal,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [command.goal,goal]; arguments []; default message [goal]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'goal'; nested exception is java.lang.NumberFormatException: For input string: \"sadfasd\"]"}
The controller has a simple method to process this form as given below:
#RequestMapping( value = "/RouteGradesGoals.html", method = RequestMethod.POST )
public String addInventoryGoal(#ModelAttribute( "command" ) InventoryGoal goal, HttpServletRequest request,
BindingResult result, SessionStatus status, ModelMap model, HttpSession session){
inventoryGoalValidator.validate(goal, result);
if (result.hasErrors()) {
return "RouteGradesGoals";
}
// do processing of the command object
return "RouteGradesGoals";
}
Command object is as follows :
public class InventoryGoal {
private Integer goal;
public Integer getGoal() {
return goal;
}
public void setGoal(Integer goal) {
this.goal = goal;
}
}
This is how I have added the message resolver in the context xml file :
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
I have added these properties in the messages.properties
typeMismatch.command.goal=invalid goal1
typeMismatch.goal=invalid goal2
typeMismatch.java.lang.Integer=invalid goal2
typeMismatch=invalid goal3
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Forerunner Webservice</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.ids.forerunner.web.configuration.WebConfig</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>mysql</param-value>
</context-param>
<servlet>
<servlet-name>restService</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>webapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webapp</servlet-name>
<url-pattern>/webapp/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>restService</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<!-- The CORS filter with parameters -->
<filter-name>CORS</filter-name>
<filter-class>com.ids.cors.CORSFilter</filter-class>
<!-- Note: All parameters are options, if ommitted CORS Filter
will fall back to the respective default values.
-->
<init-param>
<param-name>cors.allowGenericHttpRequests</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, HEAD, POST, OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Content-Type, X-Requested-With</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>X-Test-1, X-Test-2</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.maxAge</param-name>
<param-value>3600</param-value>
</init-param>
</filter>
<filter-mapping>
<!-- CORS Filter mapping -->
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>APIProtectionFilter</filter-name>
<filter-class>com.ids.forerunner.filter.APIProtectionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>APIProtectionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
in the WebConfig.java I am importing resources as given below:
#ImportResource({"classpath:/META-INF/spring/forerunner-service.xml","/WEB-INF/webapp-servlet.xml"})
webapp-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:component-scan base-package="com.ids.forerunner.webapp.controllers" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/forerunner_style.css" location="/forerunner_style.css" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.ids.forerunner.webapp.interceptor.ForerunnerRequestInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<bean id="messageSource" class=" org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:message-webapp-error" />
</bean>
<!-- <util:properties id="tophireProperties" location="classpath:tophire.properties" /> -->
</beans>
forerunner-service.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:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Enables automatic mapping of fund objects to and from JSON -->
<mvc:annotation-driven />
<import resource="classpath:/META-INF/spring/applicationContext.xml" />
<import resource="classpath:/META-INF/spring/applicationContext-jpa.xml" />
<bean id="contactFormValidator" class="com.ids.forerunner.webapp.validator.ContactFormValidator" />
<bean id="inventoryGoalValidator" class="com.ids.forerunner.webapp.validator.InventoryGoalValidator" />
<bean id="anchorAreaValidator" class="com.ids.forerunner.webapp.validator.AnchorAreaValidator" />
<bean class="com.ids.forerunner.util.ForerunnerInitializer"/>
<bean class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles" value="classpath*:/dozer-bean-mappings.xml" />
</bean>
<!-- Setup spring to pull in #Controller, #RequestMapping, etc. Configuration
scans specified packages for classes configured as Spring managed beans and
automatically sets up objects annotated with #Controller, #Service etc. -->
<context:component-scan base-package="com.ids.forerunner.web" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<!-- Configures view for returning JSON to the client -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"
p:contentType="text/plain"></bean>
<!-- maps handler methods based on HTTP paths -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="jsonMessageConverter" />
</util:list>
</property>
</bean>
<!-- Converts JSON to POJO and vice versa -->
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/pages/" p:suffix=".jsp">
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<bean id="taskList" class="com.forerunner.cronjobs.TaskList">
<property name="taskList">
<list>
<bean name="sessionTask" class="com.forerunner.cronjobs.SessionCronTask"></bean>
</list>
</property>
</bean>
<bean name="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.forerunner.cronjobs.ForerunnerCronJob" />
<property name="jobDataAsMap">
<map>
<entry key="taskList" value-ref="taskList" />
</map>
</property>
</bean>
<bean id="cronTrigger" class="com.forerunner.cronjobs.ForerunnerTrigger">
<property name="jobDetail" ref="jobDetail" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="jobDetail" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
</beans>
In the message-webapp-error.properties I have properties as follows :
typeMismatch.command.goal=invalid goal1
typeMismatch.goal=invalid goal2
typeMismatch.java.lang.Integer=invalid goal2
typeMismatch=invalid goal3
Form is posted to this url http:///forerunner/webapp/RouteGradesGoals.html
Can someone please tell me how can I prevent such error and in such scenerios return a valid error message.
Configure a MessageSource and provide a message for one of the shown error codes
typeMismatch.command.goal
typeMismatch.goal
typeMismatch.java.lang.Integer
typeMismatch
Which provides messages from most specific to least specific.
<bean id="messageSource" class=" org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
</bean>
This MessageSource will load a messages.properties (or locale specific one) from the root of the classpath. Add it and fill it accordingly
typeMismatch.command.goal=The goal needs to be a valid number.
typeMismatch.java.lang.Integer=The given input is not a valid number.
Now with this content for your case the first message will be shown, for other typeMismatch errors on Integer fields the second one will be shown.
For more information on a MessageSource see the reference guide and javadoc. More information on error code generation here.

Resources