I am getting the following error when I am trying to publish my dynamic web project from eclipse to apache TomCat:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'roleDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
I searched all over the internet but I couldn't understand the answers provided to similar problem of mine. Hope that someone can help me about this.
my web.xml is as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>MVCTutorial</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Toturial</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Toturial</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my Toturial-servlet.xml is as below:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="toturial.*" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
my spring-security.xml is as below:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true">
<intercept-url pattern="/sec/moderation.html" access="ROLE_MODERATOR" />
<intercept-url pattern="/admin/*" access="ROLE_ADMIN" />
<form-login login-page="/user-login.html"
default-target-url="/success-login.html"
authentication-failure-url="/error-login.html" />
<logout logout-success-url="/index.jsp" />
</http>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
</beans:beans>
my RoleDAO class implementation is as below:
package toturial.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import toturial.model.Role;
#Repository
public class RoleDAOImpl implements RoleDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Role getRole(int id) {
Role role = (Role) getCurrentSession().load(Role.class, id);
return role;
}
}
My TutorialController class implementation is as below:
package toturial.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class ToturialController {
#RequestMapping("/welcome")
public ModelAndView firstMethod() {
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is coming from CrunchifyHelloWorld.java **********</div><br><br>";
return new ModelAndView("welcome", "message", message);
}
#RequestMapping(value="/sec/moderation", method=RequestMethod.GET)
public ModelAndView moderatorPage() {
return new ModelAndView("moderation");
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is protected page - Admin Page!");
model.setViewName("admin");
return model;
}
#RequestMapping(value="/admin/first", method=RequestMethod.GET)
public ModelAndView firstAdminPage() {
return new ModelAndView("admin-first");
}
#RequestMapping(value="/admin/second", method=RequestMethod.GET)
public ModelAndView secondAdminPage() {
return new ModelAndView("admin-second");
}
#RequestMapping(value="/user-login", method=RequestMethod.GET)
public ModelAndView loginForm() {
return new ModelAndView("login-form");
}
#RequestMapping(value="/error-login", method=RequestMethod.GET)
public ModelAndView invalidLogin() {
ModelAndView modelAndView = new ModelAndView("login-form");
modelAndView.addObject("error", true);
return modelAndView;
}
#RequestMapping(value="/success-login", method=RequestMethod.GET)
public ModelAndView successLogin() {
return new ModelAndView("success-login");
}
}
My App.Config class implementation is as below:
package toturial.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
#EnableTransactionManagement
#ComponentScan("tutorial.*")
#PropertySource("classpath:application.properties")
#ImportResource("classpath:spring-security.xml")
#EnableWebMvc
#ComponentScan({ "toturial.*" })
public class AppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
My initializer class is as below:
package toturial.config.core;
import toturial.config.AppConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class Initializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
what do I have done wrong?! can anybody help me about this problem. I really appreciate your time.
Please add this dependency in pom.xml. It will get resolved.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
Related
I am trying spring security authentication using database facing issues
DataController.java
package com.anzy.controller;
import java.util.List;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.anzy.dao.DataDao;
import com.anzy.domain.Employee;
#Controller
public class DataController {
#Autowired
DataDao dataDao;
#RequestMapping("form")
public ModelAndView getForm(#ModelAttribute Employee employee) {
return new ModelAndView("form");
}
#RequestMapping("register")
public ModelAndView registerUser(#ModelAttribute Employee employee) {
dataDao.insertRow(employee);
return new ModelAndView("redirect:list");
}
#RequestMapping("list")
public ModelAndView getList()
{
List employeeList = dataDao.getList();
return new ModelAndView("list", "employeeList", employeeList);
}
#RequestMapping("delete")
public ModelAndView deleteUser(#RequestParam int id) {
dataDao.deleteRow(id);
return new ModelAndView("redirect:list");
}
#RequestMapping("edit")
public ModelAndView editUser(#RequestParam int id,
#ModelAttribute Employee employee) {
Employee employeeObject = dataDao.getRowById(id);
return new ModelAndView("edit", "employeeObject", employeeObject);
}
#RequestMapping("update")
public ModelAndView updateUser(#ModelAttribute Employee employee) {
dataDao.updateRow(employee);
return new ModelAndView("redirect:list");
}
}
User.java
package com.anzy.domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
#Entity
public class User implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#ManyToMany
#JoinTable(name="UserAndRoles",joinColumns=#JoinColumn(name="user_id"),inverseJoinColumns=#JoinColumn(name="role_id"))
private List<Role> roles;
#Enumerated(EnumType.STRING)
private UserStatus status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
Role.java
package com.anzy.domain;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
public class Role
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="roleName")
private String roleName;
#ManyToMany(mappedBy="roles")
private List<User>users;
public Role(int id, String roleName, List<User> users)
{
super();
this.id = id;
this.roleName = roleName;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
UserStatus.java
package com.anzy.domain;
public enum UserStatus
{
ACTIVE,
INACTIVE;
}
Employee.java
package com.anzy.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employetest")
public class Employee {
#Id
#GeneratedValue
private int id;
#Column(name = "firstname")
private String firstName;
#Column(name = "lastname")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "phone")
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
UserDao.java
package com.anzy.dao;
import java.util.List;
import com.anzy.domain.User;
public interface UserDao
{
void addUser(User user);
void editUser(User user);
void deleteUser(int userId);
User findUser(int useId);
User findUserByName(String username);
List<User> getAllUser();
}
UserDaoImpl.java
package com.anzy.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.anzy.domain.User;
#Repository
public class UserDaoImpl implements UserDao
{
#Autowired
private SessionFactory session;
public void addUser(User user)
{
session.getCurrentSession().save(user);
}
public void editUser(User user) {
session.getCurrentSession().update(user);
}
public void deleteUser(int userId) {
session.getCurrentSession().delete(findUser(userId));
}
public User findUser(int userId) {
return (User) session.getCurrentSession().get(User.class,userId);
}
public User findUserByName(String username) {
Criteria criteria=session.getCurrentSession().createCriteria(User.class);
criteria.add(Restrictions.eq("username", username));
return (User)criteria.uniqueResult();
}
public List<User> getAllUser() {
// TODO Auto-generated method stub
return session.getCurrentSession().createQuery("from User").list();
}
}
UserDetailsServiceImpl.java
package com.anzy.services;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.anzy.dao.UserDao;
import com.anzy.domain.Role;
import com.anzy.domain.User;
import com.anzy.domain.UserStatus;
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService
{
#Autowired
private UserDao userDao;
#Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
User user=userDao.findUserByName(username);
if(user!=null)
{
String password=user.getPassword();
boolean enabled=user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonExpired=user.getStatus().equals(UserStatus.ACTIVE);
boolean credentialsNonExpired=user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonLocked=user.getStatus().equals(UserStatus.ACTIVE);
Collection <GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
for(Role role:user.getRoles())
{
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
}
org.springframework.security.core.userdetails.User secureUser=new org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return secureUser;
}
else
{
throw new UsernameNotFoundException("User not found !!!");
}
}
}
DataDao.java
package com.anzy.dao;
import java.util.List;
import com.anzy.domain.Employee;
public interface DataDao
{
public int insertRow(Employee employee);
public List<Employee> getList();
public Employee getRowById(int id);
public int updateRow(Employee employee);
public int deleteRow(int id);
}
DataDaoImpl.java
package com.anzy.dao;
import java.io.Serializable;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.anzy.domain.Employee;
public class DataDaoImpl implements DataDao {
#Autowired
SessionFactory sessionFactory;
#Transactional
public int insertRow(Employee employee) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(employee);
tx.commit();
Serializable id = session.getIdentifier(employee);
session.close();
return (Integer) id;
}
public List getList() {
Session session = sessionFactory.openSession();
#SuppressWarnings("unchecked")
List employeeList = session.createQuery("from Employee")
.list();
session.close();
return employeeList;
}
public Employee getRowById(int id) {
Session session = sessionFactory.openSession();
Employee employee = (Employee) session.load(Employee.class, id);
System.out.println(employee);
return employee;
}
public int updateRow(Employee employee) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(employee);
tx.commit();
Serializable id = session.getIdentifier(employee);
session.close();
return (Integer) id;
}
public int deleteRow(int id) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee employee = (Employee) session.load(Employee.class, id);
session.delete(employee);
tx.commit();
Serializable ids = session.getIdentifier(employee);
session.close();
return (Integer) ids;
}
}
spring-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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/util http://www.springframework.org/schema/util/spring-util-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="com.anzy" />
<context:property-placeholder location="classpath:database.properties" />
<mvc:annotation-driven />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
<property name="initialSize" value="20" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.anzy.domain.Employee</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="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<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="dataDaoImpl" class="com.anzy.dao.DataDaoImpl" />
<!-- <bean id="dataServiceImpl" class="com.beingjavaguys.services.DataServiceImpl" />
-->
</beans>
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<intercept-url pattern="/*" access="isAuthenticated()"/>
<form-login />
<!-- <logout invalidate-session="true" />
--> </http>
<!-- <authentication-manager>
<authentication-provider>
<user-service>
<user name="joseph" password="bagnes" authorities="Admin,User" />
<user name="bernabe" password="jose" authorities="User" />
</user-service>
</authentication-provider>
</authentication-manager> -->
<beans:bean id="daoAuthenticationProvider" class=" org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"></beans:property>
</beans:bean>
<beans:bean id="authenticationManager" class="org.springframework.security.authentication.AuthenticationProvider">
<beans:property name="providers">
<beans:list>
<beans:ref local="daoAuthenticationProvider"/>
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5"></password-encoder>
</authentication-provider>
</authentication-manager>
</beans:beans>
web.xml
<web-app 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"
version="2.5">
<display-name>Sample Spring Maven Project</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
</web-app>
(edited from a previous version)
I created a simplified setting for your problem, and got the code to work.
Here are the two Java classes, first the service (in essense a stub, I did not try to simplify it further, the code has no particular significance):
package com.anzy.services;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService
{
#Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
Collection <GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
org.springframework.security.core.userdetails.User secureUser=new org.springframework.security.core.userdetails.User("user", "user", true, true, true, true, authorities);
return secureUser;
}
}
and here is the controller (again, simplified to have just one method)
package com.anzy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class DataController {
#RequestMapping("form")
public ModelAndView getForm() {
return new ModelAndView("form");
}
}
the four files under WEB-INF are:
spring-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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/util http://www.springframework.org/schema/util/spring-util-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="com.anzy">
<context:exclude-filter type="regex" expression="com.anzy.controller.*"/>
</context:component-scan>
<mvc:annotation-driven />
<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>
</beans>
spring-mvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.anzy.controller"/>
</beans>
spring-security.xml (note that I added use-expressions="true" to the element <http..)
<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns:bean="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="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/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/*" access="isAuthenticated()"/>
<form-login />
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService"/>
</authentication-manager>
</bean:beans>
web.xml
<web-app 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"
version="2.5">
<display-name>Sample Spring Maven Project</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
/WEB-INF/spring-config.xml
</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
</web-app>
The resulting web application starts with no exceptions.
If, however, I change in web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
/WEB-INF/spring-config.xml
</param-value>
</context-param>
to
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
and
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
to
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
then I get precisely the exception which was the subject of your question
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userDetailsService' is defined
I want to check size validation for studentHobby object and i am using #Size annotation and Using #valid annotation.
I am providing less than the value defined in #Size annotation but still I am getting the result instead of error.
I tried things but didn't come with solutions.
StudentAdmissionController.java
package com.diwakar;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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;
#Controller
public class StudentAdmissionController {
#InitBinder
public void initBinder(WebDataBinder binder) {
//binder.setDisallowedFields(new String[] {"studentMobile"});
//SimpleDateFormat date = new SimpleDateFormat("dd**MM**yyyy");
//binder.registerCustomEditor(Date.class, "studentDOB", new CustomDateEditor(date, false));
binder.registerCustomEditor(String.class, "studentName", new StudentNameEditor());
}
#RequestMapping(value="/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#RequestMapping(value="/submitForm", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#Valid #ModelAttribute("st1") Student st1, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#ModelAttribute
public void addCommonMessage(Model model) {
model.addAttribute("headerMessage", "Diwakar College of Engineering.!!");
}
Student.java
package com.diwakar;
import java.util.ArrayList;
import java.util.Date;
import javax.validation.constraints.Size;
public class Student {
private String studentName;
#Size(min=3, max=10)
private String studentHobby;
private Long studentMobile;
private Date studentDOB;
private ArrayList<String> studentSkills;
private Address studentAddress;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
public Long getStudentMobile() {
return studentMobile;
}
public void setStudentMobile(Long studentMobile) {
this.studentMobile = studentMobile;
}
public Date getStudentDOB() {
return studentDOB;
}
public void setStudentDOB(Date studentDOB) {
this.studentDOB = studentDOB;
}
public ArrayList<String> getStudentSkills() {
return studentSkills;
}
public void setStudentSkills(ArrayList<String> studentSkills) {
this.studentSkills = studentSkills;
}
public Address getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(Address studentAddress) {
this.studentAddress = studentAddress;
}
}
spring-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/welcome.html" class="com.diwakar.HelloController" /> -->
<context:component-scan base-package="com.diwakar" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Here is my admission page even though i am providing one one character it is giving me submit form instead of error.
admission.html Page
This submit form i am getting after submitting value with 1 character.
submitForm
Hi,
I got this error and i can`t figure why? all of the defintions in there place and still i have this error while i trying to insert data to my DB.
the "tx:annotation-driven" is in the appconfig-data.xml
I call the add function from "UserController"
What could be the reason it does not work?
Error log:
יול 08, 2016 1:06:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [searcher] in context with path [/Searcher] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
at com.searcher.dao.EcommerceImp.add(EcommerceImp.java:28)
at com.searcher.controller.UserController.registration(UserController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at
Classes
** UserController.java"
package com.searcher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
import com.searcher.entity.UserEntity;
import com.searcher.service.SecurityService;
import com.searcher.service.UserService;
import com.searcher.validator.UserValidator;
#Controller
public class UserController {
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#Autowired
RoleDAO roleDAO;
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new UserEntity());
try {
// Creatinw Role Entity
RoleEntity roleUser = new RoleEntity();
RoleEntity roleAdmin = new RoleEntity();
roleUser.setName("ROLE_USER");
roleAdmin.setName("ROLE_ADMIN");
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.add(userForm);
securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
UserEntity.java
package com.searcher.entity;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="User_Id")
#GeneratedValue
private long Id;
#Column(name="Name")
private String Name;
#Column(name="Password")
private String Password;
#Column(name="Password_Confirm")
private String passwordConfirm;
#Column(name="Phone")
private String Phone;
#Column(name="Email")
private String Email;
#ElementCollection(targetClass=RoleEntity.class)
private Set<RoleEntity> roles;
#ManyToMany
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
public Set<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public long getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public String toString(){
return "Id = " + Id + ", Name = " + Name + ", Password = " + Password + ", Phone = " + Phone + ", Email = " + Email;
}
}
RoleEntity
package com.searcher.entity;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "role")
public class RoleEntity {
#Id
#GeneratedValue
#Column(name="Id")
private Long Id;
#Column(name="Name")
private String Name;
#ElementCollection(targetClass=UserEntity.class)
private Set<UserEntity> users;
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
#ManyToMany(mappedBy = "roles")
public Set<UserEntity> getUsers() {
return users;
}
public void setUsers(Set<UserEntity> users) {
this.users = users;
}
}
DAO
UserDAOImp
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.UserEntity;
#Repository
public class UserImp implements UserDAO{
private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(UserEntity user) {
this.sessionFactory.getCurrentSession().persist(user);
logger.info("UserEntity saved successfully, UserEntity Details="+user);
}
#Override
public void edit(UserEntity user) {
this.sessionFactory.getCurrentSession().update(user);
logger.info("UserEntity updated successfully, UserEntity Details="+user);
}
#Override
public void deleteById(int id) {
UserEntity userToDelete = getUserById(id);
this.sessionFactory.getCurrentSession().delete(userToDelete);
logger.info("UserEntity deleted successfully, UserEntity Details="+userToDelete);
}
#Override
public UserEntity getUserById(int id) {
UserEntity userReturn = (UserEntity)this.sessionFactory.getCurrentSession().get(UserEntity.class, id);
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
return userReturn;
}
#Override
public UserEntity getUserByName(String name) {
try{
UserEntity userReturn =
(UserEntity)this.sessionFactory.getCurrentSession().createQuery("from user where Name ='" + name + "'");
if (userReturn != null){
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
}
else{
logger.info("UserEntity Not found with Name= "+userReturn);
}
return userReturn;
}catch (Exception ex){
}
return null;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<UserEntity> getAllUser() {
List<UserEntity> userList = this.sessionFactory.getCurrentSession().createQuery("from user").list();
logger.info("List<UserEntity> upload successfully, List<UserEntity> Details="+userList.toString());
return userList;
}
}
RoleDAOIMP
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.RoleEntity;
#Repository
public class RoleImp implements RoleDAO {
private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(RoleEntity role) {
this.sessionFactory.getCurrentSession().persist(role);
logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
}
#Override
public void edit(RoleEntity role) {
this.sessionFactory.getCurrentSession().update(role);
logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
}
#Override
public void deleteById(int id) {
RoleEntity roleToDelete = getRoleById(id);
this.sessionFactory.getCurrentSession().delete(roleToDelete);
logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
}
#Override
public RoleEntity getRoleById(int id) {
RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#Override
public RoleEntity getRoleByName(String name) {
RoleEntity roleReturn =
(RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<RoleEntity> getAllRole() {
List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
return roleList;
}
}
UserServiceImp
package com.searcher.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.UserEntity;
#Service("userService")
public class UserServiceImp implements UserService{
#Autowired
private UserDAO userDAO;
#Autowired
private RoleDAO roleDAO;
//#Autowired(required=true)
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
public BCryptPasswordEncoder getbCryptPasswordEncoder() {
return bCryptPasswordEncoder;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Override
#Transactional
public void add(UserEntity user) {
try {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleDAO.getAllRole()));
this.userDAO.add(user);
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
#Transactional
public void edit(UserEntity user) {
this.userDAO.edit(user);
}
#Override
#Transactional
public void deleteById(int id) {
this.userDAO.deleteById(id);
}
#Override
#Transactional
public UserEntity getUserById(int id) {
return this.userDAO.getUserById(id);
}
#Override
#Transactional
public UserEntity getUserByName(String name) {
return this.userDAO.getUserByName(name);
}
#Override
#Transactional
public List<UserEntity> getAllUser() {
return this.userDAO.getAllUser();
}
}
RoleServiceImpl
package com.searcher.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
public class RoleServiceImp implements RoleService {
#Autowired
private RoleDAO roleDAO;
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
#Override
#Transactional
public void add(RoleEntity role) {
this.roleDAO.add(role);
}
#Override
#Transactional
public void edit(RoleEntity role) {
this.roleDAO.edit(role);
}
#Override
#Transactional
public void deleteById(int id) {
this.roleDAO.deleteById(id);
}
#Override
#Transactional
public RoleEntity getRoleById(int id) {
return this.roleDAO.getRoleById(id);
}
#Override
#Transactional
public RoleEntity getRoleByName(String name) {
return this.roleDAO.getRoleByName(name);
}
#Override
#Transactional
public List<RoleEntity> getAllRole() {
return (List<RoleEntity>)this.roleDAO.getAllRole();
}
}
This is the folowing configuration files:
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" version="3.1">
<display-name>Searcher</display-name>
<!-- Location of Java #Configuration classes that configure the components that makeup this application -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<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>
<servlet>
<servlet-name>searcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<!--
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>-->
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<import resource="appconfig-mvc.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="appconfig-security.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.searcher.*"/>
<!--<context:property-placeholder location="classpath:application.properties"/>-->
</beans>
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
appconfig-data.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Configure the data source bean -->
<!-- DataSource -->
<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/SearcherDB" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.searcher.entity.RoleEntity</beans:value>
<beans:value>com.searcher.entity.UserEntity</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:prop key="hibernate.format_sql">true</beans:prop>
<!-- <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop> -->
</beans:props>
</beans:property>
</beans:bean>
<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<!-- Role -->
<beans:bean id="roleDAO" class="com.searcher.dao.RoleImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure the transaction manager bean -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
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">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:validation</value>
</list>
</property>
</bean>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
You are using non transactional daos in your UserController.registration method:
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
Use RoleServiceImpl instead.
I am new in spring and hibernate, all thing is working fine but only Component annotation is not working. Each time this error is coming -
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vc.teacher.db.dao.UserDao] 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)}
My Code is -
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>teacher</display-name>
<welcome-file-list>
<welcome-file>jsp/signin.jsp</welcome-file>
</welcome-file-list>
<!-- Spring Configuration -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.woff</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ttf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>log4jXMLpath</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
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:aop="http://www.springframework.org/schema/aop"
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-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.vc.teacher" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
lazy-init="false">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.vc.teacher.entities.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/teacher"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
**spring
-servlet.xml**
<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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<context:component-scan base-package="com.vc.teacher.controller" />
<!-- Configuration defining views files -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
UserDao class
package com.vc.teacher.db.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.vc.teacher.entities.User;
#Component
public class UserDao {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional
public User checkCreditionals(String email, String password){
User user = null;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where email = '"+email+"' and password = '"+password+"'");
List list = query.list();
if(list.size()>0)
user = (User)list.get(0);
return user;
}
#Transactional
public boolean registerUser(User user){
boolean result = false;
Session session = sessionFactory.getCurrentSession();
try{
user.setUserTypeId(2);
session.save(user);
result = true;
} catch (Exception e){
result = false;
e.printStackTrace();
}
return result;
}
}
Entity Class - User
package com.vc.teacher.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue
#Column(name="user_id")
private int id;
#Column(name="age")
private int age;
#Column(name="user_type_id")
private int userTypeId;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="profession")
private String profession;
#Column(name="phone")
private String phone;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Column(name="address")
private String address;
#Column(name="status")
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getUserTypeId() {
return userTypeId;
}
public void setUserTypeId(int userTypeId) {
this.userTypeId = userTypeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Controller class - AccountController
package com.vc.teacher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.vc.teacher.db.dao.UserDao;
import com.vc.teacher.entities.User;
#Controller
public class AccountController {
#Autowired
UserDao userDao;
#RequestMapping("/login")
public String loginUser(#RequestParam("email") String email,
#RequestParam("password") String password, Model model) {
User user = userDao.checkCreditionals(
email, password);
if (user != null) {
model.addAttribute("user", user);
return "jsp/profile";
} else {
model.addAttribute("error", "Wrong creditionals");
return "jsp/signin";
}
}
#RequestMapping("/signUp")
public String initilize(Model model) {
model.addAttribute(new User());
return "jsp/signup";
}
#RequestMapping(method = RequestMethod.POST, value = "/register")
public String signUpUser(User user, RedirectAttributes attributes) {
boolean result = false;
user.setStatus("Deactive");
result = userDao.registerUser(user);
if (result == true) {
attributes.addFlashAttribute("message", "You are ready to go now !");
return "redirect:/signUp";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "redirect:/signUp";
}
}
}
Your spring-servlet.xml says
<context:component-scan base-package="com.vc.teacher.controller" />
while the UserDao component is not in the controller package.
I am a Spring newbie and facing issues with Spring Security.
I am trying to implement a custom UserDetailsService for user retrieval and getting a null pointer exception when I access the UserService object. I am autowiring this object. The autowirng is working fine when done on other Controller and Service methods but for some reason, its not working here and hence I am getting the null pointer exception when the autowired object(UserService) is accessed.
I would really appreciate help on this.
Exception Stack trace:
java.lang.NullPointerException
java.lang.NullPointerException
at com.contact.list.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:37)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:81)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:194)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
CustomUserDetailsService Class:
package com.contact.list.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.contact.list.form.Role;
import com.contact.list.repository.UserRepository;
#Service
#Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserService userService;
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
try{
com.contact.list.form.User domainuser = userService.findByUsername(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(domainuser.getUsername(),
domainuser.getPassword().toLowerCase(),
enabled,accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(domainuser.getRoles())
);
}catch (Exception e){
System.out.println(e);
e.printStackTrace();
throw new RuntimeException(e);
}
}
public Collection<? extends GrantedAuthority> getAuthorities(List<Role> roles){
List<GrantedAuthority> authList = getGrantedAuthorities(getroles(roles));
return authList;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> userroles){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(String userrole:userroles){
authorities.add(new SimpleGrantedAuthority(userrole));
}
return authorities;
}
public List<String> getroles(List<Role> roles){
List<String> userroles = new ArrayList<String>();
for (Role role : roles){
if(role.getRole() == 1){
userroles.add("ROLE_USER");
}
if(role.getRole() == 2){
userroles.add("ROLE_ADMIN");
}
}
return userroles;
}
}
UserService Interface:
package com.contact.list.service;
import java.util.List;
import com.contact.list.form.Contact;
import com.contact.list.form.User;
public interface UserService {
public List<User> findAll();
public void save(User user);
public User findByUsername(String username);
}
UserService Implementation class:
package com.contact.list.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.contact.list.form.Contact;
import com.contact.list.form.User;
import com.contact.list.repository.UserRepository;
import com.google.common.collect.Lists;
#Service
#Repository
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userrepository;
public void save(User user) {
userrepository.save(user);
}
#Transactional(readOnly=true)
public List<User> findAll() {
return Lists.newArrayList(userrepository.findAll());
}
public User findByUsername(String username){
return userrepository.findByUsername(username);
}
}
Userrepository:
package com.contact.list.repository;
import org.springframework.data.repository.CrudRepository;
import com.contact.list.form.User;
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
}
User Class:
package com.contact.list.form;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "USER_TBL")
public class User {
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "EMAIL")
private String email;
#Id
#Column(name = "USERID")
private String username;
#Column(name = "PASSWORD")
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Role> roles = new ArrayList<Role>();
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
web.xml:
<!-- Spring Security Configuration -->
<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>
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
servlet-context.xml:
<!-- 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/" />
<interceptors>
<beans:bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
</interceptors>
<beans:bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource"/>
<beans:bean id="themeResolver" class="org.springframework.web.servlet.theme.CookieThemeResolver"/>
<!-- 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:property name="requestContextAttribute" value="requestContext"/>
</beans:bean>
<context:component-scan base-package="com.contact.list" />
<beans:bean id = "myDataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value = "org.postgresql.Driver"/>
<beans:property name="url" value = "jdbc:postgresql://localhost:5432/hibernatedb"/>
<beans:property name="username" value = "postgres"/>
<beans:property name="password" value = "password"/>
</beans:bean>
<!-- JPA Config -->
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf"/>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id = "emf" class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name = "dataSource" ref = "myDataSource"/>
<beans:property name = "jpaVendorAdapter">
<beans:bean class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</beans:property>
<beans:property name = "packagesToScan" value = "com.contact.list.form" />
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</beans:prop>
<beans:prop key = "hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id = "passwordEncoder" class = "org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
<context:annotation-config/>
<!-- JPA Config -->
<!-- JPA Repository Abstraction Config -->
<jpa:repositories base-package="com.contact.list.repository" entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager"/>
spring-security.xml
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/home*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/home" authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider user-service-ref = "customUserDetailsService">
<password-encoder ref = "passwordEncoder"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.contact.list.service.CustomUserDetailsService"/>
<beans:bean id = "passwordEncoder" class = "org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
</beans:beans>
So, to write it as an answer, what happened here is that in a typical Spring web application, you have the application context (Spring terminology, here is where beans live) that belongs to the Spring MVC Servlet.
This one is defined in the web.xml as /WEB-INF/spring/appServlet/servlet-context.xml.
On the other hand, the Spring Security Filter cannot access such context, it can only access the Root Context.
The Root Context is loaded with the ContextLoaderListener and the beans defined in:
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring-security.xml
</param-value>
As a Root Context was defined, the Servlet Context is built as a child of the Root Context. This enables the Servlet Context to access the beans that live in its parent, but the other way is not possible.
Then, basic beans as the DataSource, the Persistence system (JPA) and Services were defined in the Servlet Context. The security system was trying to access a service bean (the User Service) without success as this service was located in the Servlet Context instead of the Root Context (where Spring Security lives), hence the Null Pointer Exception.
Solution: Move the Datasource, JPA and Services beans to the Root Context, and leave the Servlet Context for Spring MVC Controllers and Views.
You should remove the #Repository annotation from the UserServiceImpl class. Otherwise Spring tries to instantiates the bean twice (because of the #Service and the #Repository annotation) ...
#Service
#Repository
#Transactional
public class UserServiceImpl implements UserService {