20/07/2019, 09:59

Ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping

Tạo Spring project (annotation) bằng Spring Tool Suite (STS) Nội dung chính: Các công nghệ sử dụng trong ví dụ này: Cấu trúc project ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping Create Spring Web MVC – Hibernate Login Example Project 1. Create ...

Tạo Spring project (annotation) bằng Spring Tool Suite (STS)

Nội dung chính:

  • Các công nghệ sử dụng trong ví dụ này:
  • Cấu trúc project ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping
  • Create Spring Web MVC – Hibernate Login Example Project
    • 1. Create project “spring-hibernate-login-example”
    • 2. Create table users
    • 3. Create model Users
    • 4. Create UserDao interface
    • 5. Create UserDaoImpl class
    • 6. Create UserService class
    • 7. Update web.xml
    • 8. Update mvc-config.xml
    • 9. Create file application.properties
    • 10. Update application-config.xml
    • 11. Create Hibernate XML mapping
    • 12. Crreate Login Controller
    • 13. Create pages
  • Run Spring – Hibernate login example project

Các công nghệ sử dụng trong ví dụ này:

  • Eclipse Oxygen 4.7
  • MySQL 10.1.29-MariaDB (from xampp-win32-7.2.0-0-VC15-installer)
  • JDK 1.8
  • Spring 4.3.6.RELEASE
  • Hibernate 4.3.11.Final
  • Log4J 1.2.17

Cấu trúc project ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping

Ví dụ login trong Spring 4 Web MVC - Hibernate 4 XML Mapping

Create Spring Web MVC – Hibernate Login Example Project

1. Create project “spring-hibernate-login-example”

You can use STS Spring Tool Suite (STS) eclipse plugin to create spring web mvc project, this tool will create necessary configuration files. Refer to tutorial Install Spring Tool Suite (STS) in Eclipse.

Update pom.xml file:

<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>org.springframework.samples.service.service</groupId>
    <artifactId>spring-hibernate-login-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
         
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

         
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
        <servlet.version>2.5</servlet.version>

         
        <spring-framework.version>4.3.6.RELEASE</spring-framework.version>

         
        <hibernate.version>4.3.11.Final</hibernate.version>
        
         
        <mysql.jdbc.version>5.1.32</mysql.jdbc.version>
        
         
        <log4j.version>1.2.17</log4j.version>

         
        <junit.version>4.11</junit.version>
    </properties>

    <dependencies>
         
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

         
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>

         
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.jdbc.version}</version>
        </dependency>

         
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

         
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

         
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

2. Create table users

create table users (
   id INT NOT NULL auto_increment,
   username VARCHAR(30) default NULL,
   password  VARCHAR(32) default NULL,
   PRIMARY KEY (id)
);

3. Create model Users

Create model Users in package com.realtut.model.

File: Users.java

package com.realtut.model;

public class Users {
    private int id;
    private String username;
    private String password;

    public Users() {
    }

    public Users(int id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }

    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;
    }
}

4. Create UserDao interface

File: UserDao.java

package com.realtut.dao;

import com.realtut.model.Users;

public interface UserDao {
	public Users findByUserName(String username);
}

5. Create UserDaoImpl class

File: UserDaoImpl .java

package com.realtut.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.realtut.model.Users;

public class UserDaoImpl implements UserDao {
    private SessionFactory sessionFactory;

    @Transactional
    public Users findByUserName(String username) {
        Session session = null;

        try {
            session = sessionFactory.openSession();
            List<Users> users = new ArrayList<Users>();
            users = session.createQuery("from Users where username=?")
                    .setParameter(0, username).list();
            if (users.size() > 0) {
                return users.get(0);
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

6. Create UserService class

File: UserService.java

package com.realtut.service;

import com.realtut.dao.UserDao;
import com.realtut.model.Users;

public class UserService {
    private UserDao userDao;

    public boolean isUsers(String username, String password) {
        Users user = userDao.findByUserName(username);
        if (user != null && user.getPassword().equals(password)) {
            return true;
        }
        return false;
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

7. Update web.xml

File: web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee"
    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>spring-hibernate-login-example</display-name>

     
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring/application-config.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

     
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

8. Update mvc-config.xml

File: mvc-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:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">

    <context:component-scan base-package="com.realtut" />

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

9. Create file application.properties

This file defines database information.

File: application.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb
jdbc.username=root
jdbc.password=1234567890

10. Update application-config.xml

This file defines spring beans and integrate spring and hibernate.

File: application-config.xml

<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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:application.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>orm/Users.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="userDao" class="com.realtut.dao.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="userService" class="com.realtut.service.UserService">
        <property name="userDao" ref="userDao" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>

11. Create Hibernate XML mapping

This file is used to map table “users” to model “com.realtut.model.Users”. Location folder “orm” under source “src/main/resources”

File: Users.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.realtut.model.Users" table="users">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="username" type="string">
            <column name="username" length="30" />
        </property>
        <property name="password" type="string">
            <column name="password" length="32" />
        </property>
    </class>
</hibernate-mapping>

12. Crreate Login Controller

File: LoginController.java

package com.realtut.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.realtut.model.Users;
import com.realtut.service.UserService;

@Controller
public class LoginController {
    private static final Logger logger = Logger.getLogger(LoginController.class.getName());

    @Autowired
    UserService userService;

    /**
     * show login
     * 
     * @author realtut
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
        logger.info("Request Login.");
        ModelAndView view = new ModelAndView("login");
        Users loginBean = new Users();
        view.addObject("loginBean", loginBean);
        logger.info("Open login page.");
        return view;
    }

    /**
     * execute login
     * 
     * @author realtut
     * @param request
     * @param response
     * @param loginBean
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView executeLogin(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute("loginBean") Users loginBean) {
        ModelAndView view = null;
        if (userService.isUsers(loginBean.getUsername(), loginBean.getPassword())) {
            request.setAttribute("loggedInUser", loginBean.getUsername());
            view = new ModelAndView("welcome");
        } else {
            request.setAttribute("message", "Invalid ussename or password!");
            view = new ModelAndView("login");
        }
        return view;
    }
}

13. Create pages

File: src/main/webapp/WEB-INF/index.jsp

<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
    <c:url value="/login" var="messageUrl" />
    <a href="${messageUrl}">Login</a>
</body>
</html>

File: src/main/webapp/WEB-INF/view/login.jsp

<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
    <p style="color: red">${message}</p>
    <form:form id="loginForm" action="login" method="POST" modelAttribute="loginBean">
        <form:label path="username">Username</form:label>
        <form:input id="username" name="username" path="username" />
        <br>
        <form:label path="username">Password</form:label>
        <form:password id="password" name="password" path="password" />
        <br>
        <input type="submit" value="Submit" />
    </form:form>
</body>
</html>

File: src/main/webapp/WEB-INF/view/welcome.jsp

<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
    <h2>Hello, ${loggedInUser}</h2>
</body>
</html>

Run Spring – Hibernate login example project

Home page:

Ví dụ login trong Spring 4 Web MVC - Hibernate 4 XML Mapping

Login page:

Ví dụ login trong Spring 4 Web MVC - Hibernate 4 XML Mapping

Login error:

Ví dụ login trong Spring 4 Web MVC - Hibernate 4 XML Mapping

Login success:

Ví dụ login trong Spring 4 Web MVC - Hibernate 4 XML Mapping Dowload Source Code
Tạo Spring project (annotation) bằng Spring Tool Suite (STS)
0