I get following error when I try use my DAO. I don know where is problem. I please for help.
Error look like this:
Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
This is my POJO class:
#Entity
#Table(name = "contacts")
public class Customer {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="firstname")
private String name;
#Column(name="lastname")
private String surname;
#Column(name = "telephone")
private String telephoneNumber;
#Column(name = "email")
private String email;
DAO class:
#Repository
public class CustomerResource implements DAO_INTERFACE {
#Autowired
private SessionFactory sf;
#Override
public void addCustomer() {
}
#Override
public List<Customer> getList() {
return sf.getCurrentSession().createQuery("from Customer").list();
}
#Override
public void delete(int id) {
}
}
Service:
#Service
public class CustomerService implements CustomerDatabaseInterface {
#Autowired
private DAO_INTERFACE customerRepo;
#Transactional
public List<Customer> getCustomers() {
return customerRepo.getList();
}
}
servlet-context.xml:
<resources mapping="/resources/**" location="/resources/" />
<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="pl.project" />
</beans:beans>
root-context.xml:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/spring/database.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:url="${db.url}"
p:driverClassName="${db.driverClassName}"
p:username="${db.username}"
p:password="${db.password}"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>pl.project.model.Customer</value>
</list>
</property>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Error log :
cze 09, 2014 7:31:39 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_05\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\MySQL\MySQL Utilities 1.3.6\;.
cze 09, 2014 7:31:39 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Test Project' did not find a matching property.
cze 09, 2014 7:31:39 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
cze 09, 2014 7:31:39 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
cze 09, 2014 7:31:39 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 449 ms
cze 09, 2014 7:31:39 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
cze 09, 2014 7:31:39 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
cze 09, 2014 7:31:40 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
cze 09, 2014 7:31:40 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Mon Jun 09 19:31:41 CEST 2014]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/spring/database.properties]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#69e74d06: defining beans [propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1054 ms
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
cze 09, 2014 7:31:42 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Mon Jun 09 19:31:42 CEST 2014]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#415ccca5: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,homeController,customerResource,customerService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#69e74d06
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String pl.project.controller.HomeController.home(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 457 ms
cze 09, 2014 7:31:42 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
cze 09, 2014 7:31:42 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
cze 09, 2014 7:31:42 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3143 ms
cze 09, 2014 7:32:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/controller] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here] with root cause
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)
at pl.project.model.CustomerResource.getList(CustomerResource.java:26)
at pl.project.model.CustomerService.getCustomers(CustomerService.java:18)
at pl.project.controller.HomeController.home(HomeController.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
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.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I am beginning programmer. I just learn hibernate and Spring.
You don't seem to have transaction management correctly configured for your spring application because you are scanning for everything in your dispatcher servlet.
<context:component-scan base-package="pl.project" />
You might have duplicated beans in the component-scanning. Both component-scan elements i.e in the dispatcher-servlet-context and the root-context detect the same elements hence instantiating your DAO service twice.
Fix your component-scan elements by scanning only your controller classes in the dispatcher-servlet-context and excluding your controller classes from the component scan in the root-context, something like this
Dispatcher Servlet Context:
<context:component-scan base-package="pl.project.controller" />
Root application context (Datasource context)
<context:component-scan base-package="pl.project">
<context:exclude-filter type="regex" expression="pl.project.controller.*"/>
</context:component-scan>
Hi you should keep in servlet-context.xml things related to MVC like views and controllers, and move the services, repositories to the root-context(application-context).
Related
im trying to configure hello world application. The problem is my dispatcherServlet cannot see the URL's.
First thing first the vital code below:
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>DebtDetector</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- <context-param> -->
<!-- <param-name>contextConfigLocation</param-name> -->
<!-- <param-value>/WEB-INF/rootApplicationContext.xml</param-value> -->
<!-- </context-param> -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns: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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="kaczynski" />
<context:annotation-config />
<mvc:annotation-driven />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="WEB-INF/hibernate.properties"></property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="kaczynski" />
<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>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
</beans>
Controller:
package kaczynski.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class ControllerAccount {
#RequestMapping("/index")
public String welcomePage(){
System.out.println("aa");
return "index";
}
}
and given warrning: (after http://localhost:8080/DebtDetector/index)
lip 15, 2016 10:57:13 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/DebtDetector/index] in DispatcherServlet with name 'mvc-dispatcher'
full server startup logs:
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.32
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Feb 2 2016 19:34:53 UTC
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.32.0
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_51
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_51-b16
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\Mateusz\Documents\workspace-sts-3.7.3.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Java\apache-tomcat-8.0.32
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\Mateusz\Documents\workspace-sts-3.7.3.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Java\apache-tomcat-8.0.32
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\Mateusz\Documents\workspace-sts-3.7.3.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Java\apache-tomcat-8.0.32\endorsed
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
lip 15, 2016 11:48:14 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_51\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_51/bin/server;C:/Program Files/Java/jre1.8.0_51/bin;C:/Program Files/Java/jre1.8.0_51/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Common Files\Autodesk Shared\;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Java\jdk1.8.0_31\bin;C:\Java\apache-maven-3.3.9\bin;C:\Java\sts-bundle\sts-3.7.3.RELEASE;;.
lip 15, 2016 11:48:14 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
lip 15, 2016 11:48:14 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
lip 15, 2016 11:48:14 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
lip 15, 2016 11:48:14 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
lip 15, 2016 11:48:14 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1452 ms
lip 15, 2016 11:48:15 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
lip 15, 2016 11:48:15 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.32
lip 15, 2016 11:48:15 AM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [281] milliseconds.
lip 15, 2016 11:48:15 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor C:\Users\Mateusz\Documents\workspace-sts-3.7.3.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\conf\Catalina\localhost\DebtDetector.xml
lip 15, 2016 11:48:15 AM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:DebtDetector' did not find a matching property.
lip 15, 2016 11:48:18 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
lip 15, 2016 11:48:18 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
lip 15, 2016 11:48:18 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
lip 15, 2016 11:48:18 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
lip 15, 2016 11:48:18 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Fri Jul 15 11:48:18 CEST 2016]; root of context hierarchy
lip 15, 2016 11:48:18 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
lip 15, 2016 11:48:21 AM org.springframework.beans.factory.config.PropertyPlaceholderConfigurer loadProperties
INFO: Loading properties file from ServletContext resource [/WEB-INF/hibernate.properties]
lip 15, 2016 11:48:21 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
lip 15, 2016 11:48:21 AM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'default'
lip 15, 2016 11:48:21 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: default
...]
lip 15, 2016 11:48:21 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.9.Final}
lip 15, 2016 11:48:21 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
lip 15, 2016 11:48:21 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
lip 15, 2016 11:48:21 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
lip 15, 2016 11:48:22 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
lip 15, 2016 11:48:22 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
lip 15, 2016 11:48:23 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
lip 15, 2016 11:48:23 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: Root WebApplicationContext: startup date [Fri Jul 15 11:48:18 CEST 2016]; root of context hierarchy
lip 15, 2016 11:48:23 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: Root WebApplicationContext: startup date [Fri Jul 15 11:48:18 CEST 2016]; root of context hierarchy
lip 15, 2016 11:48:23 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 5294 ms
lip 15, 2016 11:48:23 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'mvc-dispatcher'
lip 15, 2016 11:48:23 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'mvc-dispatcher': initialization started
lip 15, 2016 11:48:23 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Fri Jul 15 11:48:23 CEST 2016]; parent: Root WebApplicationContext
lip 15, 2016 11:48:23 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
lip 15, 2016 11:48:25 AM org.springframework.beans.factory.config.PropertyPlaceholderConfigurer loadProperties
INFO: Loading properties file from ServletContext resource [/WEB-INF/hibernate.properties]
lip 15, 2016 11:48:25 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
lip 15, 2016 11:48:25 AM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'default'
lip 15, 2016 11:48:25 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: default
...]
lip 15, 2016 11:48:25 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
lip 15, 2016 11:48:25 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
lip 15, 2016 11:48:25 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
lip 15, 2016 11:48:25 AM org.hibernate.jpa.internal.EntityManagerFactoryRegistry addEntityManagerFactory
WARN: HHH000436: Entity manager factory name (default) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
lip 15, 2016 11:48:25 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Fri Jul 15 11:48:23 CEST 2016]; parent: Root WebApplicationContext
lip 15, 2016 11:48:25 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Fri Jul 15 11:48:23 CEST 2016]; parent: Root WebApplicationContext
lip 15, 2016 11:48:26 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'mvc-dispatcher': initialization completed in 2216 ms
lip 15, 2016 11:48:26 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deployment of configuration descriptor C:\Users\Mateusz\Documents\workspace-sts-3.7.3.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\conf\Catalina\localhost\DebtDetector.xml has finished in 10,289 ms
lip 15, 2016 11:48:26 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
lip 15, 2016 11:48:26 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
lip 15, 2016 11:48:26 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 11162 ms
lip 15, 2016 11:48:26 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/DebtDetector/] in DispatcherServlet with name 'mvc-dispatcher'
Try this.
Defining class-level request handling
#Controller
#RequestMapping("/index")
public class ControllerAccount {
public String welcomePage(){
System.out.println("aa");
return "index";
}
}
OR Defining method-level GET request handling
#Controller
public class ControllerAccount {
#RequestMapping(value="/index", method=GET)
public String welcomePage(){
System.out.println("aa");
return "index";
}
}
Use :
#Controller
public class ControllerAccount {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String welcomePage(){
System.out.println("aa");
return "index";
}
}
I've tried to implement JPA entityManager provided by Hibernate and update my database.
I use MySQL 5.7 server, where username is "tutorial" and password is just "password". I've done some configurations and tried to simply insert a row into the "country" table with columns: id(int)(pk)(auto_inc) and country(varchar), but it don't affect my database.
In country table are already 4 rows: (1, "Poland"), (2,"Slovakia"), (3, "Ukraine") and (4, "Czech Republic").
Controller:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.hibernate.basics.daos.CustomersDetailsDAO;
import pl.hibernate.basics.model.Country;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private CustomersDetailsDAO customersDetailsDAO;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
Country country = new Country();
country.setCountry("Lithuania");
logger.info("Country Entity: " + country);
customersDetailsDAO.insertCountry(country);
return "home";
}
}
CustomersDetailsDAOImpl:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import pl.hibernate.basics.model.Country;
#Transactional
#Component
public class CustomersDetailsDAOImpl implements CustomersDetailsDAO {
#PersistenceContext
private EntityManager em;
#Override
public void insertCountry(Country country) {
em.persist(country);
}
}
Entity Class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="country")
public class Country {
#Id
#GeneratedValue
private int id;
#Column
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "Country [id=" + id + ", country=" + country + "]";
}
}
persistence.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: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/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<tx:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="tutorial" />
<property name="password" value="password" />
</bean>
<bean id="emFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="pl.hibernate.basics" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Console output (Note logger info at the end):
sty 29, 2016 2:31:27 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JPA Hibernate Spring WebMVC Application' did not find a matching property.
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.23
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: May 19 2015 14:58:38 UTC
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.23.0
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 10
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 10.0
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_60
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_60-b27
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\Adrian\Desktop\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Users\Adrian\Desktop\apache-tomcat-8.0.23-windows-x64\apache-tomcat-8.0.23
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\Adrian\Desktop\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Users\Adrian\Desktop\apache-tomcat-8.0.23-windows-x64\apache-tomcat-8.0.23
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\Adrian\Desktop\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\Adrian\Desktop\apache-tomcat-8.0.23-windows-x64\apache-tomcat-8.0.23\endorsed
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1250
sty 29, 2016 2:31:27 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_60\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_60/bin/server;C:/Program Files/Java/jre1.8.0_60/bin;C:/Program Files/Java/jre1.8.0_60/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\xampp\php;;C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin;C:\Program Files\MySQL\MySQL Server 5.5\bin;C:\Users\Adrian\Desktop\eclipse;;.
sty 29, 2016 2:31:27 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
sty 29, 2016 2:31:28 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
sty 29, 2016 2:31:28 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
sty 29, 2016 2:31:28 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
sty 29, 2016 2:31:28 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1372 ms
sty 29, 2016 2:31:28 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
sty 29, 2016 2:31:28 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.23
sty 29, 2016 2:31:31 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
sty 29, 2016 2:31:31 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
sty 29, 2016 2:31:32 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri Jan 29 14:31:32 CET 2016]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/persistence.xml]
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Bean 'dataSource' of type [class org.springframework.jdbc.datasource.DriverManagerDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Bean 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#e956be6' of type [class org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
WARN : org.hibernate.ejb.HibernatePersistence - HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Bean 'emFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#6441d7e2: defining beans [homeController,customersDetailsDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,emFactory,transactionManager,persistenceExceptionTranslationPostProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 6254 ms
sty 29, 2016 2:31:38 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Fri Jan 29 14:31:38 CET 2016]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#472f3baa: defining beans [mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,homeController,customersDetailsDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#6441d7e2
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String pl.hibernate.basics.controllers.HomeController.home()
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 1362 ms
sty 29, 2016 2:31:39 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
sty 29, 2016 2:31:39 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
sty 29, 2016 2:31:39 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 11657 ms
INFO : pl.hibernate.basics.controllers.HomeController - Country Entity: Country [id=0, country=Lithuania]
G'day dear stackers,
I am really struggling at the moment with a basic test class of a dummy DAO. Although I see that persist and find methods of the injected EntityManager finally triggers SQL queries, my assertions keep failing.
First, the test configuration I use:
<!-- test -->
<persistence-unit name="eSporxPersistenceTestUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>...CoalmineCanary</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>
... together with the application context used by the tests:
<!-- data source definition -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</bean>
<!-- entity manager -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="eSporxPersistenceTestUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<property name="databasePlatform" value="${database.dialect}" />
</bean>
</property>
</bean>
<!-- transaction manager -->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
My DAO works with the following entity:
#Entity
public class CoalmineCanary {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String text;
public int getId() {
return id;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
}
... and the very DAO:
#Repository
public class CoalmineCanaryRepository {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void delete(CoalmineCanary entity) {
entityManager.remove(entity);
}
#Transactional
public CoalmineCanary findById(final int id) {
return entityManager.find(CoalmineCanary.class, id);
}
#Transactional
public void save(CoalmineCanary entity) {
entityManager.persist(entity);
}
}
My test class only consists in 2 very simple tests:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/META-INF/spring/testApplicationContext.xml")
public class CoalmineCanaryRepositoryTest {
#Autowired
private CoalmineCanaryRepository canaryRepository;
private CoalmineCanary coalmineCanary;
#Before
public void setup() {
coalmineCanary = new CoalmineCanary();
coalmineCanary.setText("pokus");
canaryRepository.save(coalmineCanary);
}
#Test
public void when_loaded_then_entity_is_retrieved() {
CoalmineCanary managedCanary = canaryRepository.findById(1);
assertThat(managedCanary).isNotNull();
assertThat(managedCanary.getText()).isEqualTo("pokus");
}
#Test
public void when_removed_then_entity_not_retrievable() {
CoalmineCanary managedCanary = canaryRepository.findById(1);
assertThat(managedCanary).isNotNull();
canaryRepository.delete(managedCanary);
CoalmineCanary canary = canaryRepository.findById(1);
assertThat(canary).isNull();
}
}
Here is the console output when I run the tests:
Feb 25, 2012 2:41:39 PM org.springframework.test.context.TestContextManager retrieveTestExecutionListeners
INFO: #TestExecutionListeners is not present for class [class tv.esporx.framework.CoalmineCanaryRepositoryTest]: using defaults.
Feb 25, 2012 2:41:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [META-INF/spring/testApplicationContext.xml]
Feb 25, 2012 2:41:39 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext#c4fe76: startup date [Sat Feb 25 14:41:39 CET 2012]; root of context hierarchy
Feb 25, 2012 2:41:40 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from file [/usr/local/projects/esporx/esporx-webapp/target/test-classes/META-INF/spring/datasource.properties]
Feb 25, 2012 2:41:40 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from file [/usr/local/projects/esporx/esporx-webapp/target/classes/META-INF/spring/datasource.properties]
Feb 25, 2012 2:41:40 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5eb489: defining beans [coalmineCanaryRepository,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,validator,dataSource,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Feb 25, 2012 2:41:40 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'eSporxPersistenceTestUnit'
Feb 25, 2012 2:41:41 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Feb 25, 2012 2:41:41 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Feb 25, 2012 2:41:41 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 25, 2012 2:41:41 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 25, 2012 2:41:41 PM org.hibernate.ejb.Ejb3Configuration configure
INFO: HHH000204: Processing PersistenceUnitInfo [
name: eSporxPersistenceTestUnit
...]
Feb 25, 2012 2:41:41 PM org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
Feb 25, 2012 2:41:41 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Feb 25, 2012 2:41:41 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Feb 25, 2012 2:41:41 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: esporx.coalmine_canary
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, text]
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
Feb 25, 2012 2:41:42 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: insert into coalmine_canary (text) values (?)
Hibernate: select coalmineca0_.id as id0_0_, coalmineca0_.text as text0_0_ from coalmine_canary coalmineca0_ where coalmineca0_.id=?
Hibernate: insert into coalmine_canary (text) values (?)
Hibernate: select coalmineca0_.id as id0_0_, coalmineca0_.text as text0_0_ from coalmine_canary coalmineca0_ where coalmineca0_.id=?
Feb 25, 2012 2:41:42 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext#c4fe76: startup date [Sat Feb 25 14:41:39 CET 2012]; root of context hierarchy
Feb 25, 2012 2:41:42 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5eb489: defining beans [coalmineCanaryRepository,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,validator,dataSource,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Feb 25, 2012 2:41:42 PM org.springframework.orm.jpa.AbstractEntityManagerFactoryBean destroy
INFO: Closing JPA EntityManagerFactory for persistence unit 'eSporxPersistenceTestUnit'
What happens now is that findById(1) always returns null.
I've been trying to change many things but still fail to make the tests pass...
Thanks in advance for your help!
Rolf
All the code written by you are fine, but the tests needs a bit of tuning,
private CoalmineCanary coalmineCanary;
#Before
public void setup() {
coalmineCanary = new CoalmineCanary();
coalmineCanary.setText("pokus");
coalmineCanary = canaryRepository.save(coalmineCanary);
if(coalmineCanary.getId() == 0){
fail("Could not insert the Canary!");
}
}
#Test
public void when_loaded_then_entity_is_retrieved() {
CoalmineCanary managedCanary = canaryRepository.findById(coalmineCanary.getId());
assertThat(managedCanary).isNotNull();
assertThat(managedCanary.getText()).isEqualTo("pokus");
}
Your tests could be failing because there is no guarantee that the id of the objects willl be 1. When the entities are saved, hibernate updates the id with the value from the DB and returns the object back. If you want to use that you should return that for the caller method.
Here in your test method instead of the hard coded id you should be using the id of the saved bean so that the tests can pass. Also, Let the tests fail if the id was not set in the setup() method.
I was building my application using Spring 2.5, Hibernate 3, Tomcat 7 and MySQL Community Server 5.1. I run the application and all works fine. The problem arise when I try to use the latest version of MySQL Server (MySQL Community Server 5.5), it seems that Hibernate can not create the tables. The error message says:
table project.product doesn't exists...
Here are the Apache logs:
SEVERE: Servlet.service() for servlet [dispatcher] in context path [/Project] threw exception[Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'project.products' doesn't exist
SEVERE: Servlet.service() for servlet [dispatcher] in context path [/Project] threw exception [Request processing failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: could not execute query; nested exception is org.hibernate.exception.JDBCConnectionException: could not execute query] with root cause
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
23-jul-2011 4:12:27 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context path [/Project] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'project.products' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
at com.mysql.jdbc.Util.getInstance(Util.java:382)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2281)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
at org.hibernate.loader.Loader.doQuery(Loader.java:802)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2533)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:926)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:917)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:909)
at com.pj.dao.ProductDAOImpl.listProduct(ProductDAOImpl.java:32)
at com.pj.web.IndexController.index(IndexController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:409)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:132)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:310)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:297)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:394)
at org.springframework.security.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.ui.SessionFixationProtectionFilter.doFilterHttp(SessionFixationProtectionFilter.java:67)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.ui.ExceptionTranslationFilter.doFilterHttp(ExceptionTranslationFilter.java:101)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.providers.anonymous.AnonymousProcessingFilter.doFilterHttp(AnonymousProcessingFilter.java:105)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.ui.rememberme.RememberMeProcessingFilter.doFilterHttp(RememberMeProcessingFilter.java:109)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter.doFilterHttp(SecurityContextHolderAwareRequestFilter.java:91)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.ui.basicauth.BasicProcessingFilter.doFilterHttp(BasicProcessingFilter.java:174)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.ui.AbstractProcessingFilter.doFilterHttp(AbstractProcessingFilter.java:278)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.ui.logout.LogoutFilter.doFilterHttp(LogoutFilter.java:89)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.context.HttpSessionContextIntegrationFilter.doFilterHttp(HttpSessionContextIntegrationFilter.java:235)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:406)
at org.springframework.security.util.FilterChainProxy.doFilter(FilterChainProxy.java:185)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:236)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
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:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:851)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:278)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
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)
I made another test. I tried installing Tomcat 6 instead of Tomcat 7, and when I tried to run my application, it comes up a 404 error (resource is not available). What's wrong with my application?
Here are the logs:
23-jul-2011 4:57:56 org.apache.catalina.core.AprLifecycleListener init
INFO: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: java.library.path: C:\java\jdk\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\java\jdk\bin;.
23-jul-2011 4:57:56 org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8000
23-jul-2011 4:57:56 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 476 ms
23-jul-2011 4:57:56 org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
23-jul-2011 4:57:56 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.32
23-jul-2011 4:57:56 org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor host-manager.xml
23-jul-2011 4:57:56 org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor manager.xml
23-jul-2011 4:57:57 org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive Project.war
23-jul-2011 4:57:57 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
23-jul-2011 4:57:57 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.XmlWebApplicationContext#f8395f: display name [Root WebApplicationContext]; startup date [Sat Jul 23 04:57:57 CEST 2011]; root of context hierarchy
23-jul-2011 4:57:58 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
23-jul-2011 4:58:00 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/security-applicationContext.xml]
23-jul-2011 4:58:00 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext#f8395f]: org.springframework.beans.factory.support.DefaultListableBeanFactory#fd1810
23-jul-2011 4:58:01 org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean '(inner bean)' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
23-jul-2011 4:58:01 org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean '_delegatingMethodDefinitionSource' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
23-jul-2011 4:58:01 org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean '_methodDefinitionSourceAdvisor' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
23-jul-2011 4:58:02 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#fd1810: defining beans [viewResolver,myDataSource,mySessionFactory,myProductDAO,myUserDAO,myorderDAO,indexController,urlMapping,usuarioValidator,messageSource,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,_delegatingMethodDefinitionSource,_accessManager,_methodSecurityInterceptor,_methodSecurityInterceptorPostProcessor,_methodDefinitionSourceAdvisor,org.springframework.aop.config.internalAutoProxyCreator,_authenticationManager,_filterChainProxy,_httpSessionContextIntegrationFilter,_filterChainProxyPostProcessor,_filterChainList,_securityContextHolderAwareRequestFilter,_portMapper,_exceptionTranslationFilter,_filterSecurityInterceptor,_sessionFixationProtectionFilter,_anonymousAuthenticationProvider,_anonymousProcessingFilter,_rememberMeServices,_rememberMeAuthenticationProvider,_rememberMeFilter,_rememberMeServicesInjectionBeanPostProcessor,_logoutFilter,_basicAuthenticationEntryPoint,_basicAuthenticationFilter,_formLoginFilter,_formLoginEntryPoint,_entryPointInjectionBeanPostProcessor,_userServiceInjectionPostProcessor,org.springframework.security.providers.dao.DaoAuthenticationProvider#0,org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager#0,org.springframework.security.config.AuthenticationProviderBeanDefinitionParser$AuthenticationProviderCacheResolver#0]; root of factory hierarchy
23-jul-2011 4:58:05 org.springframework.orm.hibernate3.LocalSessionFactoryBean buildSessionFactory
INFO: Building new Hibernate SessionFactory
23-jul-2011 4:58:06 org.springframework.security.intercept.AbstractSecurityInterceptor afterPropertiesSet
INFO: Validated configuration attributes
23-jul-2011 4:58:06 org.springframework.security.config.EntryPointInjectionBeanPostProcessor postProcessBeforeInitialization
INFO: Selecting AuthenticationEntryPoint for use in ExceptionTranslationFilter
23-jul-2011 4:58:06 org.springframework.security.config.EntryPointInjectionBeanPostProcessor postProcessBeforeInitialization
INFO: Using main configured AuthenticationEntryPoint.
23-jul-2011 4:58:06 org.springframework.security.config.EntryPointInjectionBeanPostProcessor postProcessBeforeInitialization
INFO: Using bean 'org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint#107b56e' as the entry point.
23-jul-2011 4:58:06 org.springframework.security.intercept.AbstractSecurityInterceptor afterPropertiesSet
INFO: Validated configuration attributes
23-jul-2011 4:58:06 org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
23-jul-2011 4:58:06 org.springframework.security.config.RememberMeServicesInjectionBeanPostProcessor postProcessBeforeInitialization
INFO: Setting RememberMeServices on bean _basicAuthenticationFilter
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: Checking sorted filter chain: [org.springframework.security.context.HttpSessionContextIntegrationFilter[ order=200; ], org.springframework.security.ui.logout.LogoutFilter[ order=300; ], org.springframework.security.ui.webapp.AuthenticationProcessingFilter[ order=700; ], org.springframework.security.ui.basicauth.BasicProcessingFilter[ order=1000; ], org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter[ order=1100; ], org.springframework.security.ui.rememberme.RememberMeProcessingFilter[ order=1200; ], org.springframework.security.providers.anonymous.AnonymousProcessingFilter[ order=1300; ], org.springframework.security.ui.ExceptionTranslationFilter[ order=1400; ], org.springframework.security.ui.SessionFixationProtectionFilter[ order=1600; ], org.springframework.security.intercept.web.FilterSecurityInterceptor#aa559d]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: Filter chain...
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [0] - org.springframework.security.context.HttpSessionContextIntegrationFilter[ order=200; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [1] - org.springframework.security.ui.logout.LogoutFilter[ order=300; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [2] - org.springframework.security.ui.webapp.AuthenticationProcessingFilter[ order=700; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [3] - org.springframework.security.ui.basicauth.BasicProcessingFilter[ order=1000; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [4] - org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter[ order=1100; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [5] - org.springframework.security.ui.rememberme.RememberMeProcessingFilter[ order=1200; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [6] - org.springframework.security.providers.anonymous.AnonymousProcessingFilter[ order=1300; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [7] - org.springframework.security.ui.ExceptionTranslationFilter[ order=1400; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [8] - org.springframework.security.ui.SessionFixationProtectionFilter[ order=1600; ]
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: [9] - org.springframework.security.intercept.web.FilterSecurityInterceptor#aa559d
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor checkLoginPageIsntProtected
INFO: Checking whether login URL '/login.htm' is accessible with your configuration
23-jul-2011 4:58:06 org.springframework.security.config.FilterChainProxyPostProcessor postProcessBeforeInitialization
INFO: FilterChainProxy: FilterChainProxy[ UrlMatcher = org.springframework.security.util.AntUrlPathMatcher[requiresLowerCase='true']; Filter Chains: {/**=[org.springframework.security.context.HttpSessionContextIntegrationFilter[ order=200; ], org.springframework.security.ui.logout.LogoutFilter[ order=300; ], org.springframework.security.ui.webapp.AuthenticationProcessingFilter[ order=700; ], org.springframework.security.ui.basicauth.BasicProcessingFilter[ order=1000; ], org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter[ order=1100; ], org.springframework.security.ui.rememberme.RememberMeProcessingFilter[ order=1200; ], org.springframework.security.providers.anonymous.AnonymousProcessingFilter[ order=1300; ], org.springframework.security.ui.ExceptionTranslationFilter[ order=1400; ], org.springframework.security.ui.SessionFixationProtectionFilter[ order=1600; ], org.springframework.security.intercept.web.FilterSecurityInterceptor#aa559d]}]
23-jul-2011 4:58:06 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 8969 ms
23-jul-2011 4:58:06 org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
23-jul-2011 4:58:06 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.XmlWebApplicationContext#c707c1: display name [WebApplicationContext for namespace 'dispatcher-servlet']; startup date [Sat Jul 23 04:58:06 CEST 2011]; parent: org.springframework.web.context.support.XmlWebApplicationContext#f8395f
23-jul-2011 4:58:06 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext#c707c1]: org.springframework.beans.factory.support.DefaultListableBeanFactory#19ccb73
23-jul-2011 4:58:06 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#19ccb73: defining beans []; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#fd1810
23-jul-2011 4:58:06 org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 110 ms
23-jul-2011 4:58:06 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory docs
23-jul-2011 4:58:06 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory examples
23-jul-2011 4:58:07 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory ROOT
23-jul-2011 4:58:07 org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
23-jul-2011 4:58:07 org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
23-jul-2011 4:58:07 org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/47 config=null
23-jul-2011 4:58:07 org.apache.catalina.startup.Catalina start
INFO: Server startup in 11163 ms
Here's the code of spring-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:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/security/spring-security-2.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<?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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/security/spring-security-2.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<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/Project"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.domain.Product</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
Let me know if you need more code than the provided above.
You have created the appropriate user and database ? Which would seem to be: usr = root;pwd = root; and db = Project.
The problem is in method ProductDAOImpl.listProduct(), on what table does Product class map to? Make sure the table exists in the database.
Are you sure the application is connecting to MySQL. Because there is no port no in your configuration file. usually it runs on 3306.
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_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>audiClave</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>rest.root</param-value>
</context-param>
<!-- Processes application requests -->
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet</servlet- class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/REST/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>base</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>base</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
base-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="com.audiClave.controllers" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Here is the BaseController:
package com.audiClave.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class BaseController {
#RequestMapping(value = "/index.html")
public ModelAndView home() {
System.out.println("BaseController: Passing through...");
return new ModelAndView("home");
// return "WEB-INF/views/home.jsp";
}
}
I call the tomcat service with:
http://localhost:8080/audiClave/index.html
and this is from the console:
BaseController: Passing through...
appears in the console window but nothing else. Content returned states:
description The requested resource () is not available.
Contents of /WEB-INF/views/home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Audiclave</title>
</head>
<body>
<h1>Hello world from audiClave!</h1>
</body>
</html>
The problem isn't in the file though because if I return
return new ModelAndView("xxxx");
It is the same result.
It does seem to be library related as it was working before I started changing the libraries (relating to JSTL and JSP) in my project. I don't know the sequence of the libraries I have changed. I must have ended up with something incompatible with tomcat 7.
There is nothing in the tomcat log that indicates a problem. This is the startup log:
01/06/2011 9:25:20 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Python26\Scripts;C:\Python26\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;C:\Program Files\Java\jdk1.6.0_21\bin;%APPDATA%\Python\Scripts;C:\Program Files\Translate Toolkit;C:\Program Files\Gallio\bin
01/06/2011 9:25:20 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:audiClave' did not find a matching property.
01/06/2011 9:25:20 AM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
01/06/2011 9:25:20 AM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
01/06/2011 9:25:20 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 336 ms
01/06/2011 9:25:20 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
01/06/2011 9:25:20 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
01/06/2011 9:25:22 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'rest'
01/06/2011 9:25:22 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'rest': initialization started
01/06/2011 9:25:22 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'rest-servlet': startup date [Wed Jun 01 09:25:22 EST 2011]; root of context hierarchy
01/06/2011 9:25:22 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/rest-servlet.xml]
01/06/2011 9:25:22 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#62610b: defining beans [baseController,restController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,beanNameResolver,RemedyXml]; root of factory hierarchy
01/06/2011 9:25:22 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/index.html] onto handler 'baseController'
01/06/2011 9:25:22 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/REST/remedies/{language}] onto handler 'restController'
01/06/2011 9:25:22 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/REST/remedies/{language}.*] onto handler 'restController'
01/06/2011 9:25:22 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/REST/remedies/{language}/] onto handler 'restController'
01/06/2011 9:25:22 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'rest': initialization completed in 359 ms
01/06/2011 9:25:22 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'base'
01/06/2011 9:25:22 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'base': initialization started
01/06/2011 9:25:22 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'base-servlet': startup date [Wed Jun 01 09:25:22 EST 2011]; root of context hierarchy
01/06/2011 9:25:22 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/base-servlet.xml]
01/06/2011 9:25:22 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#848ecc: defining beans [baseController,restController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0]; root of factory hierarchy
01/06/2011 9:25:23 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/index.html] onto handler 'baseController'
01/06/2011 9:25:23 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/REST/remedies/{language}] onto handler 'restController'
01/06/2011 9:25:23 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/REST/remedies/{language}.*] onto handler 'restController'
01/06/2011 9:25:23 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/REST/remedies/{language}/] onto handler 'restController'
01/06/2011 9:25:23 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'base': initialization completed in 297 ms
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
01/06/2011 9:25:23 AM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["http-bio-8080"]
01/06/2011 9:25:23 AM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
01/06/2011 9:25:23 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2490 ms
As per Biju's recommendation here is the log from after baseController returns the modelAndView:
2011-06-01 11:32:59,218 ["http-bio-8080"-exec-11] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'home'
2011-06-01 11:32:59,218 ["http-bio-8080"-exec-11] DEBUG org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'home'; URL [/WEB-INF/views/home.jsp]] in DispatcherServlet with name 'base'
2011-06-01 11:32:59,218 ["http-bio-8080"-exec-11] DEBUG org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/home.jsp] in InternalResourceView 'home'
2011-06-01 11:32:59,218 ["http-bio-8080"-exec-11] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request
Register a ViewResolver in the Spring configuration along these lines:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
Now you should be able to return "home" from your controller's requestmapped method and it should correctly get resolved to "/WEB-INF/views/home.jsp" page.
You're probably missing a dependent library (which is why it fails regardless of what JSP file you specify) and your Spring context is erroring out when it tries to create something. Look carefully in catalina.out for a java.lang.NoClassDefFoundError and see if you can figure out which class it is missing.
The problem is that home.jsp does not exist in the
.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\audiClave\WEB-INF\views
directory even though in eclipse it is showing. Wasn't able to see that until I got the logging working properly.
Stopping the server, cleaning, and then republishing seems to have fixed it.