This article contains spring security with hibernate example with detail explanation and source code.

Technology:

  • Spring-MVC
  • Spring Security
  • Hibernate
  • MySQL
  • Maven
  • Intellij

Project Structure

Spring Security With Hibernate Example

Spring Security With Hibernate Example

Dependency:

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springapp</groupId>
    <artifactId>Spring-Security-with-Hibernate-example</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Spring-Security-with-Hibernate-example</name>
    <properties>
        <spring.version>4.3.1.RELEASE</spring.version>
        <hibernate.version>4.2.11.Final</hibernate.version>
        <mysql.connector.version>5.1.31</mysql.connector.version>
        <spring.security.version>4.2.0.RELEASE</spring.security.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Transaction API-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>Spring-Security-with-Hibernate-example</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Configuration Files

WebConfigs.java

package com.javadeveloperzone.configs;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
 * Created by Subhash Lamba on 19-01-2017.
 */
public class WebConfigs extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SpringWebConfig.class };
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { SpringWebConfig.class };
    }
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

SpringWebConfig.java

package com.javadeveloperzone.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
 * Created by Subhash Lamba on 19-01-2017.
 */
@EnableWebMvc
@Configuration
@ComponentScan({"com.javadeveloperzone"})
@Import({ SpringSecurityWebConfig.class })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver  viewResolver () {
        InternalResourceViewResolver  viewResolver=new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

SpringSecurityWebConfig.java

package com.javadeveloperzone.configs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by JavaDeveloperZone on 18-03-2017.
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityWebConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DriverManagerDataSource dataSource;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource).authoritiesByUsernameQuery("select employeeName, employeeRole FROM employee where employeeName=?").usersByUsernameQuery("select employeeName,employeePassword as password,1 FROM employee where employeeName=?");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/login").defaultSuccessUrl("/employee/viewEmployee")
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/logoutSuccess").permitAll();
    }
}

SecurityWebApplicationInitializer.java

package com.javadeveloperzone.configs;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
 * Created by Java Developer Zone on 18-03-2017.
 */
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

Hibernate Configuration

package com.javadeveloperzone.configs;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Properties;
/**
 * Created by Subhash Lamba on 22-01-2017.
 */
@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:application.properties"})
public class HiberanteConfig {
    @Autowired
    private Environment environment;

    @Bean(name = "dataSource")
    public DriverManagerDataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getProperty("jdbc.url"));
        dataSource.setUsername(environment.getProperty("jdbc.username"));
        dataSource.setPassword(environment.getProperty("jdbc.password"));
        return dataSource;
    }
    @Autowired
    @Bean(name = "sessionFactory")
    public LocalSessionFactoryBean getSessionFactory(DriverManagerDataSource dataSource) {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan(new String[]{"com.javadeveloperzone.model"});
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", "update");
        return properties;
    }
    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getTransactionManager(
            SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(
                sessionFactory);
        return transactionManager;
    }
}

application.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/demo_database
jdbc.username = root
jdbc.password =
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false

 

Controller

LoginController.java

package com.javadeveloperzone.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/")
public class LoginController {
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "index";
    }
    @RequestMapping(value = "logoutSuccess", method = RequestMethod.GET)
    public String logout() {
        return "logoutSuccess";
    }

}

EmployeeController.java

package com.javadeveloperzone.controller;
import com.javadeveloperzone.model.Employee;
import com.javadeveloperzone.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        return "createEmployee";
    }
    @RequestMapping(value = "viewEmployee", method = RequestMethod.GET)
    public String viewEmployee(ModelMap model) {
        model.addAttribute("employees", employeeService.list());
        return "viewEmployee";
    }
    @RequestMapping(value = "saveEmployee", method = RequestMethod.POST)
    public String saveEmployee(Employee employee) {
        employeeService.save(employee);
        return "redirect:viewEmployee";
    }
}

DAO layer

EmployeeDAO.java

