Wednesday, 4 January 2017

SpringSecurity4,Struts2,JPA,Hibernate4 Application Using Netbeans8.02 and MySQL Database Server

Security is of critical importance to all web applications. Vulnerable applications are easy prey for hackers. Spring Security is a Java/Java EE framework that provides authentication, authorization and other security features for java language based enterprise applications. It is operating system independent, so works on various kinds of operating system. On 25th September 2016 the latest stable version of spring -Security is 4.1.3.Spring- Security version 4.1.1 is used in this article.
·        Spring Security Features

1.     Comprehensive and extensible support for both Authentication and Authorization.
2.     Protection against attacks like session fixation, clickjacking, cross site request forgery (CSRF), etc.
3.     Servlet API integration.
4.     Optional integration with Spring MVC and supports more frameworks.
The JPA(Java Persistence API) is a specification for Java Persistence data using the Object-Relational Mapping (ORM - Object Relational Mapping). One of the main JPA implementations is the Hibernate framework. JPA can be used with any database that has a driver for communicating with Java applications, including, PostgreSQL, Oracle, SQL Server and MySQL.
This is a web security (Login Logout and Remember me) application operating on  ‘users’ and ‘user_roles’ tables in ‘springsecurity’ database in MySQL Database Server. It is a Struts2-Xml,JPA,Hibernate4-Annotation and  SpringSecurity4- Xml based application. Different persons with different authorization (e.g. user and admin) displayed different web pages after logging in.

Software Used
2.Netbeans 8.02
3.MySQL 5.* Database Server(or XAMPP-For easy MySQL Management)
4.MySQL Connector 5.*
5.Hibernate 4.3.** (Bundled with Netbeans)
8.Spring Security 4.1.1
1.Install JDK8 or Jdk7 if not installed
2.Install Netbeans and associated ApacheTomcat Server
3.Install  MySQL Database server or XAMPP(For easy management of MySQL ) .
After Installing Netbeans click the services tab on the left. Expand Database node. Expand Drivers node. Right click MySQL(Connector/Jdriver) then connect. Put springsecurity as the database. As shown below. Put password if you have given password at the time of installation of MySQL database server. For XAMPP no password is required. Then test connection. If successful click finish button.

Create user table by running below SQL in ‘springsecurity’ database
  `username` varchar(45) NOT NULL,
  `password` varchar(60) NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '1'

ALTER TABLE `users`   ADD PRIMARY KEY (`username`);
Insert these Records below by executing below insert statement
INSERT INTO `users` (`username`, `password`, `enabled`) VALUES
('alex', 'alex123', 1),
('mkyong', 'mykong123', 1),
('raichand70', 'jaishriram', 1),
('walid', 'walid123', 0);

  `user_role_id` int(11) NOT NULL,
  `username` varchar(45) NOT NULL,
  `role` varchar(45) NOT NULL

