How to use lazy loading in Spring MVC? I'm using eager at this moment, but this makes my app works slowler.
This is part of my domain:
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "NEWS_TAG", joinColumns = #JoinColumn(name = "NEWS_ID"), inverseJoinColumns = #JoinColumn(name = "TAG_ID"))
private List<Tags> tags = new ArrayList<Tags>();
public List<Tags> getTags() {
return this.tags;
}
And dao:
public List<News> getSomeNews(long b, long hm) {
List<News> news = (List<News>) sessionFactory
.getCurrentSession()
.createQuery(
"from News WHERE title!='About' ORDER BY publish_time")
.setMaxResults((int) hm).setFirstResult((int) b).list();
return news;
}
Servlet-context:
<context:annotation-config />
<context:component-scan base-package="net.babobka.blog" />
<import resource="../../db/db-config.xml" />
<bean id="urlForwardController"
class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
</beans>
Db-config:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/db/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>/WEB-INF/db/hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">${jdbc.show_sql}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
</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
/WEB-INF/spring/application-security.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>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>hibernateFilterChain</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
What I have to do to solve my problem?
You can use OpenSessionInViewFilter to prevent hibernate session get closed. Add this to web.xml:
<filter>
<filter-name>hibernateFilterChain</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
#see read more here: OpenSessionInViewFilter
And remove fetch = FetchType.EAGER. #ManyToMany is LAZY by default.
Change your annotation to (fetch = FetchType.LAZY). Be aware that if you're passing the result to some code outside the transaction (such as a view template), you might encounter errors if associated objects needed by the external code haven't already been loaded.
Related
/WEB-INF/appconfig-data.xml
<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/javabegin" />
<property name="username" value="root" />
<property name="password" value="pass" />
</bean>
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="minPoolSize" value="3" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.hihoall" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="myTransactionManager" />
/WEB-INF/appconfig-root.xml
<import resource="spring-mvc-servlet.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="application-security.xml"/>
<context:component-scan base-package="com.hihoall.*"/>
<context:property-placeholder location="classpath:database.properties"/>
/WEB-INF/application-security.xml
<http auto-config="true">
<remember-me data-source-ref="dataSource" />
<access-denied-handler error-page="/accessDenied" />
<intercept-url pattern="/user" access="ROLE_USER" />
<intercept-url pattern="/admin" access="ROLE_ADMIN" />
<form-login login-page='/login' default-target-url="/user"
authentication-failure-url="/login?error=true" username-parameter="user_login"
password-parameter="password_login" />
<logout logout-success-url="/login" />
</http>
<beans:bean id="jdbcGroupsImpl" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<beans:property name="enableGroups" value="true" />
<beans:property name="enableAuthorities" value="false" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="jdbcGroupsImpl">
</authentication-provider>
</authentication-manager>
/WEB-INF/spring-mvc-servlet.xml
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
<mvc:resources mapping="/favicon.ico" location="/resources/images/favicon.ico" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<ref bean="localeChangeInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/locales/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="ru" />
</bean>
<context:component-scan base-package="com.hihoall"/>
/WEB-INF/web.xml
<display-name>spring-mvc</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/appconfig-root.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Everything works well, but If I change it a little bit
The stroke "/WEB-INF/spring-mvc-servlet.xml" has been added to web.xml
<display-name>spring-mvc</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/appconfig-root.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-mvc-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
and the stroke "import resource="spring-mvc-servlet.xml" has been deleted from /webapp/WEB-INF/appconfig-root.xml
<import resource="appconfig-data.xml"/>
<import resource="application-security.xml"/>
<context:component-scan base-package="com.hihoall.*"/>
<context:property-placeholder location="classpath:database.properties"/>
</beans>
I get the error
HTTP Status 500 - org.apache.jasper.JasperException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
What should I do to make the second variant working?
You have component-scanning in mvc config file as well as data config file:
Inside /WEB-INF/spring-mvc-servlet.xml:
<context:component-scan base-package="com.hihoall"/>
Inside /WEB-INF/appconfig-root.xml
<context:component-scan base-package="com.hihoall.*"/>
Since they are scanning the same packages, then the beans are loaded 2 times here, once by mvc config & another by root config. So they are stored in Web Application Context and another in Root Application Context.
Now the transaction management beans are defined in root config file (because you are importing /WEB-INF/appconfig-data.xml in root config file).
This is causing issue with your application, the controller classes might got the beans from web application context which do not have an idea about transaction management, so when you are doing DML operations it is failing with that error.
I ahve a spring application where an ajax call after login dosen't work.
I made the ajax function as below in CHrome dev tools snippets.
var today = new Date();
var month=today.getMonth();
var name="testuser";
$(document).ready(function(){
$.ajax({
type: "GET",
url: "ajax/getStmt",
data: "name="+name+"&month="+month,
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(msg){
alert("there was an error \n"+msg);
}
});
});
controller:
package com.cardholder.controller.ajax;
#Controller
public class StatementAjax {
#Autowired
public UserDao userDao;
//initialise logger, dao
#RequestMapping(value = "/ajax/getMonths", method = RequestMethod.GET)
public String getMonths(){
//get user from session
//get user token from session
/*UserStatement availableStmts = new UserStatement();
availableStmts.setAvailableStatements(userDao.getUserStatementMonths(user.getUser_token()));*/
return "months";
}
#RequestMapping(value = "/ajax/getStmt", method = RequestMethod.GET)
public String getStatement(#RequestParam(required = true) String name, #RequestParam(required = true) String month){
System.out.println(name+", "+month);
//get user from session
//get user token from session
/*UserStatement availableStmts = new UserStatement();
availableStmts.setAvailableStatements(userDao.getUserStatementMonths(user.getUser_token()));
ArrayList<UserStatement> s = (ArrayList<UserStatement>) userDao.getUserSelectedStatement(user.getUser_token(), 07, 2015);*/
return "statements";
}
}
Spring 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:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.cardholder,com.cardholder.orm,com.cardholder.controller.ajax" />
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<bean id="secureServiceClient" class="com.cardholder.service.SecureServiceClient">
<property name="serviceUrl" value="http://xxxx:8080/xApi/api/"></property>
<property name="serviceUserName" value="xxxx"></property>
<property name="servicePassword" value="xxxx"></property>
</bean>
<bean id="httpHeders" class="org.springframework.http.HttpHeaders">
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="errorHandler">
<bean class= "com.cardholder.service.error.ServiceClientErrorHandler" />
</property>
</bean>
<bean id="resourceLoader" class="org.springframework.core.io.DefaultResourceLoader"/>
<bean id="pdfRenderer" class="com.cardholder.controller.menunav.util.Util"/>
<bean id="serviceClientInterceptor" class="com.cardholder.service.interceptors.ServiceClientInterceptor">
<property name="serviceUserName" value="xxx"></property>
<property name="servicePassword" value="xxx"></property>
</bean>
<bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<constructor-arg name="strength" value="16" />
</bean>
<bean id="idGenerator" class="org.apache.catalina.util.SessionIdGenerator"></bean>
<bean id="sessionValidator" class="com.cardholder.session.SessionValidator"></bean>
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="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="packagesToScan" value="com.cardholder"></property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://xxxx:3306/portal" />
<property name="username" value="xxxx" />
<property name="password" value="xxxx" />
</bean>
Below is the link to a screenshot from devtools.
http://i.stack.imgur.com/EXry7.png
As far as i know the request dosent even enter the application context even if the URL its trying to access is right.
i have a debug point in the dispatcher servlet's do dispatch method which should have been the first place to be reached before any interceptors, controllers etc. i dont see any thread pausing there.
EDITS:
adding 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"
id="WebApp_ID" version="3.0"
metadata-complete="true">
<display-name>NCHP</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.*</url-pattern>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>land.htm</welcome-file>
</welcome-file-list>
</web-app>
Thanks for posting your web.xml.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.*</url-pattern>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Based on the above config Spring's dispatcher will be consulted, only if the incoming URL has some path info. e.g. login.htm, something.xx. However, if the url has no path info, like /getStmt, the dispatcher will not receive the request.
You can either change your ajax end point to some thing like /getStmt.ajax. Or add /as a url pattern in the web xml (this could have other implications, based on how other resources are served in your project).
If you are currently serving pages through xxxx.htm convention, I would recommend using xxxx.ajax convention for ajax requests.
You might also want to look at this answer : No mapping found for HTTP request with URI Spring MVC
Hope this helps.
exception:
g.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'utenteDAO': Injection of autowired dependencies
failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private org.hibernate.SessionFactory
com.mauro.soclib.dao.UtenteDAO.sessionFactory; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
matching bean of type [org.hibernate.SessionFactory] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
spring-security.xml
<beans...">
<context:annotation-config />
<context:component-scan base-package="com.mauro" />
<http auto-config='true' >
<intercept-url pattern="/admin**" access="ROLE_USER" />
<intercept-url pattern="/paginaConGrafica**" access="ROLE_USER" />
<form-login login-page="/login"
default-target-url="/paginaConGrafica"
authentication-failure-url="/error-login.html"
login-processing-url="/j_spring_security_check"/>
<logout logout-success-url="/index" />
</http>
<beans:bean id="restAuthenticationProvider"
class="com.mauro.soclib.security.customAuthenticationProvider" autowire="byType">
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider
ref="restAuthenticationProvider" />
</authentication-manager>
</beans:beans>
servlet
<?xml version="1.0" encoding="UTF-8"?>
<context:annotation-config />
<context:component-scan base-package="com.mauro.soclib" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/social_libreria" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
<bean id="UtenteValidator" class="com.mauro.soclib.validator.UtenteFormValidator" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:message" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- Scan for the domain objects with the ORM annotation -->
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="packagesToScan" value="com.mauro.soclib" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="10000000" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
web.xml:
<!-- 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>
<!-- link al config file security -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- specifiche della servlet -->
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
Add this entries to your dispatcher servlet,
<bean id="utenteDAO" class="path" />
<bean id="utenteDAOImplementation class" class="path" />
it is throwing error because you have not autowired the dependencies
EDIT:
try defining the session factory,
#Autowired
#Qualifier("sessionFactory")
public void seSessionFactory(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
change the location of the project folder and set system path and path properties accordingly .It works in our case.But we are unable to find the exact reason.
I am working with spring-mvc with hibernate, and I have deployed my application on go daddy server, when I open any html file it works well, But on opening a jsp file, gives me a 404 file not found error. Please any one can help me with the problem...?
I m using Spring 3.0,
Jdk 1.7.0_04,
apache-tomcat 6.0.32
The web.xml I'm using is
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>seekersworkroom</display-name>
<welcome-file-list>
<welcome-file>/view/Index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>imageupload</servlet-name>
<servlet-class>com.seekersworkroom.controller.imageuploadController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageupload</servlet-name>
<url-pattern>/imageupload.htm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Userimageupload</servlet-name>
<servlet-class>com.seekersworkroom.controller.UserimageuploadController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Userimageupload</servlet-name>
<url-pattern>/Userimageupload.htm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>seekersworkroom</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>seekersworkroom</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>seekersworkroom-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/seekersworkroom-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
</web-app>
The welcome doesnot dispaly index.jsp file but if the same is replaced by index.html it shows this file. And by opening any url eith .jsp extension it shows 404 error.
seekersworkroom-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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="/login/*.htm" id="AdminprofileController" class="com.seekersworkroom.controller.AdminprofileController">
</bean>
<bean name="/Index/*.htm" id="IndexController" class="com.seekersworkroom.controller.IndexController">
<property name="indexDAO" ref="IndexDAO" />
<property name="skillsaddedDAO" ref="SkillsaddedDAO" />
<property name="skillsDAO" ref="SkillsDAO"></property>
<property name="userDAO" ref="UserDAO" />
<property name="acountryDAO" ref="acountryDAO" />
<property name="bregDAO" ref="BregistrationDAO" />
<property name="cregistrationDAO" ref="CregistrationDAO" />
<property name="ccontactDAO" ref="CcontactDAO" />
<property name="caddressDAO" ref="CaddressDAO" />
<property name="asubcategoryDAO" ref="AsubcategoryDAO" />
<property name="cportfolioDAO" ref="CportfolioDAO" />
<property name="keywordDAO" ref="KeywordDAO" />
<property name="bcreatejobDAO" ref="BcreatejobDAO" />
<property name="messageDAO" ref="messageDAO"></property>
<property name="userimageDAO" ref="UserimageDAO" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/view/" p:suffix=".jsp" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/skw"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="mappingResources">
<list>
<value>com/seekersworkroom/VO/User.hbm.xml</value>
<value>com/seekersworkroom/VO/buyerregistration.hbm.xml</value>
<value>com/seekersworkroom/VO/contractorregistration.hbm.xml</value>
<value>com/seekersworkroom/VO/Contractorcontact.hbm.xml</value>
<value>com/seekersworkroom/VO/Contractoraddress.hbm.xml</value>
<value>com/seekersworkroom/VO/Contractorkeyword.hbm.xml</value>
<value>com/seekersworkroom/VO/Userimage.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="acountryDAO" class="com.seekersworkroom.DAO.AcountryDAO" >
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>
<bean id="AcategoriesDAO" class="com.seekersworkroom.DAO.AcategoriesDAO" >
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>
</beans>
This is the servlet file in which the annotaions are used to cal to particular controllers.
This servlet contains the beans through which the request is redirected to particular controllers.
But the main problem is jsp file is not working only...
What can I do in web.xml so that it allows me to access the jsp file on server side??
Is that the problem with Spring framework or the web.xml file is missing something???
I assume the jsp you are accessing is outside of your WEB-INF folder. In such cases, use <mvc:resources mapping="/static/**" location="/" /> in your seekersworkroom-servlet.xml; and access the jsp using url http://yourdomain/static/yourjspname.jsp.
Also, you may not need to protect your static resources; So, use
<http pattern="/static/**" security="none" xmlns="http://www.springframework.org/schema/security"/> in your spring security configuration file
I want to use OpenSessionInViewFilter in my JSF 2.1+Spring 3.1+Hibernate 3.6.6 project
in order to get rid of the .LazyInitializationException.
Although i declare the filter in web.xml i keep getting ;
org.hibernate.LazyInitializationException: failed to lazily initialize
a collection of role: pts.entity.Invention.inventors, no
session or session was closed
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.tt</url-pattern>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>excite-bike</param-value>
</context-param>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
My applicationContext.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"
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">
<import resource="classpath:applicationContext-security.xml" />
<context:annotation-config />
<context:component-scan base-package="pts.component" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>pts.entity</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/PTS" />
<property name="username" value="root" /> <property name="password"
value="" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"
name="template">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="txManager" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="pts.scope.ViewScope" />
</entry>
</map>
</property>
</bean>
</beans>
I use spring managed(HibernateTemplate) hibernate daos for db operations.Thanks for the help.
You just have to be sure that you are not redirecting between JSF view for example:
In this view your Open Session in vew Filter will work:
<navigation-rule>
<from-view-id>start.xhtml</from-view-id>
<navigation-case>
<from-outcome>page1</from-outcome>
<to-view-id>page1.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
and if you modify this example this way:
<navigation-rule>
<from-view-id>start.xhtml</from-view-id>
<navigation-case>
<from-outcome>page1</from-outcome>
<to-view-id>page1.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
Your Filter will bnot help you because you are redirecting and this is completely new request and your original Hibernate session is already closed.
Inspired by this post:
OpenSessionInViewFilter +Redirect in JSF
When does it fail? I can see that you use Spring Security and have springSecurityFilterChain defined in you web.xml. And would assume that filter loads user from database and user has lazy collection that is accessed later, when Hibernate session created during authentication is propably closed, before OpenSessionInView filter starts executing.
Remember that filter-mapping order makes sense, filter executed in the order of their filter mappings are declared. I would try reorder them first.