SpringMvc Application Error - spring

I created a dynamic web project with Eclipse Luna and Tomcat using Spring + JPA + Hibernate .. I've added javax.persistence jar but I always get this error. Where am I doing wrong?
This project will save a user in the user table in the database .. The form data is persisted..
This is the code of my application
error code
Avvertenza: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emf' defined in ServletContext resource [/WEB-INF/context-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5490)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
at org.hibernate.cfg.AnnotationBinder.bindDefaults(AnnotationBinder.java:276)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1402)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564)
... 21 more
bean/Utente.java
package bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Utente {
#Id
#GeneratedValue
#Column(name="id")
private Integer id;
#Column(name="cognome")
private String cognome;
#Column(name="nome")
private String nome;
#Column(name="eta")
private Integer eta;
public Integer getId(){return id;}
public void setId(Integer id){this.id=id;}
public String getCognome(){return cognome;}
public void setCognome(String cognome){this.cognome=cognome;}
public String getNome(){return nome;}
public void setNome(String nome){this.nome=nome;}
public Integer getEta(){return eta;}
public void setEta(Integer eta){this.eta=eta;}
#Override
public String toString(){
return "id: "+id+" cognome:"+cognome+" nome"+nome;
}//toString
}//Utente
controller/HomeController.java
package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import persistence.UtenteDAOImpl;
import bean.Utente;
#Controller
public class HomeController {
#Autowired
UtenteDAOImpl utenteDAO;
#RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView welcome(){
return new ModelAndView("index", "command", new Utente());
}//welcome
#RequestMapping(value="/registra",method=RequestMethod.POST)
public void saveUtente(#ModelAttribute Utente utente){
utenteDAO.aggiungiUtente(utente);
}
}//HomeController
index.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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Dati utente</h2>
<form action="/SpringMVCFormHibernate/registra">
<p>
<label>Cognome</label><br/>
<input type="text" id="cognome"/>
</p>
<p>
<label>Nome</label><br/>
<input type="text" id="nome"/>
</p>
<p>
<label>Eta</label><br/>
<input type="text" id="eta"/>
</p>
<input type="submit" id="submit" value="registra">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" id="WebApp_ID" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<display-name>Spring MVC Form</display-name>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>context</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context-servlet.xml</param-value>
</context-param>
</web-app>
context-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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.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-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="controller"/>
<tx:annotation-driven/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property value="/WEB-INF/jsp/" name="prefix"/>
<property value=".jsp" name="suffix"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_hibernate"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="10"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="persistence"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<bean id="utente" class="bean.Utente"/>
</beans>

NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
is quite clear. You have a JPA 2.0 API jar in the CLASSPATH but it is expecting JPA 2.1 API jar? And while checking that you check what version of your JPA implementation you have there, and which version of JPA it requires

Related

java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver

i have a problem about Bean creation in xml definer.
When i run the application on server it shows me the first page but when i go to /customer/list it gives me http error - 500
In the tutorial he does nothing else of what i've done.
I can't show you all the .JAR files in the LIB but i have all the dependency he has in the tutorial example.
I am not using Maven, its a normal Dynamic Web Project so i can't just pass to Maven Project.
I've tried to change the Bean name trying to understand if it was a problem of existing object.
This is my Servlet:
package com.luv2code.testdb;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestDbServlet
*/
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setup connection variables
String user = "springstudent";
String pass = "springstudent";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
String driver = "com.mysql.cj.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
This is my CustomerController:
package com.luv2code.springdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping("/list")
public String listCustomer(Model theModel) {
return "list-customer";
}
}
This is my definer.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC;allowPublicKeyRetrieval=true" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
and this is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring-mvc-crud-demo</display-name>
<absolute-ordering />
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The exception encountered is:
*org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver *
java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.Environment *
You could try to add this jar to your project net.bytebuddy.
But I recommend to use maven for these purposes.

#Autowired not working in AuthenticationSuccessHandler of Spring-Security

