By GokiSoft.com| 10:19 28/11/2020|
Web Component Development (SERVJSP)

[Share Code] Tìm hiểu JSTL + Cookie + Session - Lập trình JSP/Servlet



Nội dung học:
	- Session
	- Cookie
	- JSP
		- Biến môi trường
		- JSTL
		- ...

Web:
	- Database: Server => lữu trữ dữ liệu
	- Frontend:
		- LocalStorage: => JS thao tác dữ liệu => cart
		- Cookie: JS, Ngôn ngữ backend (PHP, Java, ASP, NodeJS, ...)
	- Backend:
		- Session: => Lưu trữ trên server.
====================================================================
- Thiết kế trang login
	=> email: admin@aptechlearning.edu.vn & pass: 123
	=> welcome
- Nếu login thành công => join login => tự động chuyển sang trang welcome
- Nếu chưa login => join welcome => tự động chuyển sang trang login.

Phân tích dự án:
- login page
	- Route: /login
	- JSP: login.jsp
	- Servlet: LoginServlet
- welcome page
	- Route: /welcome
	- JSP: welcome.jsp
	- Servlet: WelcomeServlet
	- Hiển thị danh sách học viên
		- ten, email, address




#login.jsp


<%-- 
    Document   : login
    Created on : Nov 28, 2020, 8:31:08 AM
    Author     : teacher
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/>

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Login Page</h2>
			</div>
			<div class="panel-body">
                            <form method="post">
				<div class="form-group">
				  <label for="email">Email:</label>
                                  <input required="true" type="email" name="email" class="form-control" id="email">
				</div>
				<div class="form-group">
				  <label for="pwd">Password:</label>
                                  <input required="true" type="password" name="password" class="form-control" id="pwd">
				</div>
				<button class="btn btn-success">Register</button>
                            </form>
			</div>
		</div>
	</div>
</body>
</html>


#welcome.jsp


<%-- 
    Document   : welcome
    Created on : Nov 28, 2020, 8:31:23 AM
    Author     : teacher
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="lesson2.Student"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/>

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
                            <h2 class="text-center">Welcome Page
                                <form method="post">
                                    <button type="submit" class="btn btn-deault">Logout</button>
                                </form>
                            </h2>
			</div>
			<div class="panel-body">
                            <table class="table table-bordered  table-hover">
                                <thead>
                                    <tr>
                                        <th>STT</th>
                                        <th>Ho & Ten</th>
                                        <th>Email</th>
                                        <th>Dia Chi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Su dung code thuan JSP/Servlet -->
                                    <%
                                        List<Student> studentList = (List<Student>) request.getAttribute("studentList");
                                        int index = 1;
                                        for (Student student : studentList) {
                                    %>
                                        <tr>
                                            <td><%=index++%></td>
                                            <td><%=student.getFullname()%></td>
                                            <td><%=student.getEmail()%></td>
                                            <td><%=student.getAddress()%></td>
                                        </tr>
                                    <%
                                        }
                                    %>
                                    
                                    <!-- Su dung JSTL -->
                                    <c:forEach items="${studentList}" var="item" varStatus="loop">
                                        <tr>
                                            <td>${loop.index + 1}</td>
                                            <td>${item.fullname}</td>
                                            <td>${item.email}</td>
                                            <td>${item.address}</td>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>
			</div>
		</div>
	</div>
</body>
</html>


#LoginServlet.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson2;

import java.io.IOException;
import javax.jms.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author teacher
 */
public class LoginServlet extends HttpServlet {
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Check login su dung cookie
//        Cookie[] cookieList = request.getCookies();
//        String status = "";
//        
//        for (Cookie cookie : cookieList) {
//            if(cookie.getName().equals("status")) {
//                status = cookie.getValue();
//                break;
//            }
//        }
//        
//        if(status.equals("login")) {
//            response.sendRedirect("welcome");
//            return;
//        }
        //CHeck login su dung session
        HttpSession session = request.getSession();
        if(session.getAttribute("status") != null) {
            String status = session.getAttribute("status").toString();
            if(status != null && status.equals("login")) {
                response.sendRedirect("welcome");
                return;
            }
        }
        
        
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/lesson2/login.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        
        if(email.equalsIgnoreCase("admin@aptechlearning.edu.vn") && password.equals("123")) {
            //login success
            //luu thong tin da dang
            //Su dung Cookie => Quan ly luu tru du lieu
//            Cookie cookie = new Cookie("status", "login");
//            response.addCookie(cookie);
            //Su dung Session => Quan ly luu tru du lieu
            HttpSession session = request.getSession();
            session.setAttribute("status", "login");
            
            response.sendRedirect("welcome");
        } else {
            //login fail
            response.sendRedirect("login");
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


#Student.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson2;

import java.io.Serializable;

/**
 *
 * @author teacher
 */
public class Student implements Serializable{
    String fullname, email, address;

    public Student() {
    }

    public Student(String fullname, String email, String address) {
        this.fullname = fullname;
        this.email = email;
        this.address = address;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


#WelcomeServlet.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author teacher
 */
public class WelcomeServlet extends HttpServlet {
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Check login su dung cookie
//        Cookie[] cookieList = request.getCookies();
//        String status = "";
//        
//        for (Cookie cookie : cookieList) {
//            if(cookie.getName().equals("status")) {
//                status = cookie.getValue();
//                break;
//            }
//        }
//        
//        if(!status.equals("login")) {
//            response.sendRedirect("login");
//            return;
//        }
        //CHeck login su dung session
        HttpSession session = request.getSession();
        String status = session.getAttribute("status").toString();
        if(status == null || !status.equals("login")) {
            response.sendRedirect("login");
            return;
        }
        
        List<Student> studentList = new ArrayList<>();
        //fake du lieu
        studentList.add(new Student("TRAN VAN A", "a@gmail.com", "Ha Noi"));
        studentList.add(new Student("TRAN VAN B", "b@gmail.com", "Ha Noi"));
        studentList.add(new Student("TRAN VAN C", "c@gmail.com", "Nam Dinh"));
        studentList.add(new Student("TRAN VAN D", "d@gmail.com", "Ninh Binh"));
        studentList.add(new Student("TRAN VAN E", "e@gmail.com", "Hai Duong"));
        
        request.setAttribute("studentList", studentList);
        
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/lesson2/welcome.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("status");
        
        response.sendRedirect("login");
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)