Basic spring issue : using #Autowired - spring

I have the following 2 objects: User and DomainUser
User.java:
package com.domain;
import java.io.Serializable;
#SuppressWarnings("serial")
public class User implements Serializable {
private long id = 0;
private String userName;
private String password;
public User() {
}
public User(long id) {
this.id = id;
}
public String toString() {
StringBuffer sb = new StringBuffer(256);
sb.append("[id : ").append(id).append(", ");
sb.append("userName : ").append(userName).append(", ");
sb.append("password : ").append(password).append("]");
return sb.toString();
}
public long getId() {
return id;
}
public void setId(long 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;
}
}
DomainUser.java
package com.domain;
import org.springframework.beans.factory.annotation.Autowired;
public class DomainUser {
#Autowired
private User user;
private String domainName;
public String toString() {
StringBuffer sb = new StringBuffer(255);
sb.append(user.toString()).append(", domainName : ").append(domainName);
return sb.toString();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}
I am trying to autowire the User object in to DomainUser by using #Autowired annotation. But when i run the test as below, the User object is not populated.
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="user" class="com.domain.User">
<constructor-arg value="#{1234}"/>
<property name="userName" value="somename" />
<property name="password" value="sompassword" />
</bean>
<bean id="domainUser" class="com.domain.DomainUser">
<property name="domainName" value="mysite" />
</bean>
</beans>
DomainUserTest.java
package com.domain.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.DomainUser;
public class DomainUserTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
DomainUser domainUser = (DomainUser) context.getBean("domainUser");
System.out.println(domainUser.toString());
}
}
If I autowire using the 'byType' in the autowiring attribute in the applicationContext.xml it works fine :
<bean id="domainUser" class="com.domain.DomainUser" autowire="byType">
<property name="domainName" value="mysite" />
</bean>
Can some one help me understand why doesnt #Autowired annotation produce the same result?

You need an AutowiredAnnotationBeanPostProcessor to handle the injection of #Autowired properties. You could place <context:annotation-config /> (you need to define the context-namespace in your xml) or just define the post processor as a bean in your xml:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
See for example here for details.

Related

How use java config to create a inner bean?

Spring Boot version:2.1.3.RELEASE,Spring Framework version:5.1.5.RELEASE.
Simple xml config like this:
<beans xmlns="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-2.5.xsd">
<bean id="CustomerBean" class="io.github.ctlove0523.Customer">
<property name="person">
<bean class="io.github.ctlove0523.Person">
<property name="name" value="stackoverflow" />
<property name="address" value="address1" />
<property name="age" value="15" />
</bean>
</property>
</bean>
</beans>
how the java config would like?
Person.java
import org.springframework.beans.factory.annotation.Value;
public class Person {
#Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", age=" + age + "]";
}
private String name;
private String address;
private Integer age;
public String getName() {
return name;
}
#Value("stackoverflow")
public void setName(String name) {
this.name = name;
}
#Value("address1")
public void setAddress(String address) {
this.address = address;
}
#Value("15")
public void setAge(Integer age) {
this.age = age;
}
}
CustomerBean.java
import org.springframework.beans.factory.annotation.Autowired;
public class CustomerBean {
Person person;
public Person getPerson() {
return person;
}
#Autowired
public void setPerson(Person person) {
this.person = person;
}
}
App.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.registerShutdownHook();
CustomerBean customerBean = context.getBean(CustomerBean.class);
System.out.println(customerBean.getPerson());
}
}
AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
#Bean
public CustomerBean customerBean() {
return new CustomerBean();
}
#Bean
public Person person() {
return new Person();
}
}
Output :
Person [name=stackoverflow, address=address1, age=15]
Edit: Is this what you are looking for ??
Create beans from inner class using spring
Check the Spring documentation on Java configuration : https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
Depending on the code of your Person class, it would look something like this :
import io.github.ctlove0523.Customer;
#Configuration
public class AppConfig {
#Bean
public Customer customerBean() {
Customer myBean = new Customer();
// constructor or setter methods for Person
return myBean;
}
}

autowired dao NullPointerException spring mvc + hibernate [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I'm trying to learn Spring MVC and Hibernate. When I try to run tests I have "Exception in thread "main" java.lang.NullPointerException".
public interface VacancyDAO
package pro.asfert.jobparser.dao;
public interface VacancyDAO {
void LoadDataBase(String query);
void FindVacancy(String queries);}
public class VacancyDAOImpl
package pro.asfert.jobparser.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class VacancyDAOImpl implements VacancyDAO {
#Autowired
private SessionFactory sessionFactory;
public void LoadDataBase(String query) {
sessionFactory.getCurrentSession().createQuery(query);
}
public void FindVacancy(String queries) {
if (queries.contains("По вашему запросу: ")) {
System.out.print(queries);
} else {
sessionFactory.getCurrentSession().createQuery(queries);
}
}
}
public interface VacancyService
package pro.asfert.jobparser.service;
public interface VacancyService {
void LoadDataBase();
void FindVacancy(String queries);
}
**public class VacancyServiceImpl**
package pro.asfert.jobparser.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pro.asfert.jobparser.dao.VacancyDAO;
import pro.asfert.jobparser.domain.Parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
#Service
public class VacancyServiceImpl implements VacancyService {
#Autowired
private VacancyDAO VacancyDAO;
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
/* deleted */
#Transactional
public void LoadDataBase() {
VacancyDAO.LoadDataBase(query);
}
#Transactional
public void FindVacancy(String queries) {
VacancyDAO.FindVacancy(sqlQuery);
}
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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
<context:annotation-config />
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="pro.asfert.jobparser.dao"/>
<context:component-scan base-package="pro.asfert.jobparser.service"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value = "${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref = "dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class = "pro.asfert.jobparser.domain.Vacancy"></mapping>
</session-factory>
</hibernate-configuration>
Vacancy
package pro.asfert.jobparser.domain;
import javax.persistence.*;
#Entity
#Table(name = "Vacancies")
public class Vacancy {
public Vacancy() {
}
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column (name = "vacancy")
private String vacancy;
#Column (name = "salary")
private String salary;
#Column (name = "experience")
private String experience;
#Column (name = "education")
private String education;
#Column (name = "employer")
private String employer;
#Column (name = "details")
private String details;
#Column (name = "hr")
private String hr;
#Column (name = "url")
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getVacancy() {
return vacancy;
}
public void setVacancy(String vacancy) {
this.vacancy = vacancy;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getEmployer() {
return employer;
}
public void setEmployer(String employer) {
this.employer = employer;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
You're creating the service with new here:
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
That way Spring is not involved and does not know anything about this object.
How to fix it:
register your dao and service as spring beans.
initialize the context and get the service from the context and call your method.
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
VacancyServiceImpl serv = ctx.getBean(VacancyServiceImpl.class);
serv.FindVacancy("test");

Spring autowired bean is null NULL

Why my beans is null?
[b]servlet-context.xml [/b]
<?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"
>
<!-- <context:annotation-config/>-->
<context:component-scan base-package="by"/>
<context:property-placeholder location="classpath:database.properties"/>
<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/javakava"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
</beans>
[b]controller[/b]
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
#Autowired
private CommandFactory commandFactory;
#Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
performAction(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
performAction(request, response);
}
private void performAction(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String page = null;
String paramPage = request.getParameter(Constants.PARAM_PAGE);
try {
if (paramPage != null && !paramPage.isEmpty()) {
Command command = commandFactory.getCommand(paramPage);
page = command.execute(request);
// Commands c = Commands.valueOf(paramPage);
// Command command = c.getCommandClass().newInstance();
page = command.execute(request);
RequestDispatcher requestDispatcher = request
.getRequestDispatcher(page);
requestDispatcher.forward(request, response);
} else {
throw new IllegalAccessError(
"Error with access to class from Controller.java");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
LoginCommand - Here is autowared TestService bean. In IDEA it's look's good. But in debug mode my testService is null..
#Component
public class LoginCommand implements Command {
#Autowired
TestService testService;
public String execute(HttpServletRequest request) {
DaoCheckUserImpl id = new DaoCheckUserImpl();
String pass = request.getParameter(Constants.PASS);
String login = request.getParameter(Constants.LOGIN);
id.checkUser();
String userN = id.getUserN();
String userP = id.getUserP();
String userRole = id.getUserRole();
int userId = id.getUserId();
if (userN.equals(login) & userP.equals(pass) & userRole.equals("admin")) {
/*
*
* Here testService is null[/b]
*
*/
List<Test> tests = testService.getAllTests();
request.setAttribute(Constants.TESTS, tests);
User user = new User();
user.setLogin(login);
request.getSession().setAttribute(Constants.USER, user);
return Constants.MAIN_ADMIN_PAGE;
} else {
}
return Constants.ERROR_LOGIN_PAGE;
}
}
}
TestService
#Service
public class TestService {
#Autowired
public DaoTestImpl daoTestImpl;
public List<Test> getAllTests() {
return daoTestImpl.getAllTests();
}
public Test selectTest(String idTest) {
return daoTestImpl.selectTest(idTest);
}
public void deleteTest(Test test) {
daoTestImpl.deleteTest(test);
}
[b]DaoTestImpl [/b]
Here I using JdbcDaoSupport , datasource injected with constructor.
#Component
public class DaoTestImpl extends JdbcDaoSupport implements DaoTest {
#Autowired
public DaoTestImpl(DataSource dataSource) {
setDataSource(dataSource);
}
...
public List<Test> getAllTests() throws DAOException {
return getJdbcTemplate().query(("SELECT *FROM tests"), rowMapper);
}
CommandFactory
#Component
public class CommandFactory {
#Autowired
public LoginCommand loginCommand;
public Command getCommand(String paramPage) {
Commands command = Commands.valueOf(paramPage.toUpperCase());
switch (command) {
case LOGIN_COMMAND:
return loginCommand;
commands
public enum Commands { LOGIN_COMMAND
/*login_Command(LoginCommand.class),
How do you create LoginCommand object?
Autowired is used by Spring to inject the correct bean. So it works only if LoginCommand is created by Spring. If you performed a NEW, or if you use another framework without a proper integration with Spring, this can explain your issue (for example Jersey 2 without the proper configuration).
EDIT:
By the way, you can had "#Required" annotation. This will not fix your problem, but the new error message can help you to understqnd what happen (in particular it will help to see if LoginCommand object is really created by Spring and if the autowired failed [as I think] because the instance of TestService was NOT found [package naming issue, classloader issue, etc.])
Did you check if all your components are in the "by" package (that is specified in component-scan)?

Profile with spring-security doesn´t work

I´m using spring-security to validate at users in function its profiles, but my app doesn´t make it well, when I see the file log, it show me this:
DEBUG DaoAuthenticationProvider:308 - User account is locked
In my form login I put the data well, but I never pass to other page, I´m always in the same page (form page), I introduce good or bad data
My code is:
file configuration spring-security.xml
<beans:beans xmlns:security="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.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" access-decision-manager-ref="accessDecisionManager">
<security:intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/init" access="PROFILE_ADMINISTRATOR" />
<security:form-login
login-page="/"
default-target-url="/init"
always-use-default-target='true'
authentication-failure-url="/"/>
<security:http-basic />
</security:http>
<security:authentication-manager alias="autenticationManagerUserService">
<security:authentication-provider user-service-ref="userService">
<security:password-encoder hash="md5"/>
</security:authentication-provider>
</security:authentication-manager>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:property name="decisionVoters">
<beans:list>
<beans:ref bean="decisorDeRoles"/>
<beans:ref bean="decisorDeAutenticacion"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="decisorDeRoles" class="org.springframework.security.access.vote.RoleVoter">
<beans:property name="rolePrefix" value="PROFILE_"/>
</beans:bean>
<beans:bean id="decisorDeAutenticacion" class="org.springframework.security.access.vote.AuthenticatedVoter"/>
<beans:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>
</beans:beans>
class of UserDatailsService
#Service("userService")
public class SecurityAuthenticationProvider implements UserDetailsService
{
UserDao userDao = new UserDao ();
#Override
public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException, DataAccessException
{
User user = null;
List<User> users = userDao.getUser (username);
if (users.size () == 0)
{
throw new UsernameNotFoundException ("");
}
else
{
user = users.get (0);
user.setAuthorities (userDao.getProfileUser (username));
return user;
}
}
}
class UserDatails
public class User implements UserDetails
{
private List<GrantedAuthority> profiles;
private String username;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
#Override
public Collection<? extends GrantedAuthority> getAuthorities ()
{
return profiles;
}
#SuppressWarnings("unchecked")
public void setAuthorities (List<? extends GrantedAuthority> profiles)
{
this.profiles = (List<GrantedAuthority>) profiles;
}
#Override
public String getPassword ()
{
return password;
}
#Override
public String getUsername ()
{
return username;
}
#Override
public boolean isAccountNonExpired ()
{
return accountNonExpired;
}
#Override
public boolean isAccountNonLocked ()
{
return accountNonLocked;
}
#Override
public boolean isCredentialsNonExpired ()
{
return credentialsNonExpired;
}
#Override
public boolean isEnabled ()
{
return enabled;
}
public void setUsername (String username)
{
this.username = username;
}
public void setPassword (String password)
{
this.password = password;
}
public void setAccountNonExpired (boolean accountNonExpired)
{
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked (boolean accountNonLocked)
{
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired (boolean credentialsNonExpired)
{
this.credentialsNonExpired = credentialsNonExpired;
}
public void setEnabled (boolean enabled)
{
this.enabled = enabled;
}
}
class GrantedAuthority
public class Profile implements GrantedAuthority
{
private String profile;
#Override
public String getAuthority ()
{
return profile;
}
public String getProfile ()
{
return profile;
}
public void setProfile (String profile)
{
this.profile = profile;
}
}
Class that I have created to simulate access to database (to obtain data)
public class UserDao
{
public List<? extends GrantedAuthority> getProfileUser (String name)
{
List<GrantedAuthority> listGrantedAuthorities = new ArrayList<GrantedAuthority> ();
Profile profile = new Profile ();
profile.setProfile ("PROFILE_ADMINISTRATOR");
listGrantedAuthorities.add (profile);
return listGrantedAuthorities;
}
public List<User> getUser (String name)
{
List<User> listUser = new ArrayList<User> ();
User user = new User ();
user.setUsername ("Admin");
user.setPassword ("1234");
// user.setAccountNonExpired (true);
// user.setAccountNonLocked (true);
// user.setCredentialsNonExpired (true);
// user.setEnabled (true);
listUser.add (user);
return listUser;
}
}
Thanks.
I faced the same issue while working with rest oauth2 spring security.
SOLUTION
you need to make few changes in your class which implements UserDetails (org.springframework.security.core.userdetails), in your case its the user class.
For the following overriding methods isAccountNonLocked(), isAccountNonExpired(), isEnabled(), isCredentialsNonExpired()
change the retrun type to true (by default its false).
make note that these all methods should have a logic to return true or false depending on your requirement but to make your code work i am suggesting you to return true for all the mentioned methods.

Spring Authentication failure

I would like to ask from some insight as I'm not sure what is wrong here. I need to add authentication via database stored details so I'm trying to do that. The problem being that every userdetails I use to access the main pages returns the login failed page.
The DAO layer
#Transactional
#Repository ("staffDAO")
public class StaffDAO extends AbstractDAO<Staff>{
public StaffDAO() {
super(Staff.class);
}
#Autowired
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
private Transaction transaction;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;}
#SuppressWarnings("unchecked")
public List<Authority> getAuthority() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Authority ");
return query.list();}
public void saveAuthority(Authority authority) {
try {
Session session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
session.save(authority);
transaction.commit();
} catch (Exception e) {
transaction.rollback();}}
#Transactional("hibernatetransactionManager")
public Staff getUserByUserName(String userName){
Query queryResult;
queryResult =getCurrentSession().createQuery("from Staff where username=:userName");
queryResult.setParameter("userName", new String(userName));
return (Staff) queryResult.list().get(0)}}
Service layers
public interface StaffService{
List<Authority> getAuthorities();
public void saveAuthority(Authority authority);
public Staff getUserByUserName(String userName);}
#Service("staffService")
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class StaffServiceImpl implements StaffService {
#Autowired
StaffDAO staffDAO;
private AbstractDAO<Staff> sessionFactory;
public StaffDAO getStaffDAO() {
return staffDAO;}
public void setStaffDAO(StaffDAO staffDAO) {
this.staffDAO = staffDAO;}
#Override
public List<Authority> getAuthorities() {
return staffDAO.getAuthority();}
#Override
public void saveAuthority(Authority authority) {
staffDAO.saveAuthority(authority);}
#Override
public Staff getUserByUserName(String userName) {
return staffDAO.getUserByUserName(userName);}}
CustomUserDetailsService
#Repository("customUserDetailsService")
#Service
#Component
public class CustomUserDetailsService implements UserDetailsService{
#Resource
private StaffService staffService;
public CustomUserDetailsService(){
}
public CustomUserDetailsService(StaffService staffService) {
this.staffService = staffService; }
#Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
Staff staff;
try {
staff = staffService.getUserByUserName(userName);
} catch (Exception e) {
throw new UsernameNotFoundException(
"getUserByUserName returned null.");}
return (UserDetails) staff;}}
Models
#Entity
#Table(name = "staff")
#Component
public class Staff implements Serializable, UserDetails{
private static final long serialVersionUID = 8825646974241476909L;
#Id
#Column(name = "staff_id")
private String staffId;
#Column(name = "name")
private String name;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
***** getters and setters
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
#Override
public Set<Authority> getAuthorities() {
return authorities;
}}
#Entity
#Table(name="authorities")
#Component
public class Authority implements Serializable, GrantedAuthority{
private static final long serialVersionUID = 1L;
public Authority(){
// must have one default constructor
}
#Id
#Column(name = "authority")
private String authority;
#Column(name = "role_name",nullable=false,unique=true)
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#Override
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public Authority(String authority,String roleName){
this.authority=authority;
this.roleName=roleName;
}}
XML config
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
<beans:bean id="customUserDetailsService"
class="com.project.professional.service.CustomUserDetailsService">
</beans:bean>
<http auto-config="true" use-expressions="true" >
<intercept-url pattern="/j_spring_security_check" access="permitAll"/>
<intercept-url pattern='/home' access="hasRole('ROLE_USER')" />
<form-login login-page='/login' always-use-default-target="true" default-target-
url="/home" authentication-failure-url="/auth/loginFailed"/>
<logout invalidate-session="true" logout-success-url='/login' />
</http>
Controller
#RequestMapping(value="/login", method = RequestMethod.GET)
public String getLoginPage(ModelMap model) {
return "login";}
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String getHomePage(Locale locale, Model model) {
return "/home";}
Jsp
<c:url value="/j_spring_security_check" var="loginUrl"/>
<form action="${loginUrl}" method="post" name="loginForm">
<p>
<label for="j_username">Username</label>
<input id="j_username" name="j_username" type="text" />
</p>
<p>
<label for="j_password">Password</label>
<input id="j_password" name="j_password" type="password" />
</p>
<input type="submit"
value="Login"/>
</form>
So what I'm asking is if there is anything that I'm missing, as to why it does not authenticate and return the home page. I would appreciate any insight into this.

Resources