Applet sending object to Servlet problem? HELP!
Hi Guys
Im trying to write a APPLET that writes a Serialized object to a SERVLET.
Here's the connection code within the APPLET
private URLConnection getConnectionToServlet() throws IOException, MalformedURLException
{
URL servletURL = new URL(getCodeBase(),"/ProcessServlet");
URLConnection servletConnection = servletURL.openConnection();
servletConnection.setUseCaches(false);
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
servletConnection.setAllowUserInteraction(false);
return servletConnection;
}
-
Here's the code that try's writing the OBJECT to the SERVLET
OutputStream out;
ObjectOutputStream objectStream;
try
{
URLConnection connection = getConnectionToServlet();
out = connection.getOutputStream();
objectStream = new ObjectOutputStream(out);
//create a new job
Object tmpObject = new Object();
//now send the job object to the Servlet
objectStream.writeObject(newJob);
objectStream.flush();
}
catch (MalformedURLException ex)
{
System.out.println("URL to Servlet Error");
}
catch (IOException ioe)
{
System.out.println("IO Error");
}
--
The problem is nothing is actually happening, there's no EXCEPTIONS and nothing being recieved on the SERVLET side.
I have put the recieving code in the servlet within the doPOST method.
CAN ANYONE PLEASE HELP?
Thanks in advance!!!!!
Hello Ian, i've noteced that kush did not close the outputstream.
Ive changed some of your code and made it work.
Added:
((HttpURLConnection)servletConnection).setRequestMethod("POST");
objectStream.close();
out.close(); // not sure if this is needed should look it up in the API
And read the full response (allso the errorstream) since "keep-alive" is implemented in
URLConnection and I red somewhere that this can couse responses to get mixed up.
Then I've started netbeans and changed the helloworld example in the servlet examples,
here is the full applet and servlet code (note that test.java needs to be added to the
netbeans servlet project)
applet:
import java.applet.Applet;
import java.net.*;
import java.io.*;
public class test extends Applet{
public void init(){
sendObject();
}
private URLConnection getConnectionToServlet() throws IOException, MalformedURLException{
URL servletURL = new URL("http://localhost:8084/TomcatServletExample/servlet/HelloWorldExample");
URLConnection servletConnection = servletURL.openConnection();
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches (false);
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
((HttpURLConnection)servletConnection).setRequestMethod("POST");
servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
servletConnection.setAllowUserInteraction(false);
return servletConnection;
}
private void sendObject(){
OutputStream out;
ObjectOutputStream objectStream;
try{
URLConnection connection = getConnectionToServlet();
out = connection.getOutputStream();
//now send the job object to the Servlet
objectStream = new ObjectOutputStream(out);
objectStream.writeObject(this); // don't read POST in doget or you'll get responsecode 405
objectStream.flush();
objectStream.close();
out.close();
// get the inputstream (server response)
System.out.println(readTextInputStream(connection.getInputStream(),connection));
}catch (Exception ex){
ex.printStackTrace();
}
}
private String readTextInputStream(InputStream is,URLConnection urlc){
byte[] buf = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
int len = 0;
while ((len = is.read(buf)) > 0) {
bos.write(buf, 0, len);
}
// close the inputstream
is.close();
} catch (IOException e) {
try {
// now failing to read the inputstream does not mean the server did not send
// any data, here is how you can read that data, this is needed for the same
// reason mentioned above.
((HttpURLConnection) urlc).getResponseCode();
InputStream es = ((HttpURLConnection) urlc).getErrorStream();
int ret = 0;
// read the response body
while ((ret = es.read(buf)) > 0) {
}
// close the errorstream
es.close();
} catch (IOException ex) {
// deal with the exception
}
}
// TODO: check if there was an enc in the response
//if so use that to convert the byte[] to string
//instead of the default
return new String(bos.toByteArray());
}
}
servlet:
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldExample extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
ObjectInputStream in = null;
try{
// start reading the request
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream hIn = request.getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = hIn.read(buf)) > 0) {
bos.write(buf, 0, len);
}
// give the request to an objectinputstream
in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray() ));
// create the object
Object b = in.readObject();
out.println("received an object, name is: ");
out.println(b.getClass().getName());
in.close();
// should loose bos
bos.reset();
}catch(Exception e){
out.println(e.getMessage());
}
out.println("</body>");
out.println("</html>");
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("get not supported, please POST your info");
}
}
Thanks alot guys, however im getting the following exception, could it be something to do with signing the applet?
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8084 connect,resolve)
)
at java.security.AccessController.checkPermission(AccessController.java:401)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:524)
at java.lang.SecurityManager.checkConnect(SecurityManager.java:1026)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:568)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:306)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:267)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:320)
at sun.net.www.http.HttpClient.New(HttpClient.java:315)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:512)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:489)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:560)
at ClientApplet.peformAddRequest(ClientApplet.java:160)
at ClientApplet.actionPerformed(ClientApplet.java:128)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
at java.awt.Component.processMouseEvent(Component.java:5100)
at java.awt.Component.processEvent(Component.java:4897)
at java.awt.Container.processEvent(Container.java:1569)
at java.awt.Component.dispatchEventImpl(Component.java:3615)
at java.awt.Container.dispatchEventImpl(Container.java:1627)
at java.awt.Component.dispatchEvent(Component.java:3477)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
at java.awt.Container.dispatchEventImpl(Container.java:1613)
at java.awt.Component.dispatchEvent(Component.java:3477)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
Any advise on how to get this working on my machine at home? Im using netbeans and tomcat.
Cheers!