Sử dụng Ajax trong lập trình JavaServer Pages

09:39 25-09-2017BKAP Media

Như chúng ta đã biết Ajax ngày càng được sử dụng phổ biến vì khả năng tương tác cao với người dùng, làm cho ứng dụng web gần với ứng dụng desktop. AJAX viết tắt từ "Asynchronous Javascript and XML", là một kỹ thuật cho phép các ứng dụng web có những hành động giống với các ứng dụng desktop bằng việc gọi không đồng bộ tới server. Điều này loại trừ đi việc xử lý làm mới một trang đầy đủ trong khi chúng ta chỉ cần cập nhật một phần nhỏ của trang.

AJAX được thực thi sử dụng Javascript và XML. XMLHttpRequest là đối tượng thực sẽ hiện các công việc phía sau của AJAX. Dữ liệu trả về có thể là văn bản thuần, dữ liệu XML hoặc có thể là dữ liệu dạng JSON (Javascript Object Notation).

Ngày nay AJAX được sử dụng một cách dễ dàng hơn khi kết hợp với Jquery. Trong bài viết này tôi sẽ hướng dẫn các bạn sử dụng AJAX để gọi tới Servlet từ các trang Jsp và xử lý theo các kiểu dữ liệu trả về của Servlet.

  • Chúng ta hãy cùng thực hiện ví dụ minh họa đầu tiên về cách sử dụng AJAX trong trang jsp một cách đơn giản: (Các ví dụ minh họa được thực hiện trên công cụ Eclipse)

Bước 1: Tạo một Dynamic Web Project đặt tên là "ViDuAjax1"


Bước 2: Tạo một thư mục con "js" bên trong thư mục WebContent.

Copy 2 thư viện: " jquery-3.2.1.min.js" và " app-ajax.js" vào thư mục "js" (hai thư viện này có thể dễ dàng download từ internet).

Bước 3: Tạo một file "index.jsp" trong thư mục WebContent và thêm các nội dung sau:

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Simple Example</title>

<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>

<script type="text/javascript" src="js/app-ajax.js"></script>

<script type="text/javascript">

        $(document).ready(function(){          

                $('#yourname').blur(function(){

                        var name = $('#yourname').val();

                        $.ajax({

                                type: "GET",

                                url : "GetUserServlet",

                                data: {name: name},

                                success: function(responseText){

                                        $('#result').text(responseText);

                                }

                        });

                });

        });

</script>

</head>

<body>

        <form>

                <h1>Simple example using Ajax with JSP and Servlet</h1>

                Enter your name: <input type="text" id="yourname"/>

                <br>

                <br>

 

                <strong>Hello: </strong>:

                <div id="result"></div>        

        </form>

</body>

</html>

Bước 4: Tạo một Servlet tên là "GetUserServlet" và thêm vào code sau:
 

package com.demo.servlet;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class GetUserServlet
 */
@WebServlet("/GetUserServlet")
public class GetUserServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
 
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                String name = request.getParameter("name");
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(name);
        }
 
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                doGet(request, response);
        }
 

Bước 5: Click phải vào project chọn "Run As / Run on Server" và được kết quả như dưới đây:


 

  • Ví dụ tiếp theo chúng ta sẽ thực hiện gọi Servlet từ AJAX và xử lý kết quả trả về là dữ liệu dạng JSON

Bước 1: Tạo Dynamic Web Project đặt tên là " ViDuAjax2"

Bước 2: Tạo một thư mục con "js" bên trong thư mục WebContent.

Copy 2 thư viện: " jquery-3.2.1.min.js" và " app-ajax.js" vào thư mục "js"

Copy thư viện " gson-2.8.1.jar" vào thư mục lib nằm trong thư mục WEB-INF, click chuột phải và chọn Build Path/ Add To Build Path (Sử dụng thư viện này để chuyển kiểu dữ liệu thành dữ liệu dạng JSON).

Bước 3: Tạo file "index.jsp" vào thư mục Web Content và thêm vào nội dung sau:
 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Using AJAX with JSp/Servlet with JSON return type</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/app-ajax.js"></script>
<script type="text/javascript">
        $(document).ready(function(){
                $('#province').change(function(event){
                                var pro = $('#province').val();
                                $.ajax({
                                        type: "GET",
                                        data: {proname: pro},
                                        url: "GetDistrictFromProvince",
                                        success: function(responseJson){
                                                var $dis = $('#district');
                                                $dis.find('option').remove();
                                                $.each(responseJson, function(key, value){
                                                        $('<option>').val(key).text(value).appendTo($dis);
                                                });
                                        }
                                })
                });     
        });
