JSP Servlets   «Prev  Next»

Lesson 6Servlet’s response to the GET
Objective Explain how little is different on the server side.

Servlet Response to GET

Most people expect that a servlet such as the one you are about to write, that communicates with an applet, will be very different from othe servlets you have written. The surprise is that it is not. Your servlet will be sent a GET request, and it needs to send back some sort of reply.
Nothing important changes because the GET came from an applet rather than a URL the user typed.
Specifically, the doGet() method still takes the same parameters, still sets the response type, and still adds text to the response through a writer object. The parameters that the applet added to the end of the URL (after the question mark) are accessed just like the parameters from an HTML form.
The only significant differences between the form-processing servlet and the applet-communicating servlet are that the servlet that handles applet requests does not need to emit HTML. It does not produce a form in response to a GET request, and it doesn’t need to handle POST requests. It has no doPost() method, and a very simple doGet() method. It’s very similar to the servlet used in Module 2 with server side includes. Here is the whole servlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Greeter extends HttpServlet{
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();  
    
    //Get the name from the request
    String[] vals = req.getParameterValues("name");  
    if (vals != null) {
        String name = vals[0];
        if (name.length() > 0){
            out.println("Hello, " + name);
        }
        else {
          out.println("Hello, who ever you are");
        }
    }
  }
}

None of this code should need any explanation. You have seen it all before. It is so simple because it does not need to write any HTML, just send back a string based on the “name” parameter that is sent along.

Page Generation

The most basic type of HTTP servlet generates a full HTML page. Such a servlet has access to the same information usually sent to a CGI script, plus a bit more. A servlet that generates an HTML page can be used for all the tasks where CGI is used currently, such as for processing HTML forms, producing reports from a database, taking orders, checking identities, and so forth.
In the next lesson, learn how the applet displays the string that the servlet sends.