Spring Security Hibernate Annotation Project

spring+security+hibernate+annotation+project

Click here to download eclipse supported ZIP file



This is denied.jsp JSP file and it is used display the output for the application.



<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h1 id="banner">Unauthorized Access !!</h1>
<hr />
<c:if test="${not empty error}">
<div style="color:red">
Your fake login attempt was bursted, dare again !!<br /> 
Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>
<p class="message">Access denied!</p>
<a href="./login">Go back to login page</a> 
</body>
</html>


This is editEmployeeList.jsp JSP file and it is used display the output for the application.



<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 hibernate integration example on www.howtodoinjava.com</title>
</head>
<body>
<h2>Employee Management Screen</h2>
 <h6><a href="<c:url value='j_spring_security_logout'/>">Click here to logout</a></h6>
<form:form method="post" action="add" commandName="EmployeeEntity">
    <table>
  <%--   <tr>
        <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="<spring:message code="label.add"/>"/>
        </td>
    </tr> --%>
    
      <tr>
        <td>firstname</td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td>lastname</td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td>email</td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td>telephone</td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="add"/>
        </td>
    </tr>
</table> 
</form:form>
     
<h3>Employees</h3>
<c:if  test="${!empty employeeList}">
<table class="data">
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Telephone</th>
    <th>&nbsp;</th>
</tr>
<c:forEach items="${employeeList}" var="emp">
    <tr>
        <td>${emp.lastname}, ${emp.firstname} </td>
        <td>${emp.email}</td>
        <td>${emp.telephone}</td>
        <td><a href="delete/${emp.id}">delete</a></td>
    </tr>
</c:forEach>
</table>
</c:if>
</body>
</html>


This is index.jsp JSP file and it is used display the output for the application.



<jsp:forward page="./list"></jsp:forward>


This is login.jsp JSP file and it is used display the output for the application.



<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
<body>
<h1 id="banner">Login to Security Demo</h1>  
<form name="f" action="<c:url value='j_spring_security_check'/>"
method="POST">
<table>
<tr>
<td>Username:</td>
<td><input type='text' name='j_username' /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password'></td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td>
</tr>
</table>
</form>
</body>
</html>


This is logout.jsp JSP file and it is used display the output for the application.



<% session.invalidate(); %>
You are now logged out!!
<a href="${pageContext.request.contextPath}/login">go back</a>



This is EmployeeController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.spring.security.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cv.spring.security.model.EmployeeEntity;
import com.cv.spring.security.service.EmployeeService;


/**
 @author Chandra Vardhan
 */
@Controller
public class EmployeeController {

  @Autowired
  private EmployeeService employeeManager;
  
  public void setEmployeeManager(EmployeeService employeeManager) {
    this.employeeManager = employeeManager;
  }

