Blogs YAM

Tìm kiếm nội dung



May
26

Load dữ liệu bằng AJAX vào trang JSP

Chuyên mục : Java web - viết bởi : Mr.Storm


Bài viết này giúp chúng ta load dữ liệu lên trang jsp bằng ajax

Trước tiên bạn phải biết kết nối đến server ... Xem tại đây 

Bạn phải biết sử dụng javabeans .... Xem tại đây

 

Bây giờ bạn có thể bắt đầu làm việc rồi đấy ..

B1 :  Bạn tạo 2 file JSP 

     - 1 file index.jsp

 

<%--
    Document   : index
    Created on : May 20, 2010, 9:54:50 AM
    Author     : HP DV6
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@page language="java" import="java.io.*" %>
<%@page language="java" import="Connection.ConnectionServer" %>
<%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script language="javascript" src="js/action.js">
        </script>
        <jsp:useBean id="listCategory" class="Mybean.CategoriesList" />
    </head>
    <body>
        Parent Caregories :
        <select onchange="getCate(this.value)">
            <c:forEach var="arr" items="${listCategory.listCate}">
                <option value="<c:out value="${arr.idCate}"></c:out>"> <c:out value="${arr.nameCate}"></c:out></option>
            </c:forEach>
        </select>
        <div id="txtHint"></div>
    </body>
</html>

    -  1 file test.jsp

<%--
    Document   : test
    Created on : May 22, 2010, 10:40:43 AM
    Author     : HP DV6
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@page language="java" import="java.io.*" %>
<%@page language="java" import="Connection.ConnectionServer;" %>

        <% ConnectionServer objCon = new ConnectionServer();
            String root = request.getParameter("root");
                objCon.Select("select * from yam_categories where cat_parent_id = '"+root+"'");

                %>
                <label for="editfname">
                Sub category </label><select name="slv">
                    <%
                while(objCon.rows.next()) { %>
                        <option  value="<%=objCon.rows.getInt("cat_id")%>">
                            <%=objCon.rows.getString("cat_name")%>
                        </option>
                           <%  } %>
            </select>

B2 : Bạn tạo 1 file javascript

     -  tên file là action.js trong thư mục js

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
function getCate(root)
{
if (root=="")
  {
  document.getElementById("txtHint").innerHTML="Dang load...";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test.jsp?root="+root,true);
xmlhttp.send();
}

B3 : Tạo 1 file java class để kết nối đến server 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author HP DV6
 */
public class ConnectionServer {
    //Bien thi hanh
    Connection con = null;
    private Statement st;
    public ResultSet rows;
    //Chuoi connect
    String servername = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    public Connection conn = null;

    public ConnectionServer()
    {
        this.servername="localhost";
        this.port="1433";
        this.username="sa";
        this.password="123456";
        this.database="YAM_SHOPPING_CART";
        try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            this.con = DriverManager.getConnection(this.getConnectionString());
            if(this.con != null) {
                System.out.println("Connect successfully .");
            }
            else {
                System.out.println("Connect faild .");
            }
        }
        catch(ClassNotFoundException ce) {
            ce.printStackTrace();
        }
        catch (SQLException ex) {
                ex.printStackTrace();
            }
        catch (Exception ex) {
                Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
            }
    }

    public void CloseConnection() {
        try {
            this.con.close();
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public ConnectionServer(Statement st, ResultSet rows) {
        this.st = st;
        this.rows = rows;
    }

    //Cau lenh gep chuoi connect
    public String getConnectionString() throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append("jdbc:sqlserver://");
        sb.append(servername);
        sb.append(":");
        sb.append(port);
        sb.append(";databaseName=");
        sb.append(database);
        sb.append(";user=");
        sb.append(username);
        sb.append(";password=");
        sb.append(password);
        return sb.toString();
    }

    //Gui cau lenh truy van - Select du lieu
    public void Select(String sql){
        try {
            this.st = this.con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
            rows = st.executeQuery(sql);
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //Gui cau lenh truy van - Insert du lieu
    public void Insert(String sql){
        try {
            st = con.createStatement();
             st.executeUpdate(sql);
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //Dong ket noi - Close Connection
    public void Close(){
        try {
            con.close();
        } catch (SQLException ex) {
            System.out.println(ex);
        }
    }

}

B4 : Tạo 1 database 

use master 
go

create database YAM_SHOPPING_CART
go

use YAM_SHOPPING_CART
go
--Table Category
create table yam_categories
(
	cat_id int not null primary key identity(1,1),
	cat_code varchar(7) unique,
	cat_name nvarchar(50),
	cat_description nvarchar(100),
	cat_img varchar(200),
	cat_parent_id int default 0 , -- 0  là parent
	cat_status int default 1,
)
go

insert into yam_categories(cat_code,cat_name,cat_description,cat_img,cat_parent_id) values('01','Fashion','Fashion','img.jsp','0')
insert into yam_categories(cat_code,cat_name,cat_description,cat_img,cat_parent_id) values('02','Sub Fashion 1','Fashion','img.jsp','1')
insert into yam_categories(cat_code,cat_name,cat_description,cat_img,cat_parent_id) values('03','Sub Fashion 2','Fashion','img.jsp','1')

insert into yam_categories(cat_code,cat_name,cat_description,cat_img,cat_parent_id) values('04','Souvenirs','Souvenirs','img.jsp','0')
insert into yam_categories(cat_code,cat_name,cat_description,cat_img,cat_parent_id) values('05','Sub Souvenirs 1','Souvenirs','img.jsp','4')
insert into yam_categories(cat_code,cat_name,cat_description,cat_img,cat_parent_id) values('06','Sub Souvenirs 2','Souvenirs','img.jsp','4')

 

Ngoài ra bạn có thể download project tại đây

YAM -You And Me


Ý kiến / Bình luận

Bảy Sữa :

2010-06-15 15:46:10

Cách làm này có nhiều nhược điểm, theo tôi nghĩ bạn không nên sử dụng Thứ 1: Chúng ta không nên truy cập trực tiếp từ trang jsp vào cơ sở dữ liệu. Thứ 2: Nếu Hacker sử dụng chính phương pháp này để tấn công bạn sẽ ngăn chặn bằng cách nào? Thứ 3: Nếu trình duyệt ngăn chặn java script thì trang web của bạn sẽ ra sao? Thứ 4: Điều quan trọng trong bảo mật là không nên để người khác thấy tên table, bạn dùng cách này chỉ cần xem source code họ sẽ biết tên table. Một số góp ý mong bạn suy nghĩ



Mr.Storm :

2010-06-21 15:05:11

Đúng là như bạn nói, mình chỉ mới học sơ sơ về java web này thôi .. nên mình củng còn rất yếu .. Bạn có thể để lại địa chỉ email của bạn để mình có thể liên lạc với nhau ko ???



Gửi bình luận






Gửi ý kiến

Chuyên mục

Xem nhiều nhất

Bài viết nổi bật

Xem bài viết theo tháng

Danh sách Tags