24/05/2018, 21:22

Accessing a Java servlet

Ví dụ dưới đây sẽ chỉ cho bạn từng bước cách truy truy xuất java servlet. Bước đầu, client sẽ truyền tham số cho servlet yêu cầu trả về ngày tháng theo định dạng. Servlet sẽ trà về kết quả, và sẽ hiện lên màn hình. Đây là kết quả cho chuỗi: ...

Ví dụ dưới đây sẽ chỉ cho bạn từng bước cách truy truy xuất java servlet. Bước đầu, client sẽ truyền tham số cho servlet yêu cầu trả về ngày tháng theo định dạng. Servlet sẽ trà về kết quả, và sẽ hiện lên màn hình.

Đây là kết quả cho chuỗi: “yyyy.MM.dd+'at'+hh:mm:ss+zzz"

Trong hình trên, ta thấy ở phần kết quả có time zones là ICT, do ta đã truyền tham số

“zzz”, nếu chuyển thành “zzzz” để lấy full text của time zones thì kết quả sẽ thay đổi như sau:

Calling Servlet

Yêu cầu gọi servlet sẽ đuợc khai báo bên trong commandAction(), và sẽ được thực hiện khi button cmRqst được kích hoạt:

/*--------------------------------------------------

* Call the servlet

*-------------------------------------------------*/

public void commandAction(Command c, Displayable s)

{

if (c == cmRqst)

{

try

{

serverMsg = null;

callServlet();

if (serverMsg != null)

fmMain.append(serverMsg);

}

catch (Exception e)

{

System.err.println("Msg: " + e.toString());

}

}

else if (c == cmExit)

{

destroyApp(false);

notifyDestroyed();

}

}

Dưới đây là đoạn code cho phương thức callServlet(), chú ý rằng request của client sử dụng request method là GET,:

/*--------------------------------------------------

* Call the servlet

*-------------------------------------------------*/

private void callServlet() throws IOException

{

HttpConnection http = null;

InputStream iStrm = null;

boolean ret = false;

// Examples - Data is passed at the end of url for GET

String url = "http://localhost:8080/j2me/dateformatservlet?format=MMMM.dd.yyyy+'-

'+hh:mm+aa";

// String url =

"http://localhost:8080/j2me/dateformatservlet?format=yyyy.MM.dd+'at'+hh:mm:ss+zzz";

try

{

http = (HttpConnection) Connector.open(url);

//----------------

// Client Request

//----------------

// 1) Send request method

http.setRequestMethod(HttpConnection.GET);

// 2) Send header information - none

// 3) Send body/data - data is at the end of URL

//----------------

// Server Response

//----------------

iStrm = http.openInputStream();

// Three steps are processed in this method call

ret = processServerResponse(http, iStrm);

}

finally

{

// Clean up

if (iStrm != null)

iStrm.close();

if (http != null)

http.close();

}

// Process request failed, show alert

if (ret == false)

showAlert(errorMsg);

}

Code cho servlet, hầu hết các phương thức đều được biết trong doPost(), biến format dùng để lưu request từ client, sau đó servlet sẽ gọi SimpleDateFormat để tạo ra kết quả phù hợp với request:

import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

import java.util.Date;

import java.text.SimpleDateFormat;

import java.util.TimeZone;

import java.util.Locale;

public class DateFormatServlet extends HttpServlet

{

public void init(ServletConfig config) throws ServletException

{

super.init(config);

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

{

doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

{

String format = request.getParameter("format");

SimpleDateFormat simpleDate = new SimpleDateFormat(format);

Date dt = new Date();

PrintWriter out = response.getWriter();

response.setContentType("text/html");

out.println(simpleDate.format(dt));

out.close();

}

public String getServletInfo()

{

return "DateFormatServlet";

}

}

Để MIDlet nhận kết quả trả về từ servlet, trước hết phải kiểm tra status line với server và có kết trả về kết quả hay không (HTTP_OK). Do không có thông tin header nên sẽ tiến hành lấy kết quả từ input stream:

/*--------------------------------------------------

* Process a response from a server

*-------------------------------------------------*/

private boolean processServerResponse(HttpConnection http, InputStream iStrm)

throws IOException

{

//Reset error message

errorMsg = null;

// 1) Get status Line

if (http.getResponseCode() == HttpConnection.HTTP_OK)

{

// 2) Get header information - none

// 3) Get body (data)

int length = (int) http.getLength();

String str;

if (length != -1)

{

byte servletData[] = new byte[length];

iStrm.read(servletData);

str = new String(servletData);

}

else // Length not available...

{

ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

int ch;

while ((ch = iStrm.read()) != -1)

bStrm.write(ch);

str = new String(bStrm.toByteArray());

bStrm.close();

}

// Save the server message

serverMsg = str;

return true;

}

else

// Use message from the servlet

errorMsg = new String( http.getResponseMessage());

return false;

}

0