  @RequestMapping(value = "/", method = RequestMethod.GET)
  public String defaultPage(ModelMap map) {
    return "redirect:/list";
  }
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  public String listEmployees(ModelMap map) {
    
    map.addAttribute("EmployeeEntity"new EmployeeEntity());
    map.addAttribute("employeeList", employeeManager.getAllEmployees());

    return "editEmployeeList";
  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String addEmployee(
      @ModelAttribute(value = "EmployeeEntity"EmployeeEntity employee,
      BindingResult result) {
    employeeManager.addEmployee(employee);
    return "redirect:/list";
  }

  @RequestMapping("/delete/{employeeId}")
  public String deleteEmplyee(@PathVariable("employeeId"Integer employeeId) {
    employeeManager.deleteEmployee(employeeId);
    return "redirect:/list";
  }

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String login(ModelMap model) {
    return "login";
  }

  @RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
  public String loginerror(ModelMap model) {
    model.addAttribute("error""true");
    return "denied";
  }

  @RequestMapping(value = "/logout", method = RequestMethod.GET)
  public String logout(ModelMap model) {
    return "logout";
  }
}


This is EmployeeDao.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.security.dao;

import java.util.List;

import com.cv.spring.security.model.EmployeeEntity;

/**
 @author Chandra Vardhan
 */
public interface EmployeeDao {
  
  public void addEmployee(EmployeeEntity employee);

  public List<EmployeeEntity> getAllEmployees();

  public void deleteEmployee(Integer employeeId);
  
}


This is EmployeeDaoImpl.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.security.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.cv.spring.security.model.EmployeeEntity;

/**
 @author Chandra Vardhan
 */
@Repository
public class EmployeeDaoImpl implements EmployeeDao  {

  @Autowired
    private SessionFactory sessionFactory;
  
  @Override
  public void addEmployee(EmployeeEntity employee) {
    this.sessionFactory.getCurrentSession().save(employee);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<EmployeeEntity> getAllEmployees() {
    return this.sessionFactory.getCurrentSession().createQuery("from EmployeeEntity").list();
  }

  @Override
  public void deleteEmployee(Integer employeeId) {
    EmployeeEntity employee = (EmployeeEntitysessionFactory.getCurrentSession().load(
        EmployeeEntity.class, employeeId);
        if (null != employee) {
          this.sessionFactory.getCurrentSession().delete(employee);
        }
  }  

}


This is EmployeeEntity.java file having the source code to execute business logic.


 

    
package com.cv.spring.security.model;

import java.io.Serializable;


/**
 @author Chandra Vardhan
 */
public class EmployeeEntity  implements Serializable {

  private Integer id;

  private String firstname;
  
  private String lastname;

  private String email;
  
  private String telephone;

  public String getEmail() {
    return email;
  }

  public String getTelephone() {
    return telephone;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public void setTelephone(String telephone) {
    this.telephone = telephone;
  }

  public String getFirstname() {
    return firstname;
  }

  public String getLastname() {
    return lastname;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public void setLastname(String lastname) {
    this.lastname = lastname;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }
}


This is EmployeeService.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.spring.security.service;

import java.util.List;

import com.cv.spring.security.model.EmployeeEntity;

/**
 @author Chandra Vardhan
 */
public interface EmployeeService {
  
  public void addEmployee(EmployeeEntity employeey);

  public List<EmployeeEntity> getAllEmployees();

  public void deleteEmployee(Integer employeeId);
  
}


This is EmployeeServiceImpl.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.spring.security.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cv.spring.security.dao.EmployeeDao;
import com.cv.spring.security.model.EmployeeEntity;

/**
 @author Chandra Vardhan
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
  
  @Autowired
    private EmployeeDao employeeDAO;

  @Override
  @Transactional
  public void addEmployee(EmployeeEntity employee) {
    employeeDAO.addEmployee(employee);
  }

  @Override
  @Transactional
  public List<EmployeeEntity> getAllEmployees() {
    return employeeDAO.getAllEmployees();
  }

  @Override
  @Transactional
  public void deleteEmployee(Integer employeeId) {
    employeeDAO.deleteEmployee(employeeId);
  }

  public void setEmployeeDAO(EmployeeDao employeeDAO) {
    this.employeeDAO = employeeDAO;
  }
}




This is pom.xml file having the entries of dependency jars and information to build the application .


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.spring.security</groupId> <artifactId>SpringSecurityHibernateAnnotation</artifactId> <version>1.0</version> <packaging>war</packaging> <name>SpringSecurityHibernateAnnotation</name> <properties> <springframework.version>4.2.0.RELEASE</springframework.version> <springsecurity.version>4.0.1.RELEASE</springsecurity.version> </properties> <dependencies> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.2-1003-jdbc4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <artifactId>hibernate-core</artifactId> <groupId>org.hibernate</groupId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>SpringSecurityHibernateAnnotation</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>SpringSecurityHibernateAnnotation</finalName> </build> </project>


This is Employee.hbm.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.cv.spring.security.model.EmployeeEntity" table="EmployeeEntity">
<id column="id" name="id" type="java.lang.Integer">
<generator class="native" />
</id>
<property column="firstname" name="firstname" type="java.lang.String" />
<property column="lastname" name="lastname" type="java.lang.String" />
<property column="email" name="email" type="java.lang.String" />
<property column="telephone" name="telephone" type="java.lang.String" />
</class>
</hibernate-mapping>


This is application-security.xml file having the spring configuration properties.


 
<?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-4.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

<!-- <http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/accessdenied" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login" default-target-url="/list"
authentication-failure-url="/accessdenied" />
<logout logout-success-url="/logout" />
</http>
-->
<global-method-security
secured-annotations="enabled" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login"
access="permitAll" />
<intercept-url pattern="/accessdenied" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login"
default-target-url="/list" authentication-failure-url="/accessdenied" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin2"
authorities="ROLE_ADMIN" />
<user name="admin" password="admin"
authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<!-- <authentication-manager alias="authenticationManager"> <authentication-provider>
<user-service> <user name="admin" password="admin" authorities="ROLE_USER"
/> </user-service> </authentication-provider> </authentication-manager> -->
<!-- <user-service id="userService"> <user name="admin" password="admin" authorities="ROLE_USER"
/> </user-service> -->
<!-- <authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="myDataSource" />
<jdbc-user-service id="userService" data-source-ref="myDataSource" users-by-username-query=
"select username,password from users"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="org.postgresql.Driver" />
<beans:property name="url"
value="jdbc:postgresql://localhost:5432/spring" />
<beans:property name="username" value="postgres" />
<beans:property name="password" value="password" />
</beans:bean> -->
<!-- <jdbc-user-service id="userService" data-source-ref="dataSource" users-by-username-query=
"select username,password from users where username=?"/> -->
</beans:beans>


This is employee-servlet.xml file having the spring configuration properties.


 
<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.cv.spring.security.model" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<property name="configLocation">
<value>/WEB-INF/resources/hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
</value>
</property>
</bean>
<bean id="employeeDAO" class="com.cv.spring.security.model.EmployeeDaoImpl"></bean>
<bean id="employeeManager" class="com.cv.spring.security.model.EmployeeManagerImpl"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>


This is hibernate.cfg.xml file having the spring configuration properties.


 
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<mapping class="com.cv.spring.security.model.EmployeeEntity" />
</session-factory>
</hibernate-configuration>



This is web.xml deployment descriptor file and it describes how the web application should be deployed.


	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

<display-name>Archetype Created Web Application</display-name>
<!-- <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>employee</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>employee</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/employee-servlet.xml
/WEB-INF/application-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>



This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment