I have an existing Spring application that does some server side processing. I am trying to create a webapp for this particular application and chose SpringMVC to serve my purpose.
I created a display controller as follows:
#Controller
#RequestMapping("/items")
public class ItemDisplayController {
private static final Logger LOGGER = Logger.getLogger(ItemDisplayController.class);
private static final String ITEMS_REDIRECT = "redirect:/item/items";
#Autowired
private ItemDisplay itemDisplay;
#RequestMapping
public String listItems(ModelMap model) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("List all items");
}
List<ItemDetail> itemDetails = itemDisplay.getAllItems();
model.addAttribute("itemDetails",itemDetails);
return "items";
}
}
I already have an applicationContext file with the following definitions:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="props" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array>
<value>classpath:item.properties</value>
<value>file:#{systemEnvironment['ITEM_HOME']}/item.properties</value>
<value>file:#{systemProperties['ITEM_HOME']}/item.properties</value>
</array>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<bean id="itemDisplay" class="com.acme.itemDisplayImpl">
<property name="itemDisplayDAO" ref="jdbcItemDisplayDAO"/>
</bean>
<bean id="jdbcItemDisplayDAO" class="com.acme.database.dao.JdbcItemDisplayDAO">
<property name="dataSource" ref = "dataSource"/>
</bean>
<bean id="realDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="#{props['itemds.jdbc.driver']}"/>
<property name="url"><value><![CDATA[#{props['itemds.jdbc.url']}]]></value></property>
<property name="username" value="#{props['itemds.username']}"/>
<property name="password" value="#{props['itemds.password']}"/>
<property name="testOnBorrow" value="#{props['itemds.test.on.borrow']}"/>
<property name="testWhileIdle" value="#{props['itemds.test.while.idle']}"/>
<property name="poolPreparedStatements" value="#{props['itemds.pool.prepared.statements']}"/>
<property name="validationQuery" value="#{props['itemds.validation.query']}"/>
<property name="validationQueryTimeout" value="#{props['itemds.validation.query.timeout']}"/>
<property name="timeBetweenEvictionRunsMillis" value="#{props['itemds.time.between.eviction.runs.millis']}"/>
<property name="maxActive" value="#{props['itemds.max.active']}"/>
<property name="maxIdle" value="#{props['itemds.max.idle']}"/>
<property name="initialSize" value="#{props['itemds.initial.size']}"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource" ref="realDataSource"/>
</bean>
</beans>
In my *servlet.xml, I have defined the ViewResolver as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.acme.item"/>
<bean id="primaryViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="order" value="1"/>
</bean>
</beans>
And in the web.xml, I have the context-param defined:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>items</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>items</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
When I run my application, the itemDisplay is not wired up and on the debugger it is showing up with a null value.
Can somebody point out what I may be doing wrong here? In an ideal world, I would assume that annotating the itemDisplay with #Autowired in the controller would help resolve the implementation of the interface.
Only thing I can think of is, ContextLoaderListener does not complain if the applicationContext.xml is not found, Let's try this add classpath*:applicationContext.xml also make sure applicationContext.xml is run time class path of the server
Here is an excellent article that provides a good insight into spring classpath resource.
Your files looks up fine at quick glance. As long as there is only one bean with of ItemDisplay type in your context it should be autowired by type, otherwise you should get error in log file.
One small thing I noticed, which is probably unrelated to your particular issue, is that you map your 'items' controller to all files in web.xml. Usually you would want it to map to particular type of files only - say *.htm so it won't get called for resources such as images etc.
Not sure if this is a typo in your applicationContext file :
<bean id="itemDisplay" class="com.acme.itemDisplayImpl"/>
Shouldn't the class be com.acme.item.DisplayImpl ?. If the name of class is indeed itemDisplayImpl, then you need to change the component-scan element in *servlet.xml to include the correct package.
Related
I'm building the mobile version of the site with different layout. I'm using Spring mobile+Thymeleaf. For testing purposes, I'm getting redirected from main site to mobile version. Here's my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<display-name>Student Accounting site</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>studentacc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>studentacc</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>/m/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>deviceResolverRequestFilter</filter-name>
<filter-class>org.springframework.mobile.device.DeviceResolverRequestFilter</filter-class>
</filter>
</webapp>
And here's my servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:annotation-config/>
<context:component-scan base-package="org.something.webversion"/>
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.mobile.device.site.SitePreferenceWebArgumentResolver" />
<bean class="org.springframework.mobile.device.DeviceWebArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<!--Thymeleaf beans init:START-->
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver"/>
<property name="additionalDialects">
<set>
<bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect"/>
</set>
</property>
</bean>
<!--Thymeleaf beans init:END-->
<!--Other beans init:START-->
<mvc:interceptors>
<!-- Resolve the device which has generated the request -->
<bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
<!-- User's site preference -->
<bean class="org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor" />
<!-- Redirects users to the device specific site -->
<bean class="org.springframework.mobile.device.switcher.SiteSwitcherHandlerInterceptor" factory-method="urlPath">
<constructor-arg value="/m" />
</bean>
</mvc:interceptors>
<bean id="liteDeviceDelegatingViewResolver" class="org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver">
<constructor-arg>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</constructor-arg>
<property name="mobilePrefix" value="mobile/" />
<property name="enableFallback" value="true" />
</bean>
<!--Other beans init:END-->
<mvc:resources mapping="/resources/*" location="resources/"/>
</beans>
And mine controller:
public class MainController {
private static final Logger logger = Logger.getLogger(MainController.class.getName());
#RequestMapping(value = "/")
public String HelloWorld(Model model,Device device){
logger.info("Device is "+device);
if(device.isNormal()){
return "hello";
}
return "index";
}
}
Mine webapp folder look like this:
WEB-INF---
|
pages---
|
mobile---
|
index.html
So, the redirecting work just fine,I'm getting redirected to mobile version. But page i'm redirected to is non existing(404). I' just can't see the error. Thank you in advance.
"rotate" the redirect to url to sitename:8080/studentacc/m" because it is likely that "studentacc" is the name of your application in the application server, and therefore it must be the first part.
From a very short look to the API, I would try to use the SiteSwitcherHandlerInterceptor.urlPath(String mobilePath, String rootPath) method with the additional parameter for the rootPath
<bean class="org.springframework.mobile.device.switcher.SiteSwitcherHandlerInterceptor" factory-method="urlPath">
<constructor-arg value="/m" />
<constructor-arg value="/studentacc" />
</bean>
I'm getting exception: No Session found for current thread, when I want to connect with database via hibernate, my cfg files:
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Here we blog web application</display-name>
<servlet>
<servlet-name>web-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>web-dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/web-dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
dispatcher servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.lime"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.postgresql.jdbc.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:8080/come_to_blog_db"/>
<property name="username" value="postgres"/>
<property name="password" value="admin"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.lime</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
I tried one solution (adding #Transactional annotation in service layer on method connecting to hibernate,but now i'm getting 2 exceptions:
Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection, any solutions?
-maybe the problem is related with this: Cannot load JDBC driver class 'com.postgresql.jdbc.Driver'
-no one was able to help me, I have all neccesary dependencies, but don't know what's wrong, thanks
You cannot connect because the driver is not on the classpath.
You can download from here: http://jdbc.postgresql.org/download.html.
It could solve your jdbc class loading problems.
Make sure you have wired in the SessionFactory bean into your dao implementation class.
One way of doing that is as follow:
#Resource
private SessionFactory mySessionFactory;
Let's start the following segment:
<property name="driverClassName" value="com.postgresql.jdbc.Driver"/>
I used "com.postgresql.jdbc.Driver" as well for driverClassName and got the same error as you are getting. The only difference is I gave the database connection details in a resource.xml file and used resource injection to initiate the database connectivity from Java files.
<Context>
<Resource name="jdbc/test"
auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="10000"
username="postgres" password="password"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/test?allowPublicKeyRetrieval=true"/>
</Context>
My issue got resolved and there are no issues with database connectivity after I have used driverClassName="org.postgresql.Driver" instead of driverClassName="com.postgresql.jdbc.Driver".
Try the below code instead:
<property name="driverClassName" value="org.postgresql.Driver"/>
Clean the project once or multiple times before running with the new code. Once the changes get implemented, it starts working properly.
I have an Spring project with one simple entity and a JPA repository. The entity has three variables: Name (String), active (boolean) and date (java.util.Date). Once deployed, Hibernate creates the table in my MySQL database using varchar, tinyint and datetime. All seems correct but when I create/modify an instance of the entity and call the save() method of the repository, all fields are saved except the date. Is there any know problem storing dates with a JPA repository or meaby I'm doing something wrong?
I'm not putting any code here because is only a simple class and an interface for the repository. Also, the entity is being saved. My problem is only related with Date field (and any other Date field that I could define). Having said this, if anything is needed, just ask.
EDIT:
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<import resource="infraestructure.xml" />
<jpa:repositories base-package="com.smarttabletv.repository" />
</beans>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.smarttabletv" />
<!-- Activates #Scheduled and #Async annotations for scheduling -->
<task:annotation-driven />
</beans:beans>
infraestructure.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-autowire="byName">
<!-- Scans within the base package of the application for #Components to
configure as beans -->
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="${db.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="org.hibernate.envers.auditTablePrefix"></prop>
<prop key="org.hibernate.envers.auditTableSuffix">_history</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
db.properties
db.password=
db.username=
db.url=jdbc:mysql://ip:3306/smarttabletv
db.dialect=org.hibernate.dialect.MySQLInnoDBDialect
db.driver=com.mysql.jdbc.Driver
Code not working
Task task = taskService.findDispatchableTask();
task.setDispatched(true); // This is saved
task.setEndDate(new Date()); // But this not
taskService.save(task);
Task class first lines
#Entity
#Table(name = "sttv_tasks")
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "tsk_id")
private Long id;
#Column(name = "tsk_end_date")
private Date endDate;
You forgot to add the Temporal annotation on the endDate, specifying if the date, time, or both should be persisted.
#Column(name = "tsk_end_date")
#Temporal(TemporalType.TIMESTAMP)
private Date endDate;
I'm new to Spring, using version 3.2 with Hibernate 4.1.9Final, it seems that #Transactional annotations are being ignored, i've tried to set it on the controller method, service method and dao, no success
I've included the packages in
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<display-name>
Spring
</display-name>
<description>
Spring Test
</description>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springapp-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<context:component-scan base-package="com.test.web.controllers,com.test.service.impl" />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull"/>
<property name="username" value="medi"/>
<property name="password" value="tech"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingLocations" value="classpath*:com/test/model/hbm/**/*.hbm.xml" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.current_session_context_class=thread
</value>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="categoryDAO" class="com.test.dao.hibernate.HibernateCategoryDAO">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="categoryService" class="com.test.service.impl.Categories" scope="singleton">
<property name="dao" ref="categoryDAO"></property>
</bean>
</beans>
My Test Controller
public class HelloController {
#Autowired
private CategoryService categories;
public HelloController() {
System.out.println("test!!!");
}
public void setCategoryService(CategoryService categories) {
this.categories = categories;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
#Transactional
public String getIndex() {
Category c = new Category();
c.setName("Test");
categories.save(c);
return "index";
}
}
Stacktrace:
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at $Proxy19.save(Unknown Source)
at com.test.dao.hibernate.HibernateCategoryDAO.save(HibernateCategoryDAO.java:20)
at com.test.service.impl.Categories.save(Categories.java:21)
at com.test.web.controllers.HelloController.getIndex(HelloController.java:36)
at com.test.web.controllers.HelloController$$FastClassByCGLIB$$aa12a3a3.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
Removed hibernate.current_session_context_class=thread and it works. Spring injecting its own session context managing implementation when using Spring transaction support layer?
You are using #Transactional in the controller layer. It should be in your Service layer.
Make Categories.save method #Transactional and you might get this error away.
Try to add <context:component-scan base-package="your package here">
Looks like it just can't find annotations
I have a simple (sample) web application that i have a problem with if i try chaining multiple viewresolvers. When my application is configured in the way described below, trying to access http://localhost:8080/Library/spring/initApplication will throw the error described below.
It seems as though the InitApplication is erroneously being picked up by the wrong view resolver. If i change the order of the view resolvers everything works, but im still wondering why exactly this error occurs because i cant pinpoint why it happens. Im guessing a configuration issue?
26027 ["http-bio-8080"-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'initApplication' must be of type [org.springframework.web.servlet.View], but was actually of type [library.controller.InitApplication]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:349)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:266)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
at org.springframework.web.servlet.view.ResourceBundleViewResolver.loadView(ResourceBundleViewResolver.java:196)
at org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158)
at org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77)
at org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078)
Details of the important files:
InitApplication.java
#Controller
public class InitApplication {
#RequestMapping(value = "/initApplication", method = RequestMethod.GET)
etc.......
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>testwebproj</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
</web-app>
springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/library" />
<property name="username" value="root" />
<!-- <property name="password" value="" /> -->
</bean>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<bean id="pdfViewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="1" />
<property name="basename" value="views" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="library"></context:component-scan>
</beans>
views.properties
pdfPrinter.(class)=library.controller.DummyController
It is certainly because your are mapping your view with a Controller class mate!
pdfPrinter.(class)= you should indicate a View class here!
For example to map a Controller to a jsp View, you will need to proceed like this:
login.(class)=org.springframework.web.servlet.view.JstlView
login.url=/vues/en/login.jsp
have you tried renaming your bean? You may be clobbering an internal bean used by spring