</script>
</head>
<body>
        <h1>Demo Ajax with return type is JSON</h1>
        <form>
                Select Province: <select id="province">
                        <option>=====Provinces====</option>
                        <option value="Ha Noi">Ha Noi</option>
                        <option value="TP. HCM">TP. Ho Chi Minh</option>                        
                        <option value="Da Nang">Da Nang</option>
                </select>
                <br/><br/>
                Select District: <select id="district">
                        <option>=====Districts=====</option>
                </select>
        </form>
</body>

</html>

 

Bước 4: Tạo servlet đặt tên là " GetDistrictFromProvince" và thêm code sau:

package com.demo.servlet;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.google.gson.Gson;
 
/**
 * Servlet implementation class GetDistrictFromProvince
 */
@WebServlet("/GetDistrictFromProvince")
public class GetDistrictFromProvince extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetDistrictFromProvince() {
        super();
        // TODO Auto-generated constructor stub
    }
 
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                Map<Integer, String> listHN = new HashMap<Integer, String>();
                listHN.put(1, "Quan Ba Dinh");
                listHN.put(2, "Quan Cau Giay");
                listHN.put(3, "Quan Ha Ba Trung");
                listHN.put(4, "Huyen Soc Son");
                listHN.put(5, "Huyen Phuc Tho");
                
                Map<Integer, String> listHCM = new HashMap<Integer, String>();
                listHCM.put(1, "Quan 1");
                listHCM.put(2, "Quan 2");
                listHCM.put(3, "Quan Thu Duc");
                listHCM.put(4, "Huyen Cu Chi");
                listHCM.put(5, "Huyen Hoc Mon");
                
                Map<Integer, String> listDN = new HashMap<Integer, String>();
                listDN.put(1, "Quan Hai Chau");
                listDN.put(2, "Quan Thanh Khe");
                listDN.put(3, "Quan Son Tra");
                listDN.put(4, "Huyen Hoa Vang");
                listDN.put(5, "Huyen Hoang Sa");
                
                String proname = request.getParameter("proname");
                String json = null;             
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                if(proname.equals("Ha Noi")){
                        json = new Gson().toJson(listHN);
                }else if(proname.equals("TP. HCM")){
                        json = new Gson().toJson(listHCM);
                }else if(proname.equals("Da Nang")){
                        json = new Gson().toJson(listDN);
                }
                response.getWriter().write(json);
        }
 
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                doGet(request, response);
        }

Bước 5: Chạy thử chương trình và được kết quả:

  • Ví dụ cuối cùng chúng ta sẽ xử lý trong AJAX với kiểu dữ liệu JSONArray để hiển thị một danh sách đối tượng được trả về từ Servlet.

Trong ví dụ này phần tương tác giữa Servlet với database để trả về một danh sách đối tượng chúng ta sẽ không đề cập đến, bởi vì phần này chúng ta có thể làm việc thông qua JDBC hoặc JPA hoặc Hibernate đều rất dễ dàng.

Bước 1: Tạo một Dynamic Web Project và đặt tên là "ViDuAjax3"

Bước 2: : Tạo một thư mục con "js" bên trong thư mục WebContent.

Copy 2 thư viện: " jquery-3.2.1.min.js" và " app-ajax.js" vào thư mục "js"

Copy thư viện " gson-2.8.1.jar" vào thư mục lib nằm trong thư mục WEB-INF, click chuột phải và chọn Build Path/ Add To Build Path (Sử dụng thư viện này để chuyển kiểu dữ liệu thành dữ liệu dạng JSON).

Bước 3: Tạo một class tên là "Product" có nội dung như sau:
 

package com.demo.entity;
 
import java.io.Serializable;
 
public class Product implements Serializable{
        private String proId;
        private String proName;
        private String producer;
        private int yearMaking;
        private double price;
        
        public Product() {
                super();
                // TODO Auto-generated constructor stub
        }
 
        public Product(String proId, String proName, String producer, int yearMaking, double price) {
                super();
                this.proId = proId;
                this.proName = proName;
                this.producer = producer;
                this.yearMaking = yearMaking;
                this.price = price;
        }
 
        public String getProId() {
                return proId;
        }
 
        public void setProId(String proId) {
                this.proId = proId;
        }
 
