VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • C#
  • Python
  • PHP
  • Excel
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Eclipse
    • Phần mềm tiện ích
    • Cấu trúc DL&GT
    • Selenium Test

Spring Tuts

Spring là gì? Kiến trúc Spring Spring - Thiết lập môi trường Spring HelloWorld Example Dependency Injection trong Spring IoC Containers trong Spring Định nghĩa Bean trong Spring Phạm vi của Bean trong Spring Vòng đời của Bean trong Spring Spring - Kế thừ Bean Spring - Inner Bean Spring - Injecting Collection Spring - Beans Auto-Wiring Annotation Based Configuration Spring - Java Based Configuration Spring - Event Handling in Spring Spring - Custom Events in Spring Spring - AOP with Spring Framework Spring - JDBC Framework Spring - Transaction Management Spring - Web MVC Framework Spring - Logging with Log4J

Spring Tool

Cài đặt Spring Tool Suite (STS) trong Eclipse Tạo Spring project bằng Spring Tool Suite trong Eclipse Tạo Spring project (annotation) bằng Spring Tool Suite (STS)

Spring 4 Example

Ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping Ví dụ login trong Spring 4 Web MVC – Hibernate 4 Annotation
1 / 3
❮ ❯

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


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

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 Web MVC - Hibernate XML Mapping
  • Create Spring Web MVC - Hibernate Login Example Project
    • 1. Create project "spring-hibernate-annotation-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. Spring annotation configuration class
    • 9. Create file application.properties
    • 10. Crreate Login Controller
    • 11. 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

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

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

Create Spring Web MVC - Hibernate Login Example Project

1. Create project "spring-hibernate-annotation-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-annotation-login-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

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

        <!-- Web -->
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
        <servlet.version>2.5</servlet.version>

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

        <!-- Hibernate / JPA -->
        <hibernate.version>4.3.11.Final</hibernate.version>

        <!-- MySQL JDBC Connector -->
        <mysql.jdbc.version>5.1.32</mysql.jdbc.version>

        <!-- Logging -->
        <log4j.version>1.2.17</log4j.version>

        <!-- Test -->
        <junit.version>4.11</junit.version>
    </properties>

    <dependencies>
        <!-- Spring MVC -->
        <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>

        <!-- Hibernate -->
        <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>

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

        <!-- Other Web dependencies -->
        <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>

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

        <!-- Test Artifacts -->
        <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)
);

INSERT INTO users('username', 'password') VALUES ("admin", "12345678");

3. Create model Users

Create model Users in package com.realtut.model.

File: Users.java

package com.realtut.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users", catalog = "testdb")
public class Users implements java.io.Serializable {

    private Integer id;
    private String username;
    private String password;

    public Users() {
    }

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

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

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

    @Column(name = "username", length = 30)
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "password", length = 32)
    public String getPassword() {
        return this.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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.realtut.model.Users;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service("userService")
public class UserService {
    @Autowired
    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="UTF-8"?>
<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-annotation-login-example</display-name>

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

    <!-- annotated that this application is config by annotation, instead of default 
        by xml -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <!-- indicate spring annotation configuration class -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.realtut.config.ApplicationConfig</param-value>
    </context-param>

    <!-- - Servlet that dispatches request to registered handlers (Controller implementations). -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></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. Spring annotation configuration class

File: ApplicationConfig.java

package com.realtut.config;

import java.io.IOException;
import java.util.Properties;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.realtut.dao.UserDaoImpl;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.realtut" })
@PropertySource("classpath:application.properties")
public class ApplicationConfig {

    @Autowired
    Environment evn;

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean
    public DriverManagerDataSource dataSource() throws IOException {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(evn.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(evn.getProperty("jdbc.url"));
        dataSource.setUsername(evn.getProperty("jdbc.username"));
        dataSource.setPassword(evn.getProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() throws IOException {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.realtut.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);
        return txManager;
    }

    @Bean
    @Autowired
    public UserDaoImpl userDao(SessionFactory sessionFactory) {
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setSessionFactory(sessionFactory);
        return userDao;
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.dialect", evn.getProperty("hibernate.dialect"));
                setProperty("hibernate.format_sql", evn.getProperty("hibernate.format_sql"));
                setProperty("hibernate.show_sql", evn.getProperty("hibernate.show_sql"));
            }
        };
    }
}

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
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.format_sql=true
hibernate.show_sql=true

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

11. 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 Annotation

Login page:

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

Login error:

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

Login success:

Ví dụ login trong Spring 4 Web MVC - Hibernate 4 Annotation
Dowload Source Code

Download Now!


References
Spring Annotation Type Configuration
Spring document @Repository, @Component, @Service, and @Controller
Ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping
IoC Container trong Spring

Recent Updates

SpringLayout trong Java SwingMyBatis Example - MyBatis + SpringSpring là gì?Cài đặt Spring Tool Suite (STS) trong EclipseDependency Injection trong SpringĐịnh nghĩa Bean trong SpringInjecting Collection trong SpringInner Bean trong SpringIoC Container trong SpringKế thừa Bean trong SpringKiến trúc SpringPhạm vi của Bean trong SpringSắp Tết 2026 Rồi! - Còn bao nhiêu ngày nữa là đến tết 2026?

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn
Danh Sách Bài Học

Học Java | Hibernate | Spring
Học Excel | Excel VBA
Học Servlet | JSP | Struts2
Học C | C++ | C#
Học Python
Học SQL

Bài Tập Có Lời Giải

Bài tập Java
Bài tập C
Bài tập C++
Bài tập C#
Bài tập Python
Ví dụ Excel VBA

Câu Hỏi Phỏng Vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml