Spring data not saving dates - java

I have an Spring project with one simple entity and a JPA repository. The entity has three variables: Name (String), active (boolean) and date (java.util.Date). Once deployed, Hibernate creates the table in my MySQL database using varchar, tinyint and datetime. All seems correct but when I create/modify an instance of the entity and call the save() method of the repository, all fields are saved except the date. Is there any know problem storing dates with a JPA repository or meaby I'm doing something wrong?
I'm not putting any code here because is only a simple class and an interface for the repository. Also, the entity is being saved. My problem is only related with Date field (and any other Date field that I could define). Having said this, if anything is needed, just ask.
EDIT:
root-context.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"
xmlns:task="http://www.springframework.org/schema/task"
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
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<import resource="infraestructure.xml" />
<jpa:repositories base-package="com.smarttabletv.repository" />
</beans>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.smarttabletv" />
<!-- Activates #Scheduled and #Async annotations for scheduling -->
<task:annotation-driven />
</beans:beans>
infraestructure.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:tx="http://www.springframework.org/schema/tx"
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.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.xsd"
default-autowire="byName">
<!-- Scans within the base package of the application for #Components to
configure as beans -->
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="${db.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="org.hibernate.envers.auditTablePrefix"></prop>
<prop key="org.hibernate.envers.auditTableSuffix">_history</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
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">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application 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/appServlet/servlet-context.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>
</web-app>
db.properties
db.password=
db.username=
db.url=jdbc:mysql://ip:3306/smarttabletv
db.dialect=org.hibernate.dialect.MySQLInnoDBDialect
db.driver=com.mysql.jdbc.Driver
Code not working
Task task = taskService.findDispatchableTask();
task.setDispatched(true); // This is saved
task.setEndDate(new Date()); // But this not
taskService.save(task);
Task class first lines
#Entity
#Table(name = "sttv_tasks")
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "tsk_id")
private Long id;
#Column(name = "tsk_end_date")
private Date endDate;

You forgot to add the Temporal annotation on the endDate, specifying if the date, time, or both should be persisted.
#Column(name = "tsk_end_date")
#Temporal(TemporalType.TIMESTAMP)
private Date endDate;

Related

Spring not dinfing dispatchServlet

I am new to spring. And I have encounter an error on my spring application. It says :
GRAVE: Servlet [dispatcher] in web application [/web-customer-function] threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1137)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:546)
I have beean dealing with this for a long time now... It has been 5 days. And this is what I have done...
Deployment Asssembly > Add lib folder to path
Stop,clean or/and delete server
Rewrite entire code
Download the org.springframework.web.servlet.DispatcherServlet and try to run again.
I would appreciate the help to all if possible.
This is my Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring-mvc-crud-demo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
And this part is my spring-crud.xml which are beans and configurations...
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.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">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
And there is a Controller class... Just in case ...
package com.luv2code.springdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping("/list")
public String listAll(Model model) {
return "list-customers";
}
}
I got the problem fixed...
Thank you all for the help it made my think again. So I refactor the code from zero checked the libraries and it ran smoothly. So the issue was with the libraries because after refactoring the code it did not work. But checking the libraries it worked.

Spring mobile redirect 404 error