package com.javadeveloperzone.dao;
import com.javadeveloperzone.model.Employee;
import java.util.List;
/**
 * Created by Subhash Lamba on 22-01-2017.
 */
public interface EmployeeDAO {
     void save(Employee employee);
     List<Employee> list();
}

EmployeeDAOImpl.java

package com.javadeveloperzone.dao;
import com.javadeveloperzone.model.Employee;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by Subhash Lamba on 22-01-2017.
 */
@Repository
@Transactional
public class EmployeeDAOImpl implements EmployeeDAO {
    @Autowired
    SessionFactory sessionFactory;
    @Override
    public void save(Employee employee) {
        sessionFactory.getCurrentSession().save(employee);
    }
    @Override
    public List<Employee> list() {
        return sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
    }
}

Hibernate Model

Employee.java

package com.javadeveloperzone.model;
import javax.persistence.*;
/**
 * Created by Subhash Lamba on 22-01-2017.
 */
@Entity(name = "Employee")
@Table(name = "Employee")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int employeeId;
    @Column
    private String employeeName;
    @Column
    private String employeePassword;
    @Column
    private String employeeRole;
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeePassword() {
        return employeePassword;
    }
    public void setEmployeePassword(String employeePassword) {
        this.employeePassword = employeePassword;
    }
    public String getEmployeeRole() {
        return employeeRole;
    }
    public void setEmployeeRole(String employeeRole) {
        this.employeeRole = employeeRole;
    }
}

Service Layer

EmployeeService.java

package com.javadeveloperzone.service;
import com.javadeveloperzone.model.Employee;
import java.util.List;
/**
 * Created by Subhash Lamba on 22-01-2017.
 */
public interface EmployeeService {
     void save(Employee employee);
     List<Employee> list();
}

EmployeeServiceImpl.java

package com.javadeveloperzone.service;
import com.javadeveloperzone.dao.EmployeeDAO;
import com.javadeveloperzone.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * Created by Subhash Lamba on 22-01-2017.
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDAO employeeDAO;
    @Override
    public void save(Employee employee) {
        employeeDAO.save(employee);
    }
    @Override
    public List<Employee> list() {
        return employeeDAO.list();
    }
}

JSP Pages:

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Java Developer Zone
  Date: 18-03-2017
  Time: 07:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Spring Security With Hibernate Example</title>
</head>
<body>
<form name='f' action='/login' method='POST'>
    User: <input type='text' name='username' value=''>
    Password: <input type='password' name='password'/>
    <%--<input type="hidden"
           name="${_csrf.parameterName}"
           value="${_csrf.token}"/>--%>
    <input name="submit" type="submit" value="Login"/>
</form>
</body>
</html>

 

createEmployee.jsp

<html>
<head>
    <title>Spring Security With Hibernate Example</title>
</head>
<body>
  <form action="saveEmployee" method="post">
        Name: <input type="text" name="employeeName">
        <input type="submit" value="Save">
    </form>
</body>
</html>

viewEmployee.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Spring Security With Hibernate Example</title>
</head>
<body>
    <h1>Employee List</h1>
    <table border="1">
        <tr>
            <th> Id
            <th> Name
        </tr>
  <c:forEach var="employee" items="${employees}">
        <tr>
            <td> <c:out value="${employee.employeeId}" />
            <td> <c:out value="${employee.employeeName}" />
        </tr>
    </c:forEach>
        <a href="/logout">Logout</a>
    </table>
</body>
</html>

logoutSuccess.jsp

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 10-06-2017
  Time: 10:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Spring Security With Hibernate Example</title>
</head>
<body>
</body>
</html>

Output:

Spring Security with hibernate Example Login Page

Spring Security with Hibernate Example Login Page

Spring Security with Hibernate Example Login Page

 

Spring Security with hibernate Example Home Page

Spring Security With Hibernate Example Home

Spring Security With Hibernate Example Home

Spring Security with hibernate Example Logout Success

Spring Security with Hibernate Example Logout Success

Spring Security with Hibernate Example Logout Success

 

Ref:

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *