How to inject spring beans into xhtml page - java

I am working with Spring and I have a problem with a bean, here is my code:
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.grh.bo.ICollaborateurBo;
import com.grh.bo.IUserBo;
import com.grh.entities.Collaborateur;
#Component
#Scope("session")
public class CollaborateurBean implements Serializable {
private static final long serialVersionUID = 1L;
#Autowired
private ICollaborateurBo collaborateurBo;
private String nom;
private String prenom;
private String sflag = "";
private int currentProjectIndex;
private int page = 1;
public List<Collaborateur> listOfCollaborateur = new ArrayList<Collaborateur>();
private Collaborateur Collaborateurr = new Collaborateur();
List<Collaborateur> lis = new ArrayList<Collaborateur>(collaborateurBo.getAllCollaborateur());
#PostConstruct
public void init() {
setListOfCollaborateur(recupererCollaborateur());
Collaborateurr=new Collaborateur();
}
public List<Collaborateur> getLis() {
return collaborateurBo.getAllCollaborateur();
}
public void setLis(List<Collaborateur> lis) {
this.lis = lis;
}
public List<Collaborateur> getCollaborateurList() {
return collaborateurBo.getAllCollaborateur();
}
private List<Collaborateur> recupererCollaborateur() {
List<Collaborateur> ps = collaborateurBo.getAllCollaborateur();
return ps;
}
public CollaborateurBean() {
super();
}
public CollaborateurBean(ICollaborateurBo collaborateurBo, String nom,
String prenom, String sflag, int currentProjectIndex, int page,
List<Collaborateur> listOfCollaborateur,
Collaborateur collaborateurr, List<Collaborateur> lis) {
super();
this.collaborateurBo = collaborateurBo;
this.nom = nom;
this.prenom = prenom;
this.sflag = sflag;
this.currentProjectIndex = currentProjectIndex;
this.page = page;
this.listOfCollaborateur = listOfCollaborateur;
Collaborateurr = collaborateurr;
this.lis = lis;
}
public Collaborateur getCollaborateurr() {
return Collaborateurr;
}
public void setCollaborateurr(Collaborateur collaborateurr) {
Collaborateurr = collaborateurr;
}
public List<Collaborateur> getListOfCollaborateur() {
return listOfCollaborateur;
}
public void setListOfCollaborateur(List<Collaborateur> listOfCollaborateur) {
this.listOfCollaborateur = listOfCollaborateur;
}
public String getSflag() {
return sflag;
}
public void setSflag(String sflag) {
this.sflag = sflag;
}
public void setCollaborateurBo(ICollaborateurBo collaborateurBo) {
this.collaborateurBo = collaborateurBo;
}
public ICollaborateurBo getCollaborateurBo() {
return collaborateurBo;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getCurrentProjectIndex() {
return currentProjectIndex;
}
public void setCurrentProjectIndex(int currentProjectIndex) {
this.currentProjectIndex = currentProjectIndex;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
}
in this page collaborateur.xhtml i Can't display data from my DATABASE collaborateur.xhtml:
<h:dataTable value="#{CollaborateurBean.getLis()}" var="item">
<h:column>
<h:outputText value="#{item.nom}" />
</h:column>
<h:column>
<h:outputText value="#{item.prenom}" />
</h:column>
</h:dataTable>
When I test the collaborateurBo i display data from my DATABASE. This is the code that gives data from database:
<h:dataTable value="#{collaborateurBo.getAllCollaborateur()}" var="item">
<h:column>
<h:outputText value="#{item.nom}" />
</h:column>
<h:column>
<h:outputText value="#{item.prenom}" />
</h:column>
</h:dataTable>
This means that the problem is in the Collaborateur bean not in collaborateurBo or CollaborateurDao.
Here my configurations :
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"
id="WebApp_ID" version="3.0">
<display-name>GRH</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/web-application-config.xml
</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<context-param>
<param-name>facelets.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>1</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/springsecurity.taglib.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>
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/web-application-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>spring/main-flow</welcome-file>
</welcome-file-list>
<error-page>
<error-code>403</error-code>
<location>/spring/acces-interdit-flow</location>
</error-page>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>ruby</param-value>
</context-param>
</web-app>
faces-config:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config 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-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
<resource-bundle>
<base-name>com.grh.prop.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
<managed-bean>
<managed-bean-name>currentDate</managed-bean-name>
<managed-bean-class>java.util.Date</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
web-application-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:jms="http://www.springframework.org/schema/jms" xmlns:jee="http://www.springframework.org/schema/jee"
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/jms http://www.springframework.org/schema/jms/spring-jms.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- Scans for application #Components to deploy -->
<context:component-scan base-package="org.springframework.webflow.samples.booking" />
<context:component-scan base-package="com.grh" />
<!-- Database Configuration -->
<import resource="DataSource.xml" />
<import resource="Hibernate.xml" />
<!-- Spring Configuration -->
<import resource="webmvc-config.xml" />
<import resource="webflow-config.xml" />
<!-- Spring security 3.0.5 -->
<import resource="security-config.xml" />
</beans>
Please help me, thanx in advance,

Related

How to get rid of this exception " No bean named 'userDetailsService' is defined" although it is defined in xml file?

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

My Spring Application could not load the Servlet Context

I am working on the Spring4.1.6 release. I have deployed my Webapplication named SpringMVCTest on Tomcat 7.0. I am getting the below exception on the tomcat startup. Below are the spring configuration file details.
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_3_0.xsd"
version="3.0">
<display-name>SpringMVC Test Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring/webmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have already added the contextConfigLocation parameter inside the web.xml and also below is the contents of the webmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="com.springmvc" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Bean class
/**
*
*/
package com.springmvc.bean.Person;
import java.util.List;
/**
* #author jp48346
*
*/
public class Person {
private String name;
private String email;
private String gender;
private String password;
private String passwordConf;
private List<String> courses;
private String tutor;
private String hiddenMessage;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConf() {
return passwordConf;
}
public void setPasswordConf(String passwordConf) {
this.passwordConf = passwordConf;
}
public List<String> getCourses() {
return courses;
}
public void setCourses(List<String> courses) {
this.courses = courses;
}
public String getTutor() {
return tutor;
}
public void setTutor(String tutor) {
this.tutor = tutor;
}
public String getHiddenMessage() {
return hiddenMessage;
}
public void setHiddenMessage(String hiddenMessage) {
this.hiddenMessage = hiddenMessage;
}
}
PersonRegistration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>test Spring MVC Sample</title>
</head>
<body>
<h2>Fill your form!</h2>
<form:form method="POST" commandName="form">
<table>
<tr>
<td>Enter your name:</td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
But I don't understand one thing why I am still getting the below exception? As per the logs why it is still trying to look for the applicationContext.xml in the WEB-INF directory? Please help me on this issue and do let me know if any other information is required to resolve the issue.
INFO: Loading XML bean definitions from ServletContext resource
[/WEB-INF/applicationContext.xml] May 19, 2015 6:36:01 PM
org.springframework.web.context.ContextLoader
initWebApplicationContext SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from ServletContext resource
[/WEB-INF/applicationContext.xml]; nested exception is
java.io.FileNotFoundException: Could not open ServletContext resource
[/WEB-INF/applicationContext.xml] at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at
org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at
org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at
org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at
org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.io.FileNotFoundException: Could not open ServletContext resource
[/WEB-INF/applicationContext.xml] at
org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 21 more

How to view data in struts2?

I am trying to view data from databases from jsp so now I come up with idea by without any scriplet or Java code in jsp .I have learned a modeldriven and some interceptors to use in struts.xml but I don't know how to implement it ?so could some one guide and help to go further am new to strut2 world
Beantest:
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getBook()
{
return Book;
}
public void setBook(String book)
{
Book = book;
}
public String getAuthor()
{
return Author;
}
public void setAuthor(String author)
{
Author = author;
}
public String getAvailbleqty()
{
return Availbleqty;
}
public void setAvailbleqty(String availbleqty)
{
Availbleqty = availbleqty;
}
public String getCategory()
{
return Category;
}
public void setCategory(String category)
{
Category = category;
}
DataAction.java:
public List<Beantest> viewbook()
{
List<Beantest> al=new ArrayList<Beantest>();
Beantest bt = new Beantest();
try
{
String sql = "select * from Bookavaible";
Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
bt.setId(rs.getString("id"));
bt.setBook(rs.getString("Book"));
bt.setAuthor(rs.getString("Author"));
bt.setAvailbleqty(rs.getString("Availbleqty"));
bt.setCategory(rs.getString("Category"));
al.add(bt);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return al;
}
Actiontest.java
public class ActionTest {
Beantest bt;
private List<Beantest> beans;
public String viewbookaction()
{
DataAction da = new DataAction();
beans = da.viewbook();
return ActionSupport.SUCCESS;
}
public List<Beantest> getBeans()
{
return beans;
}
Bookview.jsp:
<s:action name="VBA">
<td>id:</td>
<td>Book:</td>
<td>Author:</td>
<td>Availbleqty:</td>
<td>Category:</td>
</s:action>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>BookView.jsp</welcome-file>
</welcome-file-list>
</web-app>
strut2.xml
<package name="a" namespace="/">
<action name="VBA" class="Action.ActionTest" method="viewbookaction">
<result name="success">/BookView.jsp</result>
</action>
</package>
Don't use s:action tag in JSP, until you know how and why to do that. To display values in JSP you are not needed it at all. You should use struts tags to access action bean properties. For example you can print values to the JSP out using s:property tag. For example
<s:iterator value="beans">
id: <s:property value="id"/><br>
Book: <s:property value="book"/><br>
Author: <s:property value="author"/><br>
Availbleqty: <s:property value="availbleqty"/><br>
Category: <s:property value="category"/><br>
<s:/iterator>
The FilterDispatcher is deprecated and you should replace it with StrutsPrepareAndExecuteFilter. See web.xml docs. Also see this answer for
Need suggestions regarding project implementation in Struts and Hibernate.
Change your web.xml and stuts.xml as below.
Struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="a" namespace="/" extends="struts-default">
<action name="" class="Action.ActionTest" method="viewbookaction">
<result name="success">/BookView.jsp</result>
</action>
</package>
web.xml
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
That's all. Simply run.

Freemarker servlet error: The requested resource is not available

When trying to reach "hostname:8080/WebTest1/users" I get this error below:
HTTP Status 404 -
type Status report
message
description The requested resource is not available.
Apache Tomcat/7.0.42
My web.xml looks thusly:
<?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" id="WebApp_ID" version="3.0">
<display-name>WebTest1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!-- Added these for the freemarker templates to work with the servlet -->
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<!-- FreemarkerServlet settings: -->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html; charset=UTF-8</param-value>
<!-- Forces UTF-8 output encoding! -->
</init-param>
<!-- FreeMarker settings: -->
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value>
<!-- 0 is for development only! Use higher value otherwise. -->
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<!-- <param-value>ISO-8859-1</param-value> -->
<param-value>UTF-8</param-value>
<!-- The encoding of the template files. -->
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##########</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>hello_servlet</servlet-name>
<servlet-class>com.fivetech.freemarker.examples.HelloServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>user_servlet</servlet-name>
<servlet-class>com.fivetech.webtest1.servlets.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello_servlet</servlet-name>
<url-pattern>/hello-ftl</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>user_servlet</servlet-name>
<url-pattern>/users</url-pattern>
</servlet-mapping>
<!--
Prevent the visiting of MVC Views from outside the servlet container.
RequestDispatcher.forward/include should and will still work. Removing
this may open security holes!
-->
<security-constraint>
<web-resource-collection>
<web-resource-name>FreeMarker MVC Views</web-resource-name>
<url-pattern>*.ftl</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- Nobody is allowed to visit these -->
</auth-constraint>
</security-constraint>
My bean User.java looks like:
package com.fivetech.webtest1.models;
public class User {
public String firstname;
public String lastname;
public String username;
public String password;
public User(String firstname, String lastname, String username, String password) {
this.firstname = firstname;
this.lastname = lastname;
this.username = username;
this.password = password;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return this.firstname;
}
public String getLastname() {
return this.lastname;
}
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
}
The Servlet class (UserServlet.java) looks like:
package com.fivetech.webtest1.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/users.ftl").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//nothing here yet
}
}
I have a 404 from this but I'm sure I am missing something small but I haven't been able to figure it out yet. Any ideas?

Spring MVC 3 Validator not displaying Error Message

I have problem with displaying error message in spring Application.i am using Spring MVC 3 and Apache Tiles. when i am having error in form than it will not displays error message.
please help me hear is the piece of code.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/dispatcher-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.examples.spring" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
tiles.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="create_account_success" template="/WEB-INF/jsp/account/SuccessJSP.jsp">
</definition>
<definition name="account_create" template="/WEB-INF/jsp/account/testForm.jsp">
</definition>
</tiles-definitions>
testForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form id="form" modelAttribute="formCreate" method="post">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name"/>
<form:errors path="name"/>
</td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password"/>
<form:errors path="password"/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
AccountRegistrationController.java
package com.examples.spring.controller;
import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;
import com.examples.spring.dto.AccountDTO;
import com.examples.spring.validator.AccountValidator;
#Controller
public class AccountRegistrationController {
public static final String BASE_URL = "/account";
#RequestMapping(value = BASE_URL + "/create" ,method = RequestMethod.GET)
public ModelAndView accountCreate(){
ModelAndView view = new ModelAndView();
view.addObject("formCreate", new AccountDTO());
view.setViewName("account_create");
return view;
}
#RequestMapping(value = BASE_URL + "/create" ,method = RequestMethod.POST)
public ModelAndView accountRegistration(#ModelAttribute AccountDTO accountDTO,BindingResult result ){
ModelAndView view = new ModelAndView();
AccountValidator validator = new AccountValidator();
validator.validate(accountDTO, result);
if (result.hasErrors()) {
view.setViewName("account_create");
view.addObject("formCreate", accountDTO);
return view;
}
view.setViewName("create_account_success");
return view;
}
#RequestMapping(value = BASE_URL + "/login" ,method = RequestMethod.GET)
public ModelAndView accountLogin(){
ModelAndView view = new ModelAndView();
view.setViewName("account_login");
return view;
}
}
AccountValidator.java
package com.examples.spring.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.examples.spring.dto.AccountDTO;
public class AccountValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return AccountDTO.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object result, Errors error) {
AccountDTO accountDTO = (AccountDTO) result;
ValidationUtils.rejectIfEmpty(error, "name", "require.name", "Name Requires.");
ValidationUtils.rejectIfEmpty(error, "password", "require.password", "Password Requires.");
}
}
AccountDTO.java
package com.examples.spring.dto;
public class AccountDTO {
private String name;
private String password;
public AccountDTO() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My Code is working well but it does not displays error messages in <form:errors />.
please help me.
The third parameter to ValidationUtils.rejectIfEmpty is an error code. It should be a key to the actual message in your resource bundle. I don't know how it behaves if it can't find a value. You should change it to use a key, and optionally set a default message. See the api.
You need to register your validator with the controller in which you want to use it. See: http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html#validation.mvc

Categories