Сервлет для обработки как апплетов, так и http запросов - PullRequest
0 голосов
/ 18 октября 2010

Я создаю решение, в котором сервлет на tomcat6 обрабатывает ввод с другого компьютера, предоставляя веб-страницу jsp.Я также хотел бы, чтобы тот же сервлет связывался с апплетом на той же машине, чтобы показать некоторые результаты и выполнить несколько задач.

Я могу подключиться от апплета к сервлету, используя URLConnection, но когдаПри получении сообщения от сервлета я получаю сообщение об исключении «неверный заголовок потока» из апплета.

Есть идеи?

edit: Сообщение об ошибке:

java.io.StreamCorruptedException: invalid stream header: 0A0A0A3C at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783) at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280) at applet.viewApplet.onSendData(viewApplet.java:126)

Код апплета:

 private URLConnection getServletConnection()
        throws MalformedURLException, IOException {

    // Open the servlet connection
    URL urlServlet = new URL("http://localhost:8080/Servlet");
    connection = urlServlet.openConnection();

    // Config
    connection.setDoInput(true);
    connection.setDoOutput(true);

    connection.setUseCaches (false);
    connection.setDefaultUseCaches (false);

    connection.setRequestProperty(
            "Content-Type",
            "application/x-java-serialized-object");

    return connection;
}

private void onSendData() {
    try {
        // get input data for sending
        String input = "Applet string heading for servlet";

        // send data to the servlet
        connection = getServletConnection();
        OutputStream outstream = connection.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(outstream);
        oos.writeObject(input);
        oos.flush();
        oos.close()

        // receive result from servlet
        InputStream instr = connection.getInputStream();
        ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
        String result = (String) inputFromServlet.readObject();
        inputFromServlet.close();
        instr.close();

        // show result
        textField.setText(result);

    } catch (java.net.MalformedURLException mue) {
        textField.setText("Invalid serlvetUrl, error: " + mue.getMessage());
    } catch (java.io.IOException ioe) {
        textField.setText("Couldn't open a URLConnection, error: " + ioe.getMessage());
    } catch (Exception e) {
        textField.setText("Exception caught, error: " + e.getMessage());
    }
}

Код сервлета:

public class Servlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=ISO-8859-1");
    PrintWriter out = response.getWriter();
    String defect = request.getParameter("defect").toString();

    try {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet at " + request.getContextPath() + "</h1>");
        out.println("<p>Defect: " + defect + "</p>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        response.setContentType("application/x-java-serialized-object");

        InputStream in = request.getInputStream();
        ObjectInputStream inputFromApplet = new ObjectInputStream(in);

        String servletText = "Text from Servlet";

        // echo it to the applet
        OutputStream outstr = response.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(outstr);
        oos.writeObject(servletText);
        oos.flush();
        oos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    processRequest(request, response);
}

1 Ответ

2 голосов
/ 18 октября 2010

Это потому, что вы пытаетесь десериализовать основанное на тексте тело ответа сервлета, используя ObjectInputStream, пока он вообще не сериализуется, и вы должны использовать Reader для этого.

Короче говоря: Как запускать и обрабатывать HTTP-запросы, используя URLConnection? .

...