By GokiSoft.com| 19:15 05/08/2020|
Web Component Development (SERVJSP)

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

#web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
    <servlet>
        <servlet-name>FirstServletAlias</servlet-name>
        <servlet-class>servlet.FirstServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>StudentServlet</servlet-name>
        <servlet-class>servlet.StudentServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>InputStudentServlet</servlet-name>
        <servlet-class>servlet.InputStudentServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>DataStudentServlet</servlet-name>
        <servlet-class>servlet.DataStudentServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServletAlias</servlet-name>
        <url-pattern>/tim-hieu-servlet-bai-1.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>StudentServlet</servlet-name>
        <url-pattern>/danh-sach-sinh-vien.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>InputStudentServlet</servlet-name>
        <url-pattern>/nhap-thong-tin-sinh-vien.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>DataStudentServlet</servlet-name>
        <url-pattern>/data-student-post.html</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>


#first_servlet.jsp


<%-- 
    Document   : first-wervlet
    Created on : Jul 27, 2020, 7:21:57 PM
    Author     : teacher
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Welcome to learn JSP/Servlet!</h1>
        <h2>Hello : 
            <%
                String msg = (String) request.getAttribute("msg");
                out.println(msg);
            %>
            <br/>
            <%=request.getAttribute("msg")%>
        </h2>
    </body>
</html>


#input.jsp


<%-- 
    Document   : input
    Created on : Jul 31, 2020, 7:15:46 PM
    Author     : teacher
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<title>Registation Form * Form Tutorial</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">Registation Form - Input User's Detail Information</h2>
			</div>
			<div class="panel-body">
                            <form method="post" action="data-student-post.html">
                                <div class="form-group">
				  <label for="usr">Name:</label>
                                  <input required="true" type="text" class="form-control" id="usr" name="name">
				</div>
				<div class="form-group">
				  <label for="gender">Gender</label>
                                  <select name="gender" id="gender" class="form-control">
                                      <option value=""> -- Chon Gioi Tinh -- </option>
                                      <option value="Nam">Nam</option>
                                      <option value="Nu">Nu</option>
                                      <option value="Khac">Khac</option>
                                  </select>
				</div>
				<div class="form-group">
				  <label for="rollno">RolNo</label>
                                  <input type="text" class="form-control" id="rollno" name="rollno">
				</div>
				<button class="btn btn-success">Register</button>
                            </form>
			</div>
		</div>
	</div>
</body>
</html>


#student.jsp


<%-- 
    Document   : student
    Created on : Jul 31, 2020, 7:03:35 PM
    Author     : teacher
--%>

<%@page import="java.util.ArrayList"%>
<%@page import="modal.Student"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Danh Sach Sinh Vien - Fake</title>
    </head>
    <body>
        <h1>Danh Sach Sinh Vien!</h1>
        <table border = "1" cellspacing = "3" cellpadding = "3">
            <thead>
                <tr>
                    <th>STT</th>
                    <th>Ho & Ten</th>
                    <th>Email</th>
                    <th>Dia Chi</th>
                    <th>MSV</th>
                </tr>
            </thead>
            <tbody>
                <%
                    ArrayList<Student> list = (ArrayList<Student>) request.getAttribute("studentList");
                    int count = 1;
                    for (Student std : list) {
                %>
                <tr>
                    <td><%=count++%></td>
                    <td><%=std.getFullname()%></td>
                    <td><%=std.getEmail()%></td>
                    <td><%=std.getAddress()%></td>
                    <td><%=std.getRollNo()%></td>
                </tr>
                <%
                    }
                %>
            </tbody>
        </table>
    </body>
</html>


#welcome.jsp


<%-- 
    Document   : welcome
    Created on : Jul 31, 2020, 7:23:55 PM
    Author     : teacher
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <%
//        String name = (String) request.getParameter("name");
        String name = (String) session.getAttribute("s_name");
        Cookie[] cookieLIst = request.getCookies();
        String k_name = "";
        for (Cookie elem : cookieLIst) {
            if(elem.getName().equals("k_name")) {
                k_name = elem.getValue();
            }
        }
    %>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome - <%=name%></title>
    </head>
    <body>
        <h1>Session: Welcome <%=name%>!</h1>
        <h1>Cookie Welcome <%=k_name%>!</h1>
    </body>
</html>


#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 modal;

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

    public Student() {
    }

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

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

    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
}


#DataStudentServlet.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 servlet;

import java.io.IOException;
import java.io.PrintWriter;
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 DataStudentServlet 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 {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/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 {
        String name = (String) request.getParameter("name");
        
        HttpSession session = request.getSession();
        session.setAttribute("s_name", name);
        
        Cookie co = new Cookie("k_name", name);
        response.addCookie(co);
        
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/welcome.jsp");
        dispatcher.forward(request, response);
    }

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

}


#FirstServlet.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 servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author teacher
 */
public class FirstServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FirstServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet FirstServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <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 {
        String msg = "TRAN VAN DIEP";
        request.setAttribute("msg", msg);
        
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/first_servlet.jsp");
//        dispatcher.include(request, response);
        dispatcher.forward(request, response);

        //dung forward => ko su dung code phia duoi => include : se su dung code duoi
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FirstServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Welcome to learn Servlet >> GET</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    /**
     * 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 {
        processRequest(request, response);
    }

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

}


#InputStudentServlet.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 servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author teacher
 */
public class InputStudentServlet 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 {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/input.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 {
        
    }

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

}


#StudentServlet.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 servlet;

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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modal.Student;

/**
 *
 * @author teacher
 */
public class StudentServlet 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 {
        ArrayList<Student> list = new ArrayList<>();
        
        for (int i = 0; i < 10; i++) {
            Student std = new Student("Ten " + i, i+"@gmail.com", "Ha Noi", "R00" + i);
            list.add(std);
        }
        
        request.setAttribute("studentList", list);
        
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/student.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 {
    }

    /**
     * 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)