I'm building the mobile version of the site with different layout. I'm using Spring mobile+Thymeleaf. For testing purposes, I'm getting redirected from main site to mobile version. Here's my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<display-name>Student Accounting site</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>studentacc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>studentacc</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>/m/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>deviceResolverRequestFilter</filter-name>
<filter-class>org.springframework.mobile.device.DeviceResolverRequestFilter</filter-class>
</filter>
</webapp>
And here's my servlet.xml
<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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:annotation-config/>
<context:component-scan base-package="org.something.webversion"/>
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.mobile.device.site.SitePreferenceWebArgumentResolver" />
<bean class="org.springframework.mobile.device.DeviceWebArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<!--Thymeleaf beans init:START-->
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver"/>
<property name="additionalDialects">
<set>
<bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect"/>
</set>
</property>
</bean>
<!--Thymeleaf beans init:END-->
<!--Other beans init:START-->
<mvc:interceptors>
<!-- Resolve the device which has generated the request -->
<bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
<!-- User's site preference -->
<bean class="org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor" />
<!-- Redirects users to the device specific site -->
<bean class="org.springframework.mobile.device.switcher.SiteSwitcherHandlerInterceptor" factory-method="urlPath">
<constructor-arg value="/m" />
</bean>
</mvc:interceptors>
<bean id="liteDeviceDelegatingViewResolver" class="org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver">
<constructor-arg>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</constructor-arg>
<property name="mobilePrefix" value="mobile/" />
<property name="enableFallback" value="true" />
</bean>
<!--Other beans init:END-->
<mvc:resources mapping="/resources/*" location="resources/"/>
</beans>
And mine controller:
public class MainController {
private static final Logger logger = Logger.getLogger(MainController.class.getName());
#RequestMapping(value = "/")
public String HelloWorld(Model model,Device device){
logger.info("Device is "+device);
if(device.isNormal()){
return "hello";
}
return "index";
}
}
Mine webapp folder look like this:
WEB-INF---
|
pages---
|
mobile---
|
index.html
So, the redirecting work just fine,I'm getting redirected to mobile version. But page i'm redirected to is non existing(404). I' just can't see the error. Thank you in advance.
"rotate" the redirect to url to sitename:8080/studentacc/m" because it is likely that "studentacc" is the name of your application in the application server, and therefore it must be the first part.
From a very short look to the API, I would try to use the SiteSwitcherHandlerInterceptor.urlPath(String mobilePath, String rootPath) method with the additional parameter for the rootPath
<bean class="org.springframework.mobile.device.switcher.SiteSwitcherHandlerInterceptor" factory-method="urlPath">
<constructor-arg value="/m" />
<constructor-arg value="/studentacc" />
</bean>

Spring 3.2 Hibernate No active transaction