ALTER TABLE `user_roles`   ADD PRIMARY KEY (`user_role_id`), ADD UNIQUE KEY `uni_username_role` (`role`,`username`), ADD KEY `fk_username_idx` (`username`);
ALTER TABLE `user_roles`   MODIFY `user_role_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
ALTER TABLE `user_roles` ADD CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `users` (`username`);

Insert these Records below by executing below insert statement

INSERT INTO `user_roles` (`user_role_id`, `username`, `role`) VALUES
(1, 'raichand70', 'ROLE_ADMIN'),
(2, 'alex', 'ROLE_USER'),
(3, 'mkyong', 'ROLE_USER'),
(4, 'walid', 'ROLE_USER');

Creating Project SpringSecurity4Struts2JPAHibernate4RememberMeExample
File-àNew ProjectàCategories-àChoose JavaWeb--àChoose WebApplicationàClick Next-àGive Project Name SpringSecurity4Struts2JPAHibernate4RememberMeApplicationàClick NextàClick NextàChoose Framework  Hibernateà Click Finish




In the above figure Database Connection should be with ‘springsecurity’ database.

Persistence.xml is not required for this project.
 Download mysql- connector-java-bin.jar add to libraries folder by right click addJAR/Folderàadd the mysql-java-bin.jar.
Create a folder named View under Web pages Folder. Create Two Folders named Secured and UnSecured under View Folder. Create two folders named User and Admin under Secured Folder.Admin Folder would contain admin.jsp. User folder would contain userprofile.jsp file. UnSecured Folder would two files login.jsp and redirect.jsp.please verify with project structure.
 Project Structure

JARS required to be added to Libraries Folder
Right click on the Libraries folderà addJAR/Folder then add below mentioned JAR Files . Most of the below JAR files are available for download from the provided downloadable winrar file along with other files of the project.
5. el-impl-2.2
6. spring-aop-4.3.2
7. spring-beans-4.3.2
8. spring-context-4.3.2
9. spring-core-4.3.2
10. spring-tx-4.3.2
11. spring-web-4.3.2
12. spring-expression-4.3.2
13. spring-jdbc-4.3.2
14. spring-orm-4.3.2
15. spring-security-config-4.1.1
16. spring-security-core-4.1.1
17. spring-security-web-4.1.1
18. Struts 2-core-
19. Struts 2-convention-plugin- jar
20. Struts 2-jquery-plugin-2.3.1. jar
21. Struts-taglib-1.3.10.jar
22. commons-fileupload-1.3.1.jar
23. commons-io-2.2.jar
24. commons-lang3-3.4.jar
25. commons-logging-1.1.3.jar
26. freemaker-2.3.22.jar
27. javassist-3.11.0.GA.jar
28. ognl-3.0.6.jar
29. xwork-core-
30. asm-3.3.jar

Creating Packages and Classes
Default Package contains one file struts.xml
Right click Source Package folder and create four packages
1. com.ray.springsecurity.dao-àThis would contain DAO(Data Access Object) class and interface and 
2. com.ray.springsecurity.pojos.modelàThis would contain entity (POJO) class  files and POJO Stands for Plain Old Java Objects
3. com.ray.springsecurity.serviceàThis would contain Spring Service class file
4. com.ray.struts.actionsàThis would contain Strut Actions file
This Class directs the person logging in after authentication with username and password to the authorized web page depending on authority like User or Admin.
Following Files would be created  using Netbeans
1. hibernate.cfg,xml File-àAutomatically generated. (It will be used to create, entity files and then would be deleted.)
2. Reverse Engineering File-àhibernate.reveng.xml. (It will be used to create, entity Files and then would be deleted.)
3.Entity(POJO) File-à and stands for Plain Old Java Objects)
4. DataAccessObject(DAO) File-à
5.DataAccessObject(DAO) File-à
6.SpringService Fileà
7. File àStruts Action file for logging in and directed to authorized page according to authorization.
8.redirect.jsp FileàThis file would redirect to login.jsp page on starting application.
9. login.jspàPerson writes his/her username and password with remember me facility
10. admin.jspàThis is displayed if the person logging in is having admin authorization.
11. userprofile.jspàThis is displayed if the person logging in is having user authorization. This displays the profile of user.
12. web.xml (Automatically generated and modified later)
13. spring-security.xmlàThis contains Security credentials.
14. spring-database.xmlàThis contains database credentials.

Add mysql- connector-java-bin.jar to libraries if not done.

1.Hibernate.cfg.xml  File(It would be deleted after used for creating  and User_Role entity classes)
As XAMPP is used so there is no password in the file only username is given that is root in Hibernate.cfg.xml File.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "">
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springsecurity?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"> </property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="">update</property>
    <mapping class="com.ray.springsecurity.pojos.model.User"/>
     <mapping class="com.ray.pojos.springsecurity.model.UserRole"/>

2. Creating Reverse Engineering File-àhibernate.reveng.xml(It would be deleted after used for creating and  entity class)

Right Click default package in the Source Package-ànewàchoose Hibernate Reverse Engineering Wizardàclick nextàchoose user and user_role tableàAdd àclick finish.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "">
  <schema-selection match-catalog="springsecurity"/>
  <table-filter match-name="user"/>
 <table-filter match-name="user_role"/>
3. Creating Hibernate  Entity (pojo) and
Important:To create this file MySQL database springsecurity most be connected through Netbeans.
Right click com.model package--ànew-àHibernate Mappling Files and pojos from databaseàDonot select mapping file & select EJB3.0 Pattern and Domain Code(java) àClick Finish

Please Modify both entity classes as Given Below. Generated code may differ a little. CODE:
package com.ray.springsecurity.pojos.model;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Table(name = "users", catalog = "springsecurity")
public class User implements Serializable{

            private String username;
            private String password;
            private boolean enabled;
            private Set<UserRole> userRole = new HashSet<UserRole>(0);
            public User() {
            public User(String username, String password, boolean enabled) {
                        this.username = username;
                        this.password = password;
                        this.enabled = enabled;
            public User(String username, String password,
                        boolean enabled, Set<UserRole> userRole) {
                        this.username = username;
                        this.password = password;
                        this.enabled = enabled;
                        this.userRole = userRole;
            @Column(name = "username", unique = true,
                        nullable = false, length = 45)
            public String getUsername() {
                        return this.username;
public void setUsername(String username) {
                        this.username = username;
            @Column(name = "password",
                        nullable = false, length = 60)
            public String getPassword() {
                        return this.password;
            public void setPassword(String password) {
                        this.password = password;
            @Column(name = "enabled", nullable = false)
            public boolean isEnabled() {
                        return this.enabled;
            public void setEnabled(boolean enabled) {
                        this.enabled = enabled;
            @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
            public Set<UserRole> getUserRole() {
                        return this.userRole;
            public void setUserRole(Set<UserRole> userRole) {
                        this.userRole = userRole;

UserRole.Java CODE:-
package com.ray.springsecurity.pojos.model;

import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Table(name = "user_roles", catalog = "springsecurity",
          uniqueConstraints = @UniqueConstraint(
                   columnNames = { "role", "username" }))
public class UserRole implements Serializable{
          private Integer userRoleId;
          private User user;
          private String role;

          public UserRole() {
          public UserRole(User user, String role) {
                   this.user = user;
                   this.role = role;
          @GeneratedValue(strategy = IDENTITY)
          @Column(name = "user_role_id",
                   unique = true, nullable = false)
public Integer getUserRoleId() {
                   return this.userRoleId;
          public void setUserRoleId(Integer userRoleId) {
                   this.userRoleId = userRoleId;
          @ManyToOne(fetch = FetchType.LAZY)
          @JoinColumn(name = "username", nullable = false)
          public User getUser() {
                   return this.user;
          public void setUser(User user) {
                   this.user = user;
          @Column(name = "role", nullable = false, length = 45)
          public String getRole() {
                   return this.role;
          public void setRole(String role) {
                   this.role = role;
4. Creating DataAccessObject (DAO) InterfaceFile class File
Right click com.ray.springsecurity.dao package-ànew-àJavaClassàGive class name UserDao -à click Finish. File CODE:
package com.ray.springsecurity.dao;
import com.ray.springsecurity.pojos.model.User;

public interface UserDao {

            User findByUserName(String username);

5. Creating DataAccessObject (DAO)Class Implementation File File
Right click com.ray.dao package-ànew-àJavaClassàGive class name UserDaoImpl -à click Finish. File CODE:
package com.ray.springsecurity.dao;;

import org.springframework.stereotype.Repository;
import com.ray.springsecurity.pojos.model.User;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class UserDaoImpl implements UserDao {   
 private EntityManager entityManager;
public User findByUserName(String username) {
 System.out.println("Name of the DAO user is:-"+ username);
 return entityManager.createQuery("from User u where u.username = :username", User.class)
                            .setParameter("username", username)
   public EntityManager getEntityManager() {
        return entityManager;
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
6. Service File
Right click com.ray.springsecurity.service package-ànew-àjavaclassàClass name àGive name CustomUserDetailsServiceàClick Finish CODE:
package com.ray.springsecurity.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ray.springsecurity.dao.UserDao;
import com.ray.springsecurity.pojos.model.UserRole;

public class CustomUserDetailsService implements UserDetailsService {
    UserDao userdao;
            public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {           
        System.out.println("username is:-" + username);
                        com.ray.springsecurity.pojos.model.User user = userdao.findByUserName(username);
                if (user==null){throw new UsernameNotFoundException("No such user: " + username);
              }else if(user.getUserRole().isEmpty()){
throw new UsernameNotFoundException("User" + username + "has no authorities");
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
                        return buildUserForAuthentication(user, authorities);                  

            // Converts com.ray.springsecurity.pojos.model.User user to
            private User buildUserForAuthentication(com.ray.springsecurity.pojos.model.User user, List<GrantedAuthority> authorities) {
                        return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
            private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
            Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
                        // Build user's authorities
                        for (UserRole userRole : userRoles) {
                        setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));

                        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
                        return Result;

}  Class File
Right click com.ray.struts.actions package-ànew-àjavaclassàClass name àGive name LoginActionàClick Finish CODE:
package com.ray.struts.actions;

import com.opensymphony.xwork2.ActionSupport;
import java.util.Collection;
import java.util.Iterator;
 * @author Raichand

class MyAction extends ActionSupport{
public static String ADMIN_SUCCESS = "admin_success";
public static String USER_SUCCESS = "user_success";
public class LoginAction extends ActionSupport{

    private String username;
    private String password;
    private String Role;

   public String execute() throws Exception {
       Authentication auth = SecurityContextHolder.getContext().getAuthentication();

if(!(auth instanceof AnonymousAuthenticationToken)){
    System.out.println( SecurityContextHolder.getContext().getAuthentication().getPrincipal());
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("username: " + userDetails.getUsername());
        System.out.println("password: " + userDetails.getPassword());
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) userDetails.getAuthorities();
        for (Iterator it = authorities.iterator(); it.hasNext();) {
            SimpleGrantedAuthority authority = (SimpleGrantedAuthority);
            System.out.println("Role: " + authority.getAuthority());
              Role = authority.getAuthority();

        if (Role.equals("ROLE_ADMIN"))
                  return MyAction.ADMIN_SUCCESS;
        else if(Role.equals("ROLE_USER"))
                  return MyAction.USER_SUCCESS;


                  return ERROR;       
public String getRole() {
return Role;
public void setRole(String Role) {
this.Role = Role;
    public String getUsername() {
        return username;
    public void setUsername(String username) {
        this.username = username;
    public void setPassword(String password) {
        this.password = password;
    public String getPassword() {
        return password;
8. redirect.jsp File
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=login">
9. login.jsp File
    login.jsp code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>
        <h1>Struts2 - Spring Security Demo</h1>
        <s:if test="%{#parameters.error != null}">
            <div style="color: red">Invalid username or password!Please try again.</div>
        <s:if test="%{#parameters.logout != null}">
          <div style="color: green">You have been logged out successfully</div>
        <s:form name="loginForm" action="j_spring_security_check" method="post">
            <s:textfield name="username" label="Username" value="" requiredLabel="UserName Required"/>
            <s:password name="password" label="Password" requiredLabel="Password Required"/>
            <s:checkbox  label="Remember Me" fieldValue="true" id="remember-me" name="remember-me" />          
      <table  >
        <tr >
            <td  colspan="2">
               <s:submit value="Login" align="right" theme="simple" /><s:reset value="Reset" align="right" theme="simple"  />              
            <s:hidden name="_csrf.parameterName" value="_csrf.token"/>            
10. admin.jsp code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page session="true"%>
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Admin Profile Page</title>
        <h1>Hello Admin ${}</h1> 
        <a href="logout">Logout</a>

11.userprofile.jsp Code
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page session="true"%>
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>User Profile Page</title>
        <h1>Hello User ${}</h1> 
        <a href="logout">Logout</a>
12. web.xml (Automatically generated and modified later)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns=""
            <http auto-config="true" use-expressions="true" request-matcher="regex" disable-url-rewriting="false">
                    <!-- Page level Spring Security  -->
            <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
                <intercept-url pattern="/View/UnSecured/*" access="permitAll" />
                <intercept-url pattern="/View/UnSecured/login" access="permitAll"/>
                 <intercept-url pattern="/View/Secured/Admin/*" access="hasRole('ROLE_ADMIN')"/>
                 <intercept-url pattern="/View/Secured/User/*" access="hasRole('ROLE_USER')"/>              
                  login-processing-url ="/j_spring_security_check"
                <csrf disabled="true"/>              
                        <logout invalidate-session="true"
                                    logout-url ="/logout" logout-success-url="/login?logout"
                 <logout logout-url ="/logout"/>
                        <logout logout-success-url="/login?logout" />
                          <!--<remember-me  key="springRocks" services-ref="rememberMeServices" />-->
                <remember-me  key="springRocks" services-ref="rememberMeServices"/>
     <beans:bean id="daoAuthenticationProvider" class="">
        <beans:property name="userDetailsService" ref="customUserDetailsService"/>

    <beans:bean id="authenticationManager" class="">
                                    <beans:ref bean="daoAuthenticationProvider"/>
            <!-- Authentication-manager Bean -->
            <!-- Set customUserDetailsService class as the authentication Manager for Spring Security-->
    <authentication-manager id="authenticationManager" erase-credentials="false">
        <authentication-provider user-service-ref="customUserDetailsService">
              <password-encoder hash="plaintext"></password-encoder>
   <beans:bean id ="authenticationFilter" class="">
     <beans:property name ="authenticationManager" ref="authenticationManager"/>
     <beans:property name="filterProcessesUrl" value="/login"/>
       <beans:property name="usernameParameter" value="username"/>
        <beans:property name="passwordParameter" value="password"/>
     <!-- Bean remember me -->
            <beans:bean id="rememberMeServices"                   class="">
                <beans:constructor-arg value ="springRocks"/>
                <beans:constructor-arg ref ="customUserDetailsService"/>
                        <beans:property name="cookieName" value ="remember-me"/>
                <beans:property name="parameter" value="remember-me-param" />
                <beans:property name="tokenValiditySeconds" value="1209600" />
                <beans:property name="alwaysRemember" value="true" />                            
            <beans:bean id="rememberMeAuthenticationProvider"
                        <beans:constructor-arg value ="springRocks"/>
            <beans:bean id="rememberMeFilter"
                        <beans:constructor-arg ref="rememberMeServices" />
                        <beans:constructor-arg ref="authenticationManager" />

14. spring-database.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi=""       xmlns:aop=""
xmlns:context="" xsi:schemaLocation="">
      <!-- Package needed to be scanned for annotation -->
            <context:component-scan base-package="com.ray" />
            <!-- User DAO Declaration -->
            <bean id="userdao" class="com.ray.springsecurity.dao.UserDaoImpl"></bean>
            <!-- Data Source Declaration -->
            <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/springsecurity" />
                        <property name="username" value="root" />
                        <property name="password" value="" />                
        <bean class="com.ray.springsecurity.service.CustomUserDetailsService" id="customUserDetailsService"></bean>
            <!-- EntityManagerFactory -->
  <!-- This produces a container-managed EntityManagerFactory;
         rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="DataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.ray.springsecurity.pojos.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      <property name="jpaProperties">
            <prop key="">validate</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
        JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="entityManagerFactory" />
   <!-- responsible for registering the necessary Spring components that power annotation-driven transaction management;
        such as when @Transactional methods are invoked -->
   <tx:annotation-driven />
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    <package name="default" extends="struts-default" >        
        <action name="Applogin" class="com.ray.struts.actions.LoginAction" method="execute">
            <result name="admin_success">/View/Secured/Admin/admin.jsp</result>
            <result name="user_success">/View/Secured/User/userprofile.jsp</result>
            <result name="error">/View/UnSecured/403.jsp</result>         
        <action name="login"> 
        <action name="loginfailed">
        <action name="/logout">

Login.jsp page

When logged with wrong username or password below page is displayed.

User alex is logging in

userprofile.jsp is displayed after user alex has logged in

User alex has Logged out

Admin raichand70 is logging in

Admin raichand70 has successfully logged in so admin.jsp is displayed.

Admin raichand70  has successfully logged out.


  1. Hi,
    For Struts,Hibernate CRUD look at blogpost at URL
    Thank you