Lưu trữ

Archive for the ‘JSP’ Category

Chọn(Select) dữ liệu từ một bảng trong JSP

Đoạn mã sau sẻ lấy một record ra từ bảng dữ liệu. Code này đầy trên Net mình chỉ sưu tầm và chỉnh lại tí thôi. Chỉ mang tính tham khảo!!!

String id = cust_id.getText();
try
{
PreparedStatement prepstmt;
boolean found = false;
prepstmt = theConn.dbConn.prepareStatement
(“select custName, CustAddr from tCust where custId = ?”);
prepstmt.setString(1, id);

ResultSet rs;
rs = prepstmt.executeQuery();

found = rs.next();
if (found)
System.out.println(rs.getString(1));
else
System.out.println(“Customer ” + id + ” not found!”);
prepstmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}


Để lấy nhiều mẫu tin hơn, hãy áp dụng tương tự như đoạn mã sau:
String name = cust_name.getText();
try
{
Statement stmt;
String sql;

sql = “select custName from tCust where custName = ” += “‘” + name + “‘”;
stmt = createStatement();

ResultSet rs;
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(“custName”));
}
stmt.close();
rs.close();
}
catch (Exception e)
{
e.printStackTrace();
}


Categories: JSP

Lấy & Xóa Cookie bên Client Từ Servlet

Vừa học xong cái này nên viết lại cho nhớ chứ hok có gì hết :D .

Để truy xuất đến bất kì Cookie nào được gởi đến trình duyết thông qua đối tượng  javax.servlet.http.HttpServletRequest - phương thức là doGet doPost. HttpServletResonse chứa phương thức Cookies[] getCookies() trả về một mảng đối tượng Cookie.

thử tí nhá :D .
// Lay cac cookie
Cookie[] ck = request.getCookies();

// Kiem tra xem co cookie nao ton tai khong
if (ck != null)
{
for (int i = 0; i < ck.length; i++)
{
Cookie aCk = ck[i];
System.out.println (“Name : ” + aCk.getName());
System.out.println (“Value: ” + aCk.getValue());
}
}
Chài thế là xong! 1 Chủ nhật như bao chủ nhật : laptop vs cafe đen


Mới đi đú đởn bên làng Đại Học với con em về …. chài làm quen dc bé khoa KT DHQG xinh ơi là xinh luôn :D .

đoạn code này cho phép xóa hoặc điểu chỉnh cookie theo ý muốn của mình .

import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
Cookie cookie = new Cookie (“myCookie”, “theCookieValue”);

// Het han trong 5 phut (5 * 60)
cookie.setMaxTime( 300 );

// Het han sau khi dong trinh duyet
// cookie.setMaxTime( -1 );

// Het han ngay lap tuc
// cookie.setMaxTime( 0 );
}

public void doGet(HttpServletRequest req, HttpServletResponse res)
{
doPost(req, res);
}
}

Categories: JSP