Site Search :
Standard Enterprise XML Methodology Pattern Setting Tunning Other
Article Contributors
GuestBook
Javapattern Maven
XSourceGen Dev
JetSpeed Test
JLook Image
jLook Family Site


Servlet과 Applet간의 HTTP 통신
 
Servlet과 Applet간의 HTTP 통신을 이용하여 Database 내용을 Applet에 Display하는 방법 ( 2003/04/02 ) 815
Written by ienvyou - 최지웅
2 of 4
 

 

MyApplet.java

public void actionPerformed(ActionEvent evt) {


if (evt.getSource()==users_b){
callServlet("Users");
}else if(evt.getSource()==item_b) {
callServlet("Item");
}


}
private void callServlet(String command) {


try {
URL phoneServlet = new URL(getDocumentBase(), "servlet/MyServlet");
ServletMessage msg = new ServletMessage(phoneServlet);
Properties args = new Properties();

if (command != null && command.length() > 0) {
args.put("name", command);
}
InputStream result = msg.sendMessage(args, ServletMessage.POST);
ObjectInputStream in = new ObjectInputStream(result);
list.removeAll();
if(command.equals("Users")){
UsersEntity users[]=(UsersEntity [])in.readObject();
display(users);
}else if(command.equals("Item")){
ItemEntity item[]=(ItemEntity [])in.readObject();
display(item);
}
} catch (IOException exc) {
showStatus("Cannot read Data: 1" + exc.toString());
}catch(Exception ee){
showStatus("Cannot read Data: 2" + ee.toString());
}


}


public void display(Object o[]){


if(o instanceof UsersEntity[]){
UsersEntity users[]=(UsersEntity[])o;
for (int i=0;i<users.length ;i++ )
{
list.add(users[i].user_id+" "+users[i].getUser_name()+" "+users[i].getUser_address());
}
}else if (o instanceof ItemEntity[]){
ItemEntity item[]=(ItemEntity[])o;
for (int i=0;i<item.length ;i++ )
{
list.add(item[i].getItem_name()+" "+item[i].getItem_price());
}
}


}

Applet에서는 button event를 받아서 사용자가 Users의 정보를 원하는지 Item의 정보를 원하는지에 대해 알게 된다. 이정보는 ServletMessage.class 를 이용하여 POST 혹은 GET방식을 통해 MyServlet에게 전달된다. 즉 우리가 browser를 통해 Servlet을 호출하는것 처럼 code상에서 Servlet을 호출하는 것이다.

다음의 code와 같이 Servlet에게 전달될 변수와 값을 셋팅하고 이값을 POST 방식이나 GET방식으로 전달한다. 마치 html에서 form tag를 이용하여 전달되는 방식이라고 생각하면 된다.

Properties args = new Properties();

if (command != null && command.length() > 0) {
args.put("name", command);
}

Servlet의 호출이 끝이나면 결과값에 대한정보가 output Stream 을 이요하여 받게된다.이때 Server에서는 결과값에 대한것을 ObjectOutputStream을 이용하여 ItemEntity 객체나 UsersEntity 객체의 배열 형태로 client 에게 전달하게 된다.

그결과 값은 display이 라는 method를 이용하여 화면에 결과를 display이 시킨다.

ServletMessage.java

import java.util.*;
import java.net.*;
import java.io.*;

public class ServletMessage {


public static int GET = 0;
public static int POST = 1;
private URL servlet;

public ServletMessage(URL servlet) {

this.servlet = servlet;
System.out.println(servlet.toString());

}
public InputStream sendMessage(Properties args) throws IOException {

return sendMessage(args, POST);

}
public InputStream sendMessage(Properties args, int method)
throws IOException {

if (method == GET) {
URL url = new URL(servlet.toExternalForm() + "?" +
toEncodedString(args));
return url.openStream();

} else {
URLConnection conn = servlet.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);

// POST the request data (html form encoded)
PrintStream out = new PrintStream(conn.getOutputStream());
if (args != null && args.size() > 0) {
System.out.println("POST "+toEncodedString(args));
out.print(toEncodedString(args));
}
out.close(); // ESSENTIAL for this to work!

// Read the POST response data
return conn.getInputStream();
}

}
public String toEncodedString(Properties args) {

StringBuffer sb = new StringBuffer();
if (args != null) {
String sep = "";
Enumeration names = args.propertyNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
System.out.println(name);
sb.append(sep + URLEncoder.encode(name) + "=" +
URLEncoder.encode(args.getProperty(name)));
System.out.println(sep + URLEncoder.encode(name) + "=" +
URLEncoder.encode(args.getProperty(name)));
sep = "&";
}
}
System.out.println(sb.toString());
return sb.toString();

}


}

이 Class에서는 applet에서의 event가 발생되어지면 POST 방식일경우와 GET방식일경우에 따라 Porperties 에 server로 전달되는 정보와 함께 동작 되어진다.

GET방식일경우에는 URL 을 이용하여 Servlet을 호출하게 되고 POST방식일 경우에는 PrintStream out = new PrintStream(conn.getOutputStream()) 을 이용하여 Servlet을 호출하게 된다. Servlet쪽에서는 두가지 방식에 따라 doGet()이 호출 되어지기도 하고 doPost()가 호출 되어지기도 한다.

 

 
1 2 3 4
References
 
Copyright ⓒ 2003 www.javapattern.info & www.jlook.com, an jLOOK co.,LTD