post-image

[Thực hành] Ứng dụng login

4. Validation, Exception & Cookie

Mục tiêu

Luyện tập sử dụng Controller.

Luyện tập sử dụng cơ chế Data Binding thông qua @ModelAttribute.

Điều kiện

Biết cách sử dụng Controller.

Biết cách sử dụng cơ chế Data Binding thông qua @ModelAttribute.

Mô tả

Trong phần này, chúng ta sẽ tạo một ứng dụng Login đơn giản. Ứng dụng cho phép người dùng nhập vào account và password. Nếu thông tin nhập vào là đúng thì sẽ hiển thị các thông số khác của người dùng, chẳng hạn như tên, email…

Hướng dẫn

Bước 1: Tạo dự án

Đặt tên dự án là spring-user-model.

Bước 2: Cấu hình web.xml

<<?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">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Bước 3: Cấu hình dispatcher-servlet.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/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
       http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.codegym"/>

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

</beans>

Bước 4: Tạo model User

Lớp com.codegym.model.User mô tả các thông tin của người dùng, bao gồm: account, password, name, email, age.

package com.codegym.model;

public class User {
    private String account;
    private String password;
    private String name;
    private String email;
    private int age;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Bước 5: Tạo model Login

Lớp com.codegym.mode.Login mô tả thông tin của một Login, bao gồm: account và password.

package com.codegym.model;

public class Login {
    private String account;
    private String password;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Bước 6: Tạo UserDao

Lớp com.codegym.dao.UserDao là một lớp mô phỏng nguồn dữ liệu. Lớp UserDao chứa một danh sách các user cho trước và phương thức checkLogin() cho phép kiểm tra thông tin login.

package com.codegym.com.codegym.dao;

import com.codegym.model.Login;
import com.codegym.model.User;

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

public class UserDao {
    private static List<User> users;
    static {
        users = new ArrayList<>();
        User u1 = new User();
        u1.setAge(10);
        u1.setName("John");
        u1.setAccount("john");
        u1.setEmail("[email protected]");
        u1.setPassword("123456");
        users.add(u1);

        User u2 = new User();
        u2.setAge(15);
        u2.setName("Bill");
        u2.setAccount("bill");
        u2.setEmail("[email protected]");
        u2.setPassword("123456");
        users.add(u2);

        User u3 = new User();
        u3.setAge(16);
        u3.setName("Mike");
        u3.setAccount("mike");
        u2.setEmail("[email protected]");
        u3.setPassword("123456");
        users.add(u3);
    }

    public static User checkLogin(Login login){
        for (User u: users) {
            if(u.getAccount().equals(login.getAccount())
                    && u.getPassword().equals(login.getPassword())){
                return u;
            }
        }
        return null;
    }
}

Bước 7: Tạo UserController

Lớp com.codegym.controller.UserController có phương thức home() trả về view home kèm theo một người dùng mặc định.

package com.codegym.controller;

import com.codegym.com.codegym.dao.UserDao;
import com.codegym.model.Login;
import com.codegym.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
public class UserController {

    @GetMapping("/home")
    public ModelAndView home(){
        ModelAndView modelAndView = new ModelAndView("home", "login", new Login());
        return modelAndView;
    }
}

Bước 8: Tạo view home.jsp

View home.jsp hiển thị form login.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h3>Home</h3>
    <form:form action="login" method="post" modelAttribute="login">
        <fieldset>
            <legend>Login</legend>
            <table>
                <tr>
                    <td><form:label path="account">Account:</form:label></td>
                    <td><form:input path="account"  /></td>
                </tr>
                <tr>
                    <td><form:label path="password">Password:</form:label></td>
                    <td><form:input path="password"/></td>
                </tr>
                <tr>
                    <td></td>
                    <td><form:button>Login</form:button></td>
                </tr>
            </table>
        </fieldset>
    </form:form>
</body>
</html>

Thuộc tính modelAttribute của thẻ <form:form> được liên kết tới thuộc tính login của ModelAndView trả về từ phương thức home().

Bước 9: Chạy ứng dụng

Đi đến đường dẫn http://localhost:8080/home để quan sát form login.

Bước 10: Bổ sung phương thức login cho UserController

Phương thức login() nhận vào một model Login và thực hiện việc kiểm tra thông qua UserDao.

Nếu đăng nhập thành công thì trả về view user kèm theo đối tượng User.

Nếu đăng nhập thất bại thì trả về view error.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h3>Home</h3>
    <form:form action="login" method="post" modelAttribute="login">
        <fieldset>
            <legend>Login</legend>
            <table>
                <tr>
                    <td><form:label path="account">Account:</form:label></td>
                    <td><form:input path="account"  /></td>
                </tr>
                <tr>
                    <td><form:label path="password">Password:</form:label></td>
                    <td><form:input path="password"/></td>
                </tr>
                <tr>
                    <td></td>
                    <td><form:button>Login</form:button></td>
                </tr>
            </table>
        </fieldset>
    </form:form>
</body>
</html>

Bước 11: Tạo view user.jsp

View user.jsp hiển thị thông tin của người dùng trong trường hợp đăng nhập thành công.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Welcome</h1>
    <h3>Account: ${user.account}</h3>
    <h3>Name: ${user.name}</h3>
    <h3>Email: ${user.email}</h3>
    <h3>Age: ${user.age}</h3>
</body>
</html>

Bước 12: Tạo view error.jsp

View error.jsp hiển thị trang thông báo lỗi trong trường hợp đăng nhập thất bại.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Error</title>
</head>
<body>
    <h1>Login error</h1>
</body>
</html>

Bước 13: Chạy ứng dụng

Đi đến đường dẫn http://localhost:8080/home để quan sát form login.

Nhập vào thông tin đúng account và password, quan sát kết quả.

Nhập và thông tin sai account và password, quan sát kết quả.

Hướng dẫn nộp bài:

Up code lên github.

Paste link github vào phần nộp bài  và nhấn submit.

Leave a Reply

Your email address will not be published.