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
Related
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.
This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I have been trying to work my Spring Hibernate Web Sample in Eclipse in Tomcat. Unfortunately, I get the following warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found
for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet
with name 'appServlet'
What I need to do for the warning ? As far as I see , I could not see an exact solution for that. I will be appreciated if you can help me.
This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
class>org.springframework.web.context.ContextLoaderListener</listener- class>
</listener>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/pages/*</url-pattern>
</servlet-mapping>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param- value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
This is servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/TestDB" />
<beans:property name="username" value="pankaj" />
<beans:property name="password" value="pankaj123" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.journaldev.spring.model.Person</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<beans:property name="personDAO" ref="personDAO"></beans:property>
</beans:bean>
<context:annotation-config />
<!-- <context:component-scan base-package="com.journaldev.spring, com.journaldev.spring.dao, com.journaldev.spring.model, com.journaldev.spring.service" /> -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
You should add
<context:component-scan base-package="com.journaldev" />
Controller Class Code :
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.model.Person;
import com.journaldev.spring.service.PersonService;
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required = true)
#Qualifier(value = "personService")
public void setPersonService(PersonService ps) {
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
// For add and update person both
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p) {
if (p.getId() == 0) {
//new person, add it
this.personService.addPerson(p);
} else {
//existing person, call update
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
#RequestMapping("/remove/{id}")
public String removePerson(#PathVariable("id") int id) {
this.personService.removePerson(id);
return "redirect:/persons";
}
#RequestMapping("/edit/{id}")
public String editPerson(#PathVariable("id") int id, Model model) {
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
I want to autowire my userService, but I'm getting an error. I have:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd">
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
dispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<context:annotation-config/>
<context:component-scan base-package="com.andrylat.rgz.ocean.controllers" />
<context:component-scan base-package="com.andrylat.rgz.ocean.services" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<tx:annotation-driven />
application-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- DataAccess -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="user" value="rgz1002"/>
<property name="password" value="aqweds"/>
</bean>
<context:component-scan base-package="com.andrylat.rgz.ocean.dao"/>
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.andrylat.rgz.ocean.domains</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<context:component-scan base-package="com.andrylat.rgz.ocean.domains"/>
<bean id="userDAO" class="com.andrylat.rgz.ocean.dao.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userService"
class="com.andrylat.rgz.ocean.services.UserService">
<property name="userDAO" ref="userDAO" />
</bean>
<bean id="userServiceForSecurity"
class="com.andrylat.rgz.ocean.services.UserService">
<property name="userDAO" ref="userDAO" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.andrylat.rgz.ocean.services.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>
<!-- Spring Security -->
<bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
</bean>
<sec:http auto-config="true" use-expressions="true">
<!--access-denied-handler error-page="/403" /-->
<sec:logout logout-success-url="/index.htm" />
<sec:form-login login-page="/login.htm"
default-target-url="/Ocean/test/testpage.htm"
authentication-failure-url="/login.htm?error=1" />
<sec:intercept-url pattern="/test/*"
access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
<sec:intercept-url pattern="/*"
access="permitAll" />
<sec:intercept-url pattern="/resources/**"
access="permitAll" />
<sec:csrf />
</sec:http>
<!--sec:authentication-manager>
<sec:authentication-provider>
<sec:jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select login, password, enabled from users where login =? "
authorities-by-username-query=
"select login, userrole from userroles where login =? " />
<sec:password-encoder ref="passwordEncoder" />
</sec:authentication-provider>
</sec:authentication-manager-->
<sec:authentication-manager>
<sec:authentication-provider user-service-ref="userServiceForSecurity" >
<sec:password-encoder ref="passwordEncoder" />
</sec:authentication-provider>
</sec:authentication-manager>
UserService.java
#Service("userService") public class UserService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Transactional(readOnly = true)
#Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
com.andrylat.rgz.ocean.domains.User user = userDAO.findByUserName(username);
List<GrantedAuthority> authorities
= new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(user.getRole ()));
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(com.andrylat.rgz.ocean.domains.User user,
List<GrantedAuthority> authorities) {
return new User(user.getLogin(), user.getPassword(),
user.getEnabled(), true, true, true, authorities);
}}
IndexController.java
#Controller public class IndexController {
//#Autowired
//#Qualifier("userService")
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Autowired
private SessionFactory sessionFactory;
#RequestMapping (value="/index", method=RequestMethod.GET)
private ModelAndView getIndexPage (){
if (sessionFactory==null) {
System.err.println("sessionFactory is null!");
} else {
System.err.println("sessionFactory OK!");
}
return new ModelAndView ("index");
}
#RequestMapping (value="/login", method=RequestMethod.GET)
private ModelAndView getLoginPage (){
return new ModelAndView ("login");
} }
Problem: my UserService in IndexController.java don't autowired! And i was added "sessionFactory" and it don't autowired too. "SessionFactory" is only null and when i write annotation to UserService i have next stacktrace (from jsp):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.andrylat.rgz.ocean.services.UserService com.andrylat.rgz.ocean.controllers.IndexController.userService; nested exception is java.lang.IllegalArgumentException: **Can not set com.andrylat.rgz.ocean.services.UserService field com.andrylat.rgz.ocean.controllers.IndexController.userService to com.sun.proxy.$Proxy158**
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
I don't understand why I can't get this UserService and my sessionFactory is null.
Seems like the problem with the application-context.xml naming.
So, Ensure that the file applicationContext.xml exists with proper name (should not be application-context.xml) in the WEB-INF folder so that the sessionFactory bean will be loaded. Otherwise, the sessionFactory bean object will be null.
Error was in
private UserService userService;
UserService is class and not interface. I create interface UserServiceI (UserService is implement UserServiceI) and write in IndexController
#Autowire
private UserServiceI userService;
All works!
I'm working on a spring project and I'm trying to apply sprin security.The problem is that when I add spring-security.xml at contextConfigurationLocation parameters for some reason I can't figure out service beans are not autowired at controllers and I get
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.ibios.services.ArticleCategoryService] 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:952)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:821)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4149)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4458)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
spring security xml file is:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<debug/>
<http pattern="/resources" security="none" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll"/>
<intercept-url pattern="/logout" access="permitAll"/>
<intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/user" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>
<form-login login-page="/login"
authentication-failure-url="/login/failure"
default-target-url="/"/>
<access-denied-handler error-page="/denied"/>
<logout invalidate-session="true"
logout-success-url="/logout/success"
logout-url="/logout"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
</authentication-provider>
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.ibios.services.impl.CustomUserDetailService"/>
root-context xml is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:project.properties" />
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}"/>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:/META-INF/persistence.xml</value>
</list>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="entityManager" />
<property name="dataSource" ref="datasource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="terminologyService" class="com.ibios.services.impl.TerminologyServiceImpl" />
<bean id="articleCategoryService" class="com.ibios.services.impl.ArticleCategoryServiceImpl" />
<bean id="exerciseCategoryService" class="com.ibios.services.impl.ExerciseCategoryServiceImpl"/>
<bean id="exerciseService" class="com.ibios.services.impl.ExerciseServiceImpl"/>
<bean id="articleService" class="com.ibios.services.impl.ArticleServiceImpl"/>
<bean id="customUserDetailsService" class="com.ibios.services.impl.CustomUserDetailService"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<jpa:repositories base-package="com.ibios.repositories" />
<context:component-scan base-package="com.ibios.web" />
</beans>
articleCategory service impl class is:
public class ArticleCategoryServiceImpl implements ArticleCategoryService{
#Resource
ArticleCategoryRepository articleCategoryRepository;
#Override
public void create(ArticleCategory articleCategory) {
articleCategoryRepository.saveAndFlush(articleCategory);
}
#Override
public void update(ArticleCategory articleCategory) {
articleCategoryRepository.saveAndFlush(articleCategory);
}
#Override
public void delete(ArticleCategory articleCategory) {
articleCategoryRepository.delete(articleCategory);
}
#Transactional
#Override
public List<ArticleCategory> findAll() {
List<ArticleCategory> articleCategories = articleCategoryRepository.findAll();
return articleCategories;
}
#Override
public Page<ArticleCategory> findAll(Pageable pageable) {
PageRequest page1 = new PageRequest(pageable.getPageNumber(),
pageable.getPageSize(), Direction.DESC, "id");
Page<ArticleCategory> categories = articleCategoryRepository.findAll(page1);
return categories;
}
#Override
public ArticleCategory getById(Integer id) {
ArticleCategory articleCategory = articleCategoryRepository.findOne(id);
return articleCategory;
}
#Override
public List<ArticleCategory> findLatest() {
List<ArticleCategory> latest=articleCategoryRepository.findLatest();
return latest;
}
}
and the controller class is
#Controller
public class AddArticleCategoryController {
#Autowired
private ArticleCategoryService articleCategoryService;
#RequestMapping(value = "/addArticleCategory", method = RequestMethod.POST)
public String addArticleCategory(#ModelAttribute("articleCategory") ArticleCategory articleCategory, BindingResult result) {
articleCategory.setCreated(Calendar.getInstance());
articleCategoryService.create(articleCategory);
return "addArticleCategory";
}
#RequestMapping(value = "/addArticleCategory", method = RequestMethod.GET)
public ModelAndView showrticleCategory(#ModelAttribute ArticleCategory articleCategory, BindingResult result) {
return new ModelAndView("addArticleCategory", "articleCategory", new ArticleCategory());
}
#RequestMapping(value = "/showArticleCategories", method = RequestMethod.GET)
public String showArticleCategories(Model model, #PageableDefaults(pageNumber = 0, value = 15) Pageable pageable) {
Page<ArticleCategory> page = articleCategoryService.findAll(pageable);
model.addAttribute("page", page);
return "showArticleCategories";
}
#RequestMapping(value = "/editArticleCategory", method = RequestMethod.GET)
public String editArticleCategory(#RequestParam("id") String id, Model model) {
ArticleCategory articleCategory = articleCategoryService.getById(Integer.parseInt(id));
model.addAttribute("articleCategory", articleCategory);
return "editArticleCategory";
}
#RequestMapping(value = "/editArticleCategory", method = RequestMethod.POST)
public String editArticleCategorires(#ModelAttribute("articleCategory") ArticleCategory articleCategory, BindingResult result) {
System.out.println("CREATED:" + (String) result.getFieldValue("created"));
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date createdDate = formatter.parse((String) result.getFieldValue("created"));
Calendar created = Calendar.getInstance();
created.setTime(createdDate);
articleCategory.setCreated(created);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
articleCategoryService.update(articleCategory);
return "showArticleCategories";
}
public ArticleCategoryService getArticleCategoryService() {
return articleCategoryService;
}
public void setArticleCategoryService(ArticleCategoryService articleCategoryService) {
this.articleCategoryService = articleCategoryService;
}
}
the web.xml part for spring security is:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
<param-value>/WEB-INF/spring/spring-security.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<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>
Up until now I've tried to use ArticleCategoryService interface instead of the implementing class,I've set proxy-target-class to "true" at the transaction manager all of them with no results.
Try to add the #Service annotation to the ArticleCategoryServiceImpl
Change your web.xml from
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
<param-value>/WEB-INF/spring/spring-security.xml</param-value>
</context-param>
To:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml</param-value>
</context-param>
I have been struggling to make all of this work since days now and don't know what to do. I believe I went through every single post on the subject here on SO and went through douzens of tutorials...
Here is the message I am having at this time:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fruitController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.controller.FruitController.setFruitManager(com.service.FruitManager); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.service.FruitManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
I have been able to solve this error in the past, but only to have a new one "No session found for current thread". When not having this one, I got some problem with my Assembler and UserDetailsServiceImpl bean not being recognized in my spring-security.xml file...
I do not think the problem(s) come from my code, I just can't get to set my config files properly and I am probably missing something here.
Here are the config files:
web.xml:
<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>Spring MVC Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</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/mvc-dispatcher-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>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config/>
<!-- Load everything except #Controllers -->
<context:component-scan base-package="com">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="save*" />
<tx:method name="*" read-only="false" />
</tx:attributes>
</tx:advice>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.dao.HibernateFruitDAO</value>
</list>
</property>
<property name="packagesToScan">
<list>
<value>com.service</value>
<value>com.controller</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</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:3306/basename" />
<property name="username" value="xxx" />
<property name="password" value="yyy" />
</bean>
</beans>
mvc-dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath:hibernate.properties" />
<!-- Load #Controllers only -->
<context:component-scan base-package="com.controller"
use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
</beans>
spring-security.xml
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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<beans:bean id="userDetailsService" class="com.service.UserDetailsServiceImpl">
</beans:bean>
<beans:bean id="assembler" class="com.service.Assembler">
</beans:bean>
<http auto-config='true' use-expressions='true'>
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/secure/**" access="hasRole('ROLE_Admin')" />
<logout logout-success-url="/listing.htm" />
<form-login login-page="/login.htm" login-processing-url="/j_spring_security_check"
authentication-failure-url="/login_error.htm" default-target-url="/listing.htm"
always-use-default-target="true" />
</http>
<beans:bean id="com.daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="com.daoAuthenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
</beans:beans>
FruitController:
package com.controller;
#Controller
public class FruitController{
protected final Log logger = LogFactory.getLog(getClass());
private FruitManager fruitManager;
#Autowired
public void setFruitManager(FruitManager FruitManager) {
this.fruitManager = fruitManager;
}
#RequestMapping(value = "/listing", method = RequestMethod.GET)
public String getFruits(ModelMap model) {
model.addAttribute("fruits", this.fruitManager.getFruits());
return "listing";
}
}
FruitDAO:
public interface FruitDAO {
public List<Fruit> getFruitList();
public List<Fruit> getFruitListByUserId(String userId);
public void saveFruit(Fruitprod);
public void updateFruit(Fruitprod);
public void deleteFruit(int id);
public Fruit getFruitById(int id);
}
HibernateFruitDAO
package com.dao;
#Repository("fruitDao")
public class HibernateFruitDAO implements FruitDAO {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Fruit> getList() {
return (List<Fruit>) getSession().createCriteria ( Fruit.class ).list();
}
public List<Fruit> getFruitListByUserId(String userId) {
return (List<Fruit>)sessionFactory.getCurrentSession().createCriteria("from Fruit where userId =?", userId).list();
}
public void saveFruit(Fruit fruit) {
sessionFactory.getCurrentSession().save(fruit);
}
public void updateFruit(Fruit fruit) {
sessionFactory.getCurrentSession().update(fruit);
}
public void deleteFruit(int id) {
Fruit fruit = (Fruit) sessionFactory.getCurrentSession().load(Fruit.class, id);
if (null != fruit) {
sessionFactory.getCurrentSession().delete(fruit);
}
}
public Fruit getFruitById(int id) {
return (Fruit)sessionFactory.getCurrentSession().load(Fruit.class, id);
}
private Session getSession(){
return sessionFactory.getCurrentSession();
}
}
Interface FruitManager:
package com.service;
import java.io.Serializable;
import java.util.List;
import com.domain.Fruit;
public interface FruitManager extends Serializable{
public List<Fruit> getFruits();
public List<Fruit> getFruitsByUserId(String userId);
public void addFruit(Fruit fruit);
public void removeFruit(int id);
public Fruit getFruitById(int id);
public void updateFruit(Fruit fruit);
}
Implementation of FruitManager:
package com.service;
#Repository("fruitManager")
#Transactional
public class SimpleFruitManager implements FruitManager {
/**
*
*/
private static final long serialVersionUID = ...;
#Autowired
private FruitDAO fruitDao;
public List<Fruit> getFruits() {
return fruitDao.getFruitList();
}
public List<Fruit> getFruitsByUserId(String userId){
return fruitDao.getFruitListByUserId(userId);
}
public void setFruitDao(FruitDAO fruitDao) {
this.fruitDao = fruitDao;
}
public void addFruit(Fruit fruit) {
fruitDao.saveFruit(fruit);
}
public void removeFruit(int id) {
fruitDao.deleteFruit(id);
}
public getFruitById(int id) {
return fruitDao.getFruitById(id);
}
public void updateFruit(Fruit fruit) {
fruitDao.updateFruit(fruit);
}
}
At a glance, it seems you're suffering from a common problem of not understanding how Spring ApplicationContexts fit together to make a web application. See my other answer to exactly the same problem to see if it clears things up:
Declaring Spring Bean in Parent Context vs Child Context
You may also be enlightened by this answer on a similar topic, which links to my previously mentioned answer as well as one other:
Spring XML file configuration hierarchy help/explanation
A couple brief tips to get you headed in the right direction...
By convention, Spring's ContextLoaderListener loads beans from WEB-INF/applicationContext.xml to create the root application context. When you override the default, as you're doing, that file is no longer loaded.
Tip #1: stick with the conventional behavior. It'll make your life simpler.
Also by convention, starting up a Spring DispatcherServlet loads beans from WEB-INF/<servlet name>-context.xml to create the context used to configure the dispatcher servlet. This context becomes a child of the root context.
Tip #2: see tip #1
So you see, you're presently over-configuring things. Read the linked answers and the reference materials linked therein. Learn to work with Spring instead of against it.
In your web.xml file, the applicationContext.xml is never get loaded. You should put it location in context-param. Put the location of mvc-dispatcher-servlet.xml (containing controller related bean) as init-param for DispatcherServlet instead:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
I think you must to use this in the DaoImpl to get the session:
#Autowired
private SessionFactory sessionFactory;