Hi I am unable to access spring bean in AuthenticationSuccessHandler of spring security.I saw many post in stackoverflow but no luck nothing works,
Spring-MVC-3.2.6
Spring Security - 3.2.0
Please find the below file for reference,
servlet-config.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:p="http://www.springframework.org/schema/p"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.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-3.2.xsd">
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<context:component-scan base-package="com.taskmanagement" />
<security:global-method-security
pre-post-annotations="enabled">
<!--register security:expression-handler To use rights(hasPermission) along
wih roles(hasRole) -->
<security:expression-handler ref="TaskManagementExpressionHandler" />
</security:global-method-security>
<bean id="TaskManagementExpressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator">
<bean id="permissionEvaluator"
class="com.taskmanagement.security.TaskManagementPermissionEvaluator">
<property name="dataSource" ref="dataSource"></property>
</bean>
</property>
</bean>
<!--mvc:resources is used for static file location location is a folder
underneath spring will look for static resources 2)Also we should configure
this in web.xml.Because right now we configured only for .html not .pdf -->
<mvc:resources location="pdfs" mapping="/pdfs/**" />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:resources mapping="/webjars/**" location="/webjars/"/>
<!-- p:basename :: Here we should give the property file name here the name
is messages. This bean is simply used by spring for message resource -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages" />
<!--This bean is simply used by spring for message resource for locale resolver
it uses interceptor -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
p:defaultLocale="en" />
<!-- Now register locale interceptor.That's it for locale -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="language"></bean>
</mvc:interceptors>
<import resource="hibernate-config.xml" />
<!-- Method1 Long hand <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix"
value=".jsp"></property> </bean> -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="3"></bean>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"
p:order="2" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean
class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="applicaton/json"></entry>
<entry key="xml" value="applicaton/xml"></entry>
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"></property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers -->
<property name="favorPathExtension" value="false" />
</bean>
<bean id="tilesviewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"></property>
<property name="order" value="0"></property>
</bean>
<!-- Helper class to configure Tiles 2.x for the Spring Framework -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/tiles2/TilesConfigurer.html -->
<!-- The actual tiles templates are in the tiles-definitions.xml -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/config/tiles-definitions.xml</value>
</list>
</property>
</bean>
<import resource="classpath:/WEB-INF/config/security-config.xml" />
</beans>
security-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- We are making security as default bean instead of beans -->
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.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-3.2.xsd">
<!-- This will activate the expressions in spring valid expr are : hasRole,hasAnyRole,hasPermission,PermitAll -->
<http use-expressions="true" auto-config="true">
<!-- Allow login only user must have ROLE_USER -->
<!-- The below line is for spring basic authentication without using custom
controller * jsp <http-basic/> -->
<!-- For custom login use the below code -->
<intercept-url pattern="/login*" access="permitAll" /> <!-- Without this it won't allow the access for login.html because in the
above we restrained URL with ROLE_USER -->
<intercept-url pattern="/resources/**" access="permitAll"/>
<intercept-url pattern="/loginFailed.html" access="permitAll" />
<intercept-url pattern="/logout.html" access="permitAll" />
<intercept-url pattern="/signup.html" access="permitAll" />
<intercept-url pattern="/signupSubmit.html" access="permitAll" />
<intercept-url pattern="/session-expired.html" access="permitAll" />
<intercept-url pattern="/updatepassword*" access="permitAll"/>
<intercept-url pattern="/changePassword*" access="permitAll"/>
<intercept-url pattern="/403.html" access="permitAll" />
<!--<intercept-url pattern="/**" access="ROLE_USER"/> if we activate expression
then we should use hasRole or hasAnyRole or hasPermission or PermitAll in
access other wise it ill throw http status 500 failed to evaluate expr error -->
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.html"
authentication-failure-url="/loginFailed.html" authentication-success-handler-ref="successAuthenticationHandler"/>
<logout logout-success-url="/logout.html" delete-cookies="JSESSIONID"/>
<access-denied-handler error-page="/403.html" />
<remember-me key="myAppKey" user-service-ref="userDetailsService"/>
<!-- This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated.
Often you would prefer to prevent a second login, in which case you can use -->
<session-management invalid-session-url="/session-expired.html">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/session-expired.html"/>
</session-management>
</http>
<!-- Password Hashing Bean -->
<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" >
<beans:constructor-arg name="strength" value="12" />
</beans:bean>
<!-- After successfull login using the below handler we will map to corresponding screen -->
<beans:bean id="successAuthenticationHandler"
class="com.taskmanagement.authentication.handler.SuccessAuthenticationHandler"/>
<authentication-manager>
<!-- <authentication-provider user-service-ref="userDetailsService"/> -->
<authentication-provider>
<!-- The below code will configure md5 <password-encoder hash="md5"></password-encoder> -->
<!-- The below code will configure bcrypt -->
<password-encoder ref="passwordEncoder"></password-encoder>
<!--<jdbc-user-service data-source-ref="dataSource" /> -->
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,password, enabled from users where username=?"
authorities-by-username-query="select username, authority from authorities where username =? " />
</authentication-provider>
</authentication-manager>
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"></beans:property>
<beans:property name="url"
value="jdbc:mysql://localhost:3306/taskmgmt"></beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="root"></beans:property>
</beans:bean>
<beans:bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>
<!-- Session Timeout & Concurrency control -->
</beans:beans>
SuccessAuthenticationHandler.java
package com.taskmanagement.authentication.handler;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import com.taskmanagement.dao.CommonDao;
#Service("authenticationSuccessHandler")
public class SuccessAuthenticationHandler implements AuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
private CommonDao userDao;
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
System.out.println("onAuthenticationSuccess::Entered");
User user = (User)authentication.getPrincipal();
String userName = user.getUsername();
System.out.println("userName::"+user.getUsername());
com.taskmanagement.model.User userBo = this.userDao.get(com.taskmanagement.model.User.class,userName);
userBo.setLastLogggedIn(new Date());
userDao.saveOrUpdate(user);
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/** Builds the target URL according to the logic defined in the main class Javadoc. */
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
System.out.println("isUser::"+isUser+"::isAdmin::"+isAdmin);
if (isUser) {
return "/adminEntryAction.html";
} else if (isAdmin) {
return "/addMinutes.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
In SuccessAuthenticationHandler.java while accessing this.userDao it throws nullPointerException could anyone please guide me to resolve this issue.
Kindly let me know for any queries.
CommonDao.java
public interface CommonDao {
public <T> Integer save(final T obj);
public <T> String saveRetString(final T obj);
public <T> void delete(final Class<T> type,final String obj);
public <T> T get(final Class<T> type, final String id);
public <T> T merge(final T o);
public <T> void saveOrUpdate(final T o);
public <T> List<T> getAll(final Class<T> type);
public List<UserBO> searchContacts(String name);
}
CommonDaoImpl.java
#Repository
public class CommonDaoImpl implements CommonDao {
#Autowired
HibernateSessionFactory hibernateSessionFactory;
#SuppressWarnings("unchecked")
public <T> Integer save(final T obj){
//interact wth DB
}
public <T> String saveRetString(final T obj){
//interact wth DB
}
public <T> void delete(final Class<T> type,final String id){
//interact wth DB
}
#SuppressWarnings("unchecked")
public <T> T get(final Class<T> type, final String id){
return (T) hibernateSessionFactory.getSession().get(type, id);
}
#SuppressWarnings("unchecked")
public <T> T merge(final T o){
//interact wth DB
}
/***/
public <T> void saveOrUpdate(final T o){
//interact wth DB
}
#SuppressWarnings("unchecked")
public <T> List<T> getAll(final Class<T> type) {
//interact wth DB
}
#SuppressWarnings("unchecked")
#Override
public List<UserBO> searchContacts(String name) {
//interact wth DB
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- It is need for spring security to intercept URL -->
<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> <!-- We are going to send every rquest to this filter -->
</filter-mapping>
<!-- It will tell where the spring security configuration xml is -->
<!-- Bootstraps the root web application context before servlet initialization -->
<!-- It will bootstrap our spring security -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
<servlet>
<servlet-name>taskManagementServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>taskManagementServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>taskManagementServlet</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>taskManagementServlet</servlet-name>
<url-pattern>/pdfs/**</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout> <!-- THis specify timeout in minutes -->
</session-config>
<display-name>Archetype Created Web Application</display-name>
</web-app>
After added the following load on startup(refer below code),
<servlet>
<servlet-name>taskManagementServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
Getting the following exception,
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/config/security-config.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765) [catalina.jar:7.0.23]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260) [catalina.jar:7.0.23]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.23]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525) [catalina.jar:7.0.23]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515) [catalina.jar:7.0.23]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_18]
at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_18]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_18]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_18]
at java.lang.Thread.run(Thread.java:619) [na:1.6.0_18]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:140) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
... 22 common frames omitted
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/config/security-config.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:140)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
... 22 more
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/TaskManagement] startup failed due to previous errors
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

Spring MyBatis expected at least 1 bean which qualifies as autowire candidate for this dependency

i have a trouble with my Spring MyBatis Project.
Here the classes of the 4 packages tiers:
controller
mapper
model
service
com.mb.alf.controller
ServizioController.java
package com.mb.alf.controller;
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.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.mb.alf.model.Servizio;
import com.mb.alf.service.ServizioService;
#Controller
#SessionAttributes("servizio")
public class ServizioController {
#Autowired
private ServizioService servizioService;
#RequestMapping("/returnServizio")
public ModelAndView returnServizio() {
Servizio servizio = servizioService.getServizio();
return new ModelAndView("returnServizio", "servizio", servizio); }}
com.mb.alf.mapper
ServizioMapper.java
package com.mb.alf.mapper;
import org.apache.ibatis.annotations.Select;
import com.mb.alf.model.Servizio;
public interface ServizioMapper {
#Select("select s.ser_puntopresa, s.ser_oldcodser from serviz s where s.ser_ute = '01' and S.SER_PUNTOPRESA = 101")
public Servizio getServizio();
}
com.mb.alf.model
Servizio.java
package com.mb.alf.model;
public class Servizio {
Integer serv_puntopresa;
Integer ser_oldcodser;
public Integer getSer_oldcodser() {
return ser_oldcodser; }
public void setSer_oldcodser(Integer ser_oldcodser) {
this.ser_oldcodser = ser_oldcodser; }
public Integer getServ_puntopresa() {
return serv_puntopresa; }
public void setServ_puntopresa(Integer num) {
this.serv_puntopresa = num; }
}
com.mb.alf.service
ServizioService.java
package com.mb.alf.service;
import com.mb.alf.model.Servizio;
public interface ServizioService {
Servizio getServizio();
}
ServizioServiceImpl.java
package com.mb.alf.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mb.alf.mapper.ServizioMapper;
import com.mb.alf.model.Servizio;
#Component #Service("servizioService")
public class ServizioServiceImpl implements ServizioService {
#Autowired
private ServizioMapper servizioMapper;
#Transactional
public Servizio getServizio() {
return servizioMapper.getServizio(); } }
Here my XML files:
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">
<servlet>
<servlet-name>myBatisServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myBatisServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<display-name>Archetype Created Web Application</display-name>
</web-app>
springConfig.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: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.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.mb.alf" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<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="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#MYHOST:orcl"/>
<property name="username" value="USER"/>
<property name="password" value="PASSWORD"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.mb.alf.model"/>
<property name="mapperLocations" value="classpath*:com/mb/alf/mapper/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mb.alf.mappers" />
</bean>
</beans>
It gets this Exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servizioController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mb.alf.service.ServizioService com.mb.alf.controller.ServizioController.servizioService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servizioService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mb.alf.mapper.ServizioMapper com.mb.alf.service.ServizioServiceImpl.servizioMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mb.alf.mapper.ServizioMapper] 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)}
Please, how and where can I implement the correct bean?
Thanks in advance
Perhaps you should seperate the mybatis setup in another xml instead of putting it in current springConfig.xml
For example:
web.xml add the following:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/spring.xml;
classpath:conf/spring-mybatis.xml
</param-value>
</context-param>
...
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
In spring-mybatis.xml*, add your dataSource, transactionManager, sqlSessionFactory, sqlSession and org.mybatis.spring.mapper.MapperScannerConfigurer.
One example can be found here https://github.com/liratanak/SpdSample-Spring-MVC-3-MyBatis-3-Tiles-3

Hibernate annotations with DataSource en sessionFactory in Spring project

I'm trying to use Hibernate's annotation with a dataSource in my web Application with Spring but I've an error "NoSuchBeanDefinitionException" and I don't know why. From my point of view all is correct... If somebody can help me to resolve it it's very good for me :)
Here it's my root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans">
<context:component-scan base-package="fot.manager.service, fot.manager.dao" />
<context:annotation-config />
<!-- To use transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- DataSource -->
<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/f1_tycoon" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- Hibernate -->
<bean id="sessionFactory" name="connectionDB"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>fot.manager.model.Bannissement</value>
<value>fot.manager.model.CategorieForum</value>
<value>fot.manager.model.CategorieNews</value>
<value>fot.manager.model.Commentaire</value>
<value>fot.manager.model.MessageForum</value>
<value>fot.manager.model.News</value>
<value>fot.manager.model.Pilote</value>
<value>fot.manager.model.Rang</value>
<value>fot.manager.model.SectionForum</value>
<value>fot.manager.model.Signalement</value>
<value>fot.manager.model.SujetForum</value>
<value>fot.manager.model.Utilisateur</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
</value>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
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"
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>fot.manager</display-name>
<welcome-file-list>
<welcome-file>connexion.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Ajax servlet -->
<servlet>
<servlet-name>ajax</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>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ajax</servlet-name>
<url-pattern>/ajax/*</url-pattern>
</servlet-mapping>
</web-app>
And the stacktrace :
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [fot.manager.service.NewsService] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3988)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
at java.lang.Thread.run(Unknown Source)
I've also an other error stacktrace for a Java file:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jqGridController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fot.manager.service.NewsService fot.manager.ajax.jqGridController.newsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [fot.manager.service.NewsService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3988)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fot.manager.service.NewsService fot.manager.ajax.jqGridController.newsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [fot.manager.service.NewsService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 31 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [fot.manager.service.NewsService] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 33 more
And the Java file :
package fot.manager.ajax;
import java.util.Collection;
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.ResponseBody;
import fot.manager.model.News;
import fot.manager.service.NewsService;
#Controller
#RequestMapping("/ajax")
public class jqGridController {
#Autowired
private NewsService newsService;
// Contrôleur pour afficher les news
#RequestMapping("/getNews")
#ResponseBody
public Collection<News> getNews(){
Collection<News> listNews = newsService.getAllNews();
for (News news : listNews){
System.out.println(news.getAuteur().getPseudo());
}
return listNews;
}
}
My NewsService class Implement :
package fot.manager.service.impl;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import fot.manager.dao.NewsDao;
import fot.manager.model.News;
import fot.manager.service.NewsService;
#Service("newsService")
#Transactional
public class NewsServiceImpl implements NewsService {
#Autowired
private NewsDao newsDao;
#Override
public Collection<News> getAllNews() {
return newsDao.getAllNews();
}
#Override
public News getNewsById(int id) {
return newsDao.getNewsById(id);
}
#Override
public News editNews(News news) {
return newsDao.editNews(news);
}
#Override
public News deleteNews(int id) {
return newsDao.deleteNews(id);
}
}
And the interface :
package fot.manager.service;
import java.util.Collection;
import fot.manager.model.News;
public interface NewsService {
Collection<News> getAllNews();
News getNewsById(int id);
News editNews(News news);
News deleteNews(int id);
}
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"
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">
<context:component-scan base-package="bgc.isis.generator.controller"/>
<context:annotation-config/>
<!-- Resources -->
<mvc:resources location="/resources/images/, /resources/css/, /resources/js/" mapping="/resources/**"/>
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!--
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
<!-- ViewResolver class : org.springframework.web.servlet.view.UrlBasedViewResolver -->
Thanks a lot to solve my problem :)
I'm not sure this syntax is valid (at least I can't find it in the doc):
<context:component-scan base-package="fot.manager.service, fot.manager.dao" />
I think you're looking for:
<context:component-scan base-package="fot.manager">
<context:include-filter type="regex" expression=".*\.service\..*"/>
<context:include-filter type="regex" expression=".*\.dao\..*"/>
</contextn:component-scan>
Because you've qualified NewsServiceImpl Service annotation with the newsService logical name, you need to match this with the corresponding Qualifier annotation otherwise Spring will attempt to inject an unqualified NewsService which doesnt exist.
#Autowired
#Qualifier("newsService")
private NewsService newsService;
Alternatively you could simply remove the logical name NewsServiceImpl's #Service annotation

get Null pointer Exception when try to access model class in dwr function

My SessionFactory object is #Autowired
package com.ravi.dao.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ravi.dao.UserDao;
import com.ravi.model.User;
#Repository("userDao")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<User> listUsers()
{
System.out.println("UserDaoImpl - listUsers");
return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
}
#Override
public void saveUser(User user)
{
System.out.println("UserDaoImpl - saveUser");
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUserByUserEmail(String userEmail)
{
System.out.println("UserDaoImpl - getUserByUserEmail");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list();
}
#SuppressWarnings("unchecked")
#Override
public List<User> validateLoginUser(String userEmail, String password)
{
System.out.println("userEmail -- "+userEmail+" password --"+password);
System.out.println("UserDaoImpl - validateLoginUser");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail and password=:password").setString("userEmail", userEmail).setString("password",password).list();
}
}
i create on dwr function which is below.
package com.ravi.dwr;
import java.util.List;
import com.ravi.dao.daoImpl.UserDaoImpl;
import com.ravi.model.User;
public class ForgotPwd
{
public void sendMail(String EmailId)
{
System.out.println("DWR Called.");
UserDaoImpl userDaoImpl=new UserDaoImpl();
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
User user=lstUser.get(0);
System.out.println("DWR Called.-- userEmail :"+user.getUserEmail());
}
}
when i want to try to print userEmail . null pointer exception is generated # return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list(); this point.
my spring-servlet.xml cofiguration.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.ravi"/>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- <bean id="sessionFactory" -->
<!-- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ravi.model.User</value>
<value>com.ravi.model.Language</value>
<value>com.ravi.model.Questions</value>
<value>com.ravi.model.QuestionOptions</value>
<value>com.ravi.model.Admin</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="SessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
i don't want to remove #Autowired annotation in sessionFactory object. so please suggest me the best way to access or configure dwr function. other way i tried without using #Autowired annotation but in that case i have to entry all bean class in my spring-servlet.xml and also configure. hibernate.cfg.xml file.
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
UserLoginController --> showUserLogin
INFO (org.directwebremoting.log.startup:157) - Starting: DwrServlet v3.0.0-RC2-final-312 on Apache Tomcat/7.0.50 / JDK 1.7.0_10 from Oracle Corporation at `enter code here`/OnlineQuestion
DWR Called.
INFO (org.directwebremoting.log.accessLog:427) - Method execution failed:
java.lang.NullPointerException
at com.ravi.dwr.ForgotPwd.sendMail(ForgotPwd.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.directwebremoting.impl.CreatorModule$1.doFilter(CreatorModule.java:229)
at org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:241)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:379)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:332)
at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:104)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:141)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChai
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
Assuming you want to use Spring MVC with DWR, try following code:
WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
...
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
...
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
<dwr:controller id="dwrController" />
<dwr:annotation-scan base-package="com.ravi.dwr" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/dwr/**/*">dwrController</prop>
</props>
</property>
</bean>
<context:component-scan base-package="com.ravi" />
...
</beans>
ForgotPwd.java
package com.ravi.dwr;
...
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
...
#RemoteProxy
public class ForgotPwd {
#Autowired
private UserDaoImpl userDaoImpl;
...
#RemoteMethod
public void sendMail(String EmailId) {
System.out.println("DWR Called.");
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
...
}
...
}

Resources