JSP Servlets   «Prev  Next»

Lesson 8Reading the servlet response
ObjectiveAdd code to an applet to read the response from a servlet.

Reading Java Servlet Response

The following code example uses Vue.js on the front-end to communicate with the servlet. Communication is achieved using Vue.js as the front end and JavaScript’s fetch() to send data to a Java Servlet backend.
Vue.js Frontend Example
This example assumes:
  • A servlet endpoint exists at /MyServlet
  • The servlet expects a GET or POST parameter named username


<!DOCTYPE html>
<html>
<head>
  <title>Vue to Servlet Example</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
  <div id="app">
    <h2>Send Data to Servlet</h2>
    <input v-model="username" placeholder="Enter username">
    <button @click="sendToServlet">Submit</button>
    <p v-if="response">Response from servlet: {{ response }}</p>
  </div>

  <script>
    const { createApp } = Vue;

    createApp({
      data() {
        return {
          username: '',
          response: ''
        };
      },
      methods: {
        async sendToServlet() {
          try {
            const res = await fetch('/MyServlet', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              body: new URLSearchParams({ username: this.username })
            });

            this.response = await res.text();
          } catch (err) {
            console.error('Error communicating with servlet:', err);
            this.response = 'Error occurred.';
          }
        }
      }
    }).mount('#app');
  </script>
</body>
</html>


✅ Java Servlet Example (Backend)
// MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.println("Hello, " + username + "! This is the servlet response.");
  }
}

🧪 Deployment Notes
The Vue.js frontend uses JavaScript’s `fetch()` function to send a user-provided parameter to a backend Java servlet. In the example, a simple input field is bound to a `username` variable using Vue’s `v-model` directive. When the user clicks the "Submit" button, the `sendToServlet()` method is triggered. This method constructs an HTTP POST request with the `Content-Type` set to `application/x-www-form-urlencoded`, which is the traditional encoding format expected by many Java servlets. The parameter is serialized using `URLSearchParams`, which formats it as a key-value pair in the request body (e.g., `username=Tom`). This mimics the behavior of a traditional HTML form submission but is handled asynchronously with JavaScript, avoiding a full-page reload.
On the server side, the servlet receives the HTTP request and extracts the `username` parameter using `request.getParameter("username")`. After processing the input—whether logging it, querying a database, or generating a dynamic response—the servlet sends back a plain text reply using `response.getWriter().println(...)`. Vue then captures this response using `await res.text()` and binds it to a data variable (`response`), which is automatically rendered in the DOM thanks to Vue's reactive data binding. This seamless exchange of data between the frontend and backend, without reloading the page, demonstrates the advantage of combining modern JavaScript frameworks with classic servlet-based infrastructure.


Reading Java Servlet Response
Input Stream Connection
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
String reply = reader.readLine();
is.close();
Input Stream Connection

line 1 get an input stream from the connection
line 2 first spot, get a buffered reader from the input stream reader
line 3 second spot, get an input stream reader from the input stream
line 4 read the reply from the buffered reader
line 5 close the input stream from the servlet

Java Servlets
This is Java 1.1 code, and it is not as simple as it could be.
The URLConnection class has a getInputStream() method that returns an InputStream.
You could read one byte at a time from this stream if you wished, but it’s nicer to read a line at a time straight into a String that you can pass to other methods, like setText() for the label.
The InputStream class does not have a function that reads more than a byte, unfortunately.
You can read a whole line with the readLine() method of the BufferedReader class.
You can’t build a BufferedReader from an InputStream, but you can build a BufferedReader from an InputStreamReader, and you can build an InputStreamReader from an InputStream. That is what this code does. The end result is a String (called reply in my example) that you can pass to setText() to change the text of the label.
In the next lesson, review what you have learned in this module.

Reading Servlet Response - Exercise

Try your hand at building an applet and servlet that process a form.
Reading Servlet Response - Exercise

SEMrush Software