        public String getProName() {
                return proName;
        }
 
        public void setProName(String proName) {
                this.proName = proName;
        }
 
        public String getProducer() {
                return producer;
        }
 
        public void setProducer(String producer) {
                this.producer = producer;
        }
 
        public int getYearMaking() {
                return yearMaking;
        }
 
        public void setYearMaking(int yearMaking) {
                this.yearMaking = yearMaking;
        }
 
        public double getPrice() {
                return price;
        }
 
        public void setPrice(double price) {
                this.price = price;
        }    

}

 

Bước 4: Tạo một servlet tên là "GetAllProducts" và thêm nội dung code sau:
 

package com.demo.servlet;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.demo.entity.Product;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
 
/**
 * Servlet implementation class GetAllProducts
 */
@WebServlet("/GetAllProducts")
public class GetAllProducts extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetAllProducts() {
        super();
        // TODO Auto-generated constructor stub
    }
 
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                List<Product> listPro = new ArrayList<>();
                listPro.add(new Product("P01", "Ti vi", "Toshiba", 2015, 5000000));
                listPro.add(new Product("P02", "Tu lanh", "Sanyo", 2016, 8000000));
                listPro.add(new Product("P03", "Dieu hoa", "Daikin", 2017, 12000000));
                listPro.add(new Product("P04", "O to CRV", "Honda", 2016, 900000000));
                listPro.add(new Product("P05", "May tinh", "Acer", 2015, 10000000));
                
                Gson gson = new Gson();
                JsonElement element = gson.toJsonTree(listPro, new TypeToken<List<Product>>(){}.getType());
                JsonArray jsonArray = element.getAsJsonArray();
                response.setContentType("application/json");
                response.getWriter().println(jsonArray);
        }
 
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                doGet(request, response);
        }

Bước 5: Tạo trang "index.jsp" và thêm nội dung sau

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax with JsonArray return type</title>
<style type="text/css">
        table, td, th{
                border: 1px solid green;
                font-family: 'Oxygen', sans-serif;
        }
        th{
                background-color:green;
                color: white;
        }
        body{
                text-align: center;
        }
        .container{
                margin-left: auto;
                margin-right: auto;
                width: 40em;
        }
</style>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/app-ajax.js"></script>
<script type="text/javascript">
        $(document).ready(function(){
                $("#tablediv").hide();
                $("#showTable").click(function(event){
                        $.ajax({
                                type: "GET",
                                url : "GetAllProducts",
                                success: function(responseJson){
                                        if(responseJson!=null){
                                                $("#productTable").find("tr:gt(0)").remove();
                                                var table1 = $("#productTable");
                                                $.each(responseJson, function(key, value){
                                                        var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td></tr>");
                                                        rowNew.children().eq(0).text(value['proId']);
                                                        rowNew.children().eq(1).text(value['proName']);
                                                        rowNew.children().eq(2).text(value['producer']);
                                                        rowNew.children().eq(3).text(value['yearMaking']);
                                                        rowNew.children().eq(4).text(value['price']);
                                                        rowNew.appendTo(table1);
                                                });             
                                        }
                                }
                        })                      
                        $("#tablediv").show();
                })
        });
</script>
</head>
<body class="container">
        <h1>AJAX with JSP/Servlet and JSONArray return type</h1>
        <input type="button" value="Show Table" id="showTable"/>
        <div id="tablediv">
                <table cellpadding="0" id="productTable">
                        <tr>
                                <th scope="col">Product Id</th>
                                <th scope="col">Product Name</th>
                                <th scope="col">Producer</th>
                                <th scope="col">Year Making</th>
                                <th scope="col">Price</th>
                        </tr>
                </table>
        </div>
</body>

</html> 


Bước 6: Chạy thử và được kết quả

Bấm vào nút Show Table sẽ được kết quả:
 

Chuyên gia: Nguyễn Duy Quang

   0968276996
< wire:id="ymgPgRMIf2jgh72o7Xmv" wire:initial-data="{"fingerprint":{"id":"ymgPgRMIf2jgh72o7Xmv","name":"embedded.footer","locale":"vn"},"effects":{"listeners":[]},"serverMemo":{"children":[],"errors":[],"htmlHash":"26380eb1","data":[],"dataMeta":[],"checksum":"719746d37643b7570c4bfffb8976c76b39e53e8c8bd7bfcde2ced02c4f973939"}}"!-- Messenger Plugin chat Code -->