I'm new to Spring, using version 3.2 with Hibernate 4.1.9Final, it seems that #Transactional annotations are being ignored, i've tried to set it on the controller method, service method and dao, no success
I've included the packages in
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<display-name>
Spring
</display-name>
<description>
Spring Test
</description>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springapp-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<context:component-scan base-package="com.test.web.controllers,com.test.service.impl" />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull"/>
<property name="username" value="medi"/>
<property name="password" value="tech"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingLocations" value="classpath*:com/test/model/hbm/**/*.hbm.xml" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.current_session_context_class=thread
</value>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="categoryDAO" class="com.test.dao.hibernate.HibernateCategoryDAO">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="categoryService" class="com.test.service.impl.Categories" scope="singleton">
<property name="dao" ref="categoryDAO"></property>
</bean>
</beans>
My Test Controller
public class HelloController {
#Autowired
private CategoryService categories;
public HelloController() {
System.out.println("test!!!");
}
public void setCategoryService(CategoryService categories) {
this.categories = categories;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
#Transactional
public String getIndex() {
Category c = new Category();
c.setName("Test");
categories.save(c);
return "index";
}
}
Stacktrace:
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at $Proxy19.save(Unknown Source)
at com.test.dao.hibernate.HibernateCategoryDAO.save(HibernateCategoryDAO.java:20)
at com.test.service.impl.Categories.save(Categories.java:21)
at com.test.web.controllers.HelloController.getIndex(HelloController.java:36)
at com.test.web.controllers.HelloController$$FastClassByCGLIB$$aa12a3a3.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
Removed hibernate.current_session_context_class=thread and it works. Spring injecting its own session context managing implementation when using Spring transaction support layer?
You are using #Transactional in the controller layer. It should be in your Service layer.
Make Categories.save method #Transactional and you might get this error away.
Try to add <context:component-scan base-package="your package here">
Looks like it just can't find annotations

Spring webmvc chaining viewresolvers gives BeanNotOfRequiredTypeException

I have a simple (sample) web application that i have a problem with if i try chaining multiple viewresolvers. When my application is configured in the way described below, trying to access http://localhost:8080/Library/spring/initApplication will throw the error described below.
It seems as though the InitApplication is erroneously being picked up by the wrong view resolver. If i change the order of the view resolvers everything works, but im still wondering why exactly this error occurs because i cant pinpoint why it happens. Im guessing a configuration issue?
26027 ["http-bio-8080"-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'initApplication' must be of type [org.springframework.web.servlet.View], but was actually of type [library.controller.InitApplication]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:349)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:266)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
at org.springframework.web.servlet.view.ResourceBundleViewResolver.loadView(ResourceBundleViewResolver.java:196)
at org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158)
at org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77)
at org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078)
Details of the important files:
InitApplication.java
#Controller
public class InitApplication {
#RequestMapping(value = "/initApplication", method = RequestMethod.GET)
etc.......
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>testwebproj</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
</web-app>
springmvc-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"
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.xsd">
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/library" />
<property name="username" value="root" />
<!-- <property name="password" value="" /> -->
</bean>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<bean id="pdfViewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="1" />
<property name="basename" value="views" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="library"></context:component-scan>
</beans>
views.properties
pdfPrinter.(class)=library.controller.DummyController
It is certainly because your are mapping your view with a Controller class mate!
pdfPrinter.(class)= you should indicate a View class here!
For example to map a Controller to a jsp View, you will need to proceed like this:
login.(class)=org.springframework.web.servlet.view.JstlView
login.url=/vues/en/login.jsp
have you tried renaming your bean? You may be clobbering an internal bean used by spring

Mixing *-servlet.xml with applicationContext.xml

I have an existing Spring application that does some server side processing. I am trying to create a webapp for this particular application and chose SpringMVC to serve my purpose.
I created a display controller as follows:
#Controller
#RequestMapping("/items")
public class ItemDisplayController {
private static final Logger LOGGER = Logger.getLogger(ItemDisplayController.class);
private static final String ITEMS_REDIRECT = "redirect:/item/items";
#Autowired
private ItemDisplay itemDisplay;
#RequestMapping
public String listItems(ModelMap model) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("List all items");
}
List<ItemDetail> itemDetails = itemDisplay.getAllItems();
model.addAttribute("itemDetails",itemDetails);
return "items";
}
}
I already have an applicationContext file with the following definitions:
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="props" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array>
<value>classpath:item.properties</value>
<value>file:#{systemEnvironment['ITEM_HOME']}/item.properties</value>
<value>file:#{systemProperties['ITEM_HOME']}/item.properties</value>
</array>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<bean id="itemDisplay" class="com.acme.itemDisplayImpl">
<property name="itemDisplayDAO" ref="jdbcItemDisplayDAO"/>
</bean>
<bean id="jdbcItemDisplayDAO" class="com.acme.database.dao.JdbcItemDisplayDAO">
<property name="dataSource" ref = "dataSource"/>
</bean>
<bean id="realDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="#{props['itemds.jdbc.driver']}"/>
<property name="url"><value><![CDATA[#{props['itemds.jdbc.url']}]]></value></property>
<property name="username" value="#{props['itemds.username']}"/>
<property name="password" value="#{props['itemds.password']}"/>
<property name="testOnBorrow" value="#{props['itemds.test.on.borrow']}"/>
<property name="testWhileIdle" value="#{props['itemds.test.while.idle']}"/>
<property name="poolPreparedStatements" value="#{props['itemds.pool.prepared.statements']}"/>
<property name="validationQuery" value="#{props['itemds.validation.query']}"/>
<property name="validationQueryTimeout" value="#{props['itemds.validation.query.timeout']}"/>
<property name="timeBetweenEvictionRunsMillis" value="#{props['itemds.time.between.eviction.runs.millis']}"/>
<property name="maxActive" value="#{props['itemds.max.active']}"/>
<property name="maxIdle" value="#{props['itemds.max.idle']}"/>
<property name="initialSize" value="#{props['itemds.initial.size']}"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource" ref="realDataSource"/>
</bean>
</beans>
In my *servlet.xml, I have defined the ViewResolver as follows:
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.acme.item"/>
<bean id="primaryViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="order" value="1"/>
</bean>
</beans>
And in the web.xml, I have the context-param defined:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
xmlns="http://java.sun.com/xml/ns/javaee">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>items</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>items</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
When I run my application, the itemDisplay is not wired up and on the debugger it is showing up with a null value.
Can somebody point out what I may be doing wrong here? In an ideal world, I would assume that annotating the itemDisplay with #Autowired in the controller would help resolve the implementation of the interface.
Only thing I can think of is, ContextLoaderListener does not complain if the applicationContext.xml is not found, Let's try this add classpath*:applicationContext.xml also make sure applicationContext.xml is run time class path of the server
Here is an excellent article that provides a good insight into spring classpath resource.
Your files looks up fine at quick glance. As long as there is only one bean with of ItemDisplay type in your context it should be autowired by type, otherwise you should get error in log file.
One small thing I noticed, which is probably unrelated to your particular issue, is that you map your 'items' controller to all files in web.xml. Usually you would want it to map to particular type of files only - say *.htm so it won't get called for resources such as images etc.
Not sure if this is a typo in your applicationContext file :
<bean id="itemDisplay" class="com.acme.itemDisplayImpl"/>
Shouldn't the class be com.acme.item.DisplayImpl ?. If the name of class is indeed itemDisplayImpl, then you need to change the component-scan element in *servlet.xml to include the correct package.

Categories

Resources