mkngau
asked on
Applet to servlet
Hi,
I got the problem to send my serializable object from Applet to servlet.
I used the method recommended from http://www.j-nine.com/pubs/applet2servlet/Applet2Servlet.html
Anyway, when I run the applet and invoke the method to pass the serializable object to the servlet...nothing seem like to be happen. There is no error message and seem like the servlet have not been invoke by the applet.
Below is my code in applet (the ContentData is a serializable object)
servlet = new URL("http://mars:7001/CWCreateContentServlet");
servletConnection = servlet.openConnection();
/** inform the servlet that applet will send the output and accept input */
servletConnection.setDoInp ut(true);
servletConnection.setDoOut put(true);
/** disable the cache version */
servletConnection.setUseCa ches(false );
//servletConnection.setDef aultUseCac hes(false) ;
/** specified the content type */
//servletConnection.setReq uestProper ty("Conten t-Type", "application/octet-stream" );
servletConnection.setReque stProperty ("Content- Type", "application/x-www-form-ur lencoded") ;
/** send the content object to the servlet using serialization */
outputToServlet = new ObjectOutputStream(servlet Connection .getOutput Stream());
// serialize the object
ContentData content = new ContentData(title, dtdPK, xslPK, bXML, status);
outputToServlet.writeObjec t(content) ;
outputToServlet.flush();
outputToServlet.close();
and here is the code in my servlet :
ObjectInputStream inputFromApplet = new ObjectInputStream(req.getI nputStream ());
ContentData content = null;
inputFromApplet = new ObjectInputStream(req.getI nputStream ());
content = (ContentData)(inputFromApp let.readOb ject());
inputFromApplet.close();
can anyone tell me what's wrong? Thanks.
I got the problem to send my serializable object from Applet to servlet.
I used the method recommended from http://www.j-nine.com/pubs/applet2servlet/Applet2Servlet.html
Anyway, when I run the applet and invoke the method to pass the serializable object to the servlet...nothing seem like to be happen. There is no error message and seem like the servlet have not been invoke by the applet.
Below is my code in applet (the ContentData is a serializable object)
servlet = new URL("http://mars:7001/CWCreateContentServlet");
servletConnection = servlet.openConnection();
/** inform the servlet that applet will send the output and accept input */
servletConnection.setDoInp
servletConnection.setDoOut
/** disable the cache version */
servletConnection.setUseCa
//servletConnection.setDef
/** specified the content type */
//servletConnection.setReq
servletConnection.setReque
/** send the content object to the servlet using serialization */
outputToServlet = new ObjectOutputStream(servlet
// serialize the object
ContentData content = new ContentData(title, dtdPK, xslPK, bXML, status);
outputToServlet.writeObjec
outputToServlet.flush();
outputToServlet.close();
and here is the code in my servlet :
ObjectInputStream inputFromApplet = new ObjectInputStream(req.getI
ContentData content = null;
inputFromApplet = new ObjectInputStream(req.getI
content = (ContentData)(inputFromApp
inputFromApplet.close();
can anyone tell me what's wrong? Thanks.
Make sure the code in your Servlet is in the doPost() method, and not in doGet()
AGE_Nicolls
AGE_Nicolls
You need to specify the content-length, try
something like this:
Applet Code:
protected void writeOrder(URLConnection con, Order value)
{
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(stream) ;
out.writeObject(value);
out.flush();
byte[] buf = stream.toByteArray();
con.setRequestProperty("co ntent-type ","applica tion/octet -stream");
con.setRequestProperty("co ntent-leng th",""+buf .length);
DataOutputStream dataOut = new DataOutputStream(con.getOu tputStream ());
dataOut.write(buf);
dataOut.flush();
dataOut.close();
}
Here is the code you have to put in your servlet to receive the information:
public void service(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get the session
HttpSession session = request.getSession(true);
// If the request is a GET method then call the standard GET method
if (request.getMethod().equal s("GET"))
{
showPage(request, response);
}
else
{
String contentType = request.getContentType();
// If we have to stream to client
if (contentType.equals("appli cation/oct et-stream" ))
{
// Create the output stream
ObjectInputStream in = new ObjectInputStream(request. getInputSt ream());
try{
// Read input parameters
Order order = (Order) in.readObject();
something like this:
Applet Code:
protected void writeOrder(URLConnection con, Order value)
{
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(stream)
out.writeObject(value);
out.flush();
byte[] buf = stream.toByteArray();
con.setRequestProperty("co
con.setRequestProperty("co
DataOutputStream dataOut = new DataOutputStream(con.getOu
dataOut.write(buf);
dataOut.flush();
dataOut.close();
}
Here is the code you have to put in your servlet to receive the information:
public void service(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get the session
HttpSession session = request.getSession(true);
// If the request is a GET method then call the standard GET method
if (request.getMethod().equal
{
showPage(request, response);
}
else
{
String contentType = request.getContentType();
// If we have to stream to client
if (contentType.equals("appli
{
// Create the output stream
ObjectInputStream in = new ObjectInputStream(request.
try{
// Read input parameters
Order order = (Order) in.readObject();
Just write "servletConnection.connect ();" after setDoOutput(true) in your code and try to run your program. Don't forget to compile it. :-)
servletConnection.setDoInp ut(true);
servletConnection.setDoOut put(true);
servletConnection.connect( );
servletConnection.setDoInp
servletConnection.setDoOut
servletConnection.connect(
ASKER
hi venkat2000,
when I put in the servletConnection.connect( );
I got java.lang.IllegalAccessErr or: Already connected
So do you have any idea?
when I put in the servletConnection.connect(
I got java.lang.IllegalAccessErr
So do you have any idea?
ASKER
here is the complete servlet.
/*
* CreateContentServlet.java
*
* Created on June 05, 2001, 1:30 AM
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.*;
import java.util.*;
import com.pws.dtd.*;
import com.pws.template.*;
import com.pws.contentwriter.*;
import com.common.ContentData;
public class CWCreateContentServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
HttpSession session = req.getSession();
String title = "";
String creationDate = "";
DtdPK dtdPK = null;
TemplatePK templatePK = null;
//SitePK sitePK = null;
//UserPK userPK = null;
String status = "";
byte[] bXML = null;
try {
String customerName = req.getParameter("userType ");
ObjectInputStream inputFromApplet = new ObjectInputStream(req.getI nputStream ());
ContentData content = null;
PrintWriter out = null;
if(session.getValue("cw") == null) {
System.out.println("cw == null");
} else {
System.out.println("cw passed");
ContentWriter cw = (ContentWriter)session.get Value("cw" );
creationDate = (String)cw.getDate();
System.out.println("creati onDate : "+creationDate);
inputFromApplet = new ObjectInputStream(req.getI nputStream ());
content = (ContentData)(inputFromApp let.readOb ject());
inputFromApplet.close();
System.out.println("Here") ;
title = content.getTitle();
System.out.println("title : " + title);
cw.createContent(title);
System.out.println("Succes s!");
out = new PrintWriter(resp.getOutput Stream());
resp.setContentType("text/ plain");
out.println("passed!");
out.flush();
out.close();
}
} catch(Exception exc) {
System.out.println("Error CWCreateContentServlet : "+exc);
System.out.println("fail!" );
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doPost(req, resp);
}
}
/*
* CreateContentServlet.java
*
* Created on June 05, 2001, 1:30 AM
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.*;
import java.util.*;
import com.pws.dtd.*;
import com.pws.template.*;
import com.pws.contentwriter.*;
import com.common.ContentData;
public class CWCreateContentServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
HttpSession session = req.getSession();
String title = "";
String creationDate = "";
DtdPK dtdPK = null;
TemplatePK templatePK = null;
//SitePK sitePK = null;
//UserPK userPK = null;
String status = "";
byte[] bXML = null;
try {
String customerName = req.getParameter("userType
ObjectInputStream inputFromApplet = new ObjectInputStream(req.getI
ContentData content = null;
PrintWriter out = null;
if(session.getValue("cw") == null) {
System.out.println("cw == null");
} else {
System.out.println("cw passed");
ContentWriter cw = (ContentWriter)session.get
creationDate = (String)cw.getDate();
System.out.println("creati
inputFromApplet = new ObjectInputStream(req.getI
content = (ContentData)(inputFromApp
inputFromApplet.close();
System.out.println("Here")
title = content.getTitle();
System.out.println("title : " + title);
cw.createContent(title);
System.out.println("Succes
out = new PrintWriter(resp.getOutput
resp.setContentType("text/
out.println("passed!");
out.flush();
out.close();
}
} catch(Exception exc) {
System.out.println("Error CWCreateContentServlet : "+exc);
System.out.println("fail!"
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doPost(req, resp);
}
}
ASKER
here is the codes in the applet :
ObjectInputStream in;
URL servlet = null;
URLConnection servletConnection;
ObjectOutputStream outputToServlet;
try{
System.out.println("Start servlet");
servlet = new URL("http://mars:7001/CWCreateContentServlet");
servletConnection = servlet.openConnection();
/** inform the servlet that applet will send the output and accept input */
servletConnection.setDoInp ut(true);
servletConnection.setDoOut put(true);
/** disable the cache version */
servletConnection.setUseCa ches(false );
servletConnection.setDefau ltUseCache s(false);
/** specified the content type */
servletConnection.setReque stProperty ("content- type", "application/octet-stream" );
/** send the content object to the servlet using serialization */
outputToServlet = new ObjectOutputStream(servlet Connection .getOutput Stream());
// serialize the object
ContentData content = new ContentData(title);
if(outputToServlet == null){
System.out.println("output ToServlet null");
} else {
System.out.println("output ToServlet got value");
}
outputToServlet.writeObjec t(content) ;
outputToServlet.flush();
outputToServlet.close();
System.out.println("title : "+ content.getTitle());
System.out.println("End servlet");
} catch (Exception exc) {
System.out.println("Error create content : " + exc);
}
and when I run it, I got this out put :
Start servlet
outputToServlet got value
title : testing
End servlet
this mean the code in the applet run fine, not exception been returned. But how come the servlet didn't do anything?
ObjectInputStream in;
URL servlet = null;
URLConnection servletConnection;
ObjectOutputStream outputToServlet;
try{
System.out.println("Start servlet");
servlet = new URL("http://mars:7001/CWCreateContentServlet");
servletConnection = servlet.openConnection();
/** inform the servlet that applet will send the output and accept input */
servletConnection.setDoInp
servletConnection.setDoOut
/** disable the cache version */
servletConnection.setUseCa
servletConnection.setDefau
/** specified the content type */
servletConnection.setReque
/** send the content object to the servlet using serialization */
outputToServlet = new ObjectOutputStream(servlet
// serialize the object
ContentData content = new ContentData(title);
if(outputToServlet == null){
System.out.println("output
} else {
System.out.println("output
}
outputToServlet.writeObjec
outputToServlet.flush();
outputToServlet.close();
System.out.println("title : "+ content.getTitle());
System.out.println("End servlet");
} catch (Exception exc) {
System.out.println("Error create content : " + exc);
}
and when I run it, I got this out put :
Start servlet
outputToServlet got value
title : testing
End servlet
this mean the code in the applet run fine, not exception been returned. But how come the servlet didn't do anything?
I am not sure about it .. but I would suggest flushing and closing the connection in the applet like
servletConection.close();
and also to try to comment out the line
req.getParameter("userType ");
in the servlet ...
servletConection.close();
and also to try to comment out the line
req.getParameter("userType
in the servlet ...
ASKER
hi raghbir_banwait,
what are you mean by the "I would suggest flushing and closing the connection in the applet like
servletConection.close();"
I have did the same thing in my applet :
outputToServlet.flush();
outputToServlet.close();
what are you mean by the "I would suggest flushing and closing the connection in the applet like
servletConection.close();"
I have did the same thing in my applet :
outputToServlet.flush();
outputToServlet.close();
I have written a small sample for you to demonstrate applet-servlet communication.
test.html
---------
<html>
<body>
<applet code="TestApplet.class" width=300 height=300>
</applet>
</body>
</html>
TestApplet.java
---------------
import java.io.*;
import java.applet.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestApplet extends Applet {
public void start() {
try{
String s1 = "hello";
String s2 = "hai";
//Create a URL
URL url=new URL("http://localhost:8080/examples/servlet/TestServlet");
//Establish the connection
URLConnection con= url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
OutputStream out=con.getOutputStream();
//Send data to servlet
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(s1);
oos.writeObject(s2);
InputStream in =con.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
//Get reply from servlet
String reply = ois.readObject().toString( );
//Show the corresponding message or redirect the user to the
//next page.
System.out.println("the reply is: " + reply);
oos.close();
ois.close();
} catch (ConnectException ce) {
System.out.println("Connec tion Refused.\nProblem at Web server.\nTry after some time.");
}
catch (Exception e){
System.out.println("Except ion while calling Servlet :"+e);
}
setVisible(true);
} // end of start()
} //end of class TestApplet
TestServlet.java
----------------
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet{
public void init(ServletConfig config) throws ServletException {
System.out.println("in init");
} //end of init()
public void service(HttpServletRequest req, HttpServletResponse res) {
System.out.println("in service");
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try{
ois = new ObjectInputStream(req.getI nputStream ());
oos = new ObjectOutputStream(res.get OutputStre am());
//Get the two strings from applet
String str1 = ois.readObject().toString( );
String str2 = ois.readObject().toString( );
oos.writeObject("The two strings are " + str1 + " and " + str2 + ".");
ois.close();
oos.flush();
oos.close();
oos=null;
} catch(Exception e){
System.out.println(" Servlet service(): " + e);
System.out.println("The exception is: " + e.getMessage());
try{
oos.writeObject("Error occured at server.\nPlease try later");
}catch(IOException ioe) {
System.out.println("IO Exception in error occured"+ioe);
}
}
} //end of service()
} //end of class TestServlet
This example is working fine. Try to do some changes in the lines of this example. It will work.
test.html
---------
<html>
<body>
<applet code="TestApplet.class" width=300 height=300>
</applet>
</body>
</html>
TestApplet.java
---------------
import java.io.*;
import java.applet.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestApplet extends Applet {
public void start() {
try{
String s1 = "hello";
String s2 = "hai";
//Create a URL
URL url=new URL("http://localhost:8080/examples/servlet/TestServlet");
//Establish the connection
URLConnection con= url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
OutputStream out=con.getOutputStream();
//Send data to servlet
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(s1);
oos.writeObject(s2);
InputStream in =con.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
//Get reply from servlet
String reply = ois.readObject().toString(
//Show the corresponding message or redirect the user to the
//next page.
System.out.println("the reply is: " + reply);
oos.close();
ois.close();
} catch (ConnectException ce) {
System.out.println("Connec
}
catch (Exception e){
System.out.println("Except
}
setVisible(true);
} // end of start()
} //end of class TestApplet
TestServlet.java
----------------
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet{
public void init(ServletConfig config) throws ServletException {
System.out.println("in init");
} //end of init()
public void service(HttpServletRequest
System.out.println("in service");
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try{
ois = new ObjectInputStream(req.getI
oos = new ObjectOutputStream(res.get
//Get the two strings from applet
String str1 = ois.readObject().toString(
String str2 = ois.readObject().toString(
oos.writeObject("The two strings are " + str1 + " and " + str2 + ".");
ois.close();
oos.flush();
oos.close();
oos=null;
} catch(Exception e){
System.out.println(" Servlet service(): " + e);
System.out.println("The exception is: " + e.getMessage());
try{
oos.writeObject("Error occured at server.\nPlease try later");
}catch(IOException ioe) {
System.out.println("IO Exception in error occured"+ioe);
}
}
} //end of service()
} //end of class TestServlet
This example is working fine. Try to do some changes in the lines of this example. It will work.
Remember to place the applet class, and the html file in the doc root of your webserver. Place the servlet in the servlet root. Change the url for calling the servlet in the applet code and then compile it.
I would suggest a few changes in your code.
Changes in servlet
------------------
1. Use service() method instead of both doGet and doPost for the time being. Once the servlet starts working, u can play with the methods. i.e., Cut the code in doPost method and paste it in service() method and remove doXXX methods.
2. Now the code is in service() method. Remove the line "inputFromApplet = new ObjectInputStream(req.getI nputStream ());" from the else part.
3. Cut the line "out = new PrintWriter(resp.getOutput Stream()); " from the else block and paste it just after the line "PrintWriter out = null;" and before if statement.
4. Write the line "inputFromApplet.close();" before "out.flush();"
5. Make sure that the servlet url u specified in the applet is correct. To do so, u can type the servlet url in the browser address bar and press enter. See whether ur servlet is inited or not.
I hope, this will help you in solving your problem.
I would suggest a few changes in your code.
Changes in servlet
------------------
1. Use service() method instead of both doGet and doPost for the time being. Once the servlet starts working, u can play with the methods. i.e., Cut the code in doPost method and paste it in service() method and remove doXXX methods.
2. Now the code is in service() method. Remove the line "inputFromApplet = new ObjectInputStream(req.getI
3. Cut the line "out = new PrintWriter(resp.getOutput
4. Write the line "inputFromApplet.close();"
5. Make sure that the servlet url u specified in the applet is correct. To do so, u can type the servlet url in the browser address bar and press enter. See whether ur servlet is inited or not.
I hope, this will help you in solving your problem.
ASKER
hi venkat2000,
Thanks for your help. I have solve my problem. I will award the point to you. by the way, I want to check something with you, is the applet and servlet need to have both the ObjectInputStream and ObjectOutputStream? If missing one, that mean the communication cannot be establish? Thanks.
Thanks for your help. I have solve my problem. I will award the point to you. by the way, I want to check something with you, is the applet and servlet need to have both the ObjectInputStream and ObjectOutputStream? If missing one, that mean the communication cannot be establish? Thanks.
ASKER
hi venkat2000,
Thanks for your help. I have solve my problem. I will award the point to you. by the way, I want to check something with you, is the applet and servlet need to have both the ObjectInputStream and ObjectOutputStream? If missing one, that mean the communication cannot be establish? Thanks.
Thanks for your help. I have solve my problem. I will award the point to you. by the way, I want to check something with you, is the applet and servlet need to have both the ObjectInputStream and ObjectOutputStream? If missing one, that mean the communication cannot be establish? Thanks.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Dear mkngau,
I think your codes are nearly correct, and it will do alright if you add the following line code after you call
outputToServlet.close();
InputStream in =con.getInputStream();
this line code make the call to servlet actually
I think your codes are nearly correct, and it will do alright if you add the following line code after you call
outputToServlet.close();
InputStream in =con.getInputStream();
this line code make the call to servlet actually
ASKER
hi sontnvn,
Thanks for your information. Anyway, venkat2000 have help me to solve this problem. See you.
Hi venkat2000,
Thanks for you help. See you.
regards,
mkngau
Thanks for your information. Anyway, venkat2000 have help me to solve this problem. See you.
Hi venkat2000,
Thanks for you help. See you.
regards,
mkngau
thanks for the points :-)
any exception
Shyam