Writing a Servlet

Now that we have JServ running, let’s add a little servlet to it, just to show how its done. Of course, there’s already a simple servlet in the JServ package, the Hello servlet mentioned earlier; the source is in the example directory, so take a look. We wanted to do something just a little more interesting, so here’s another servlet called Simple, which shows the parameters passed to it. As always, Java requires plenty of code to make this happen, but there you are:

import java.io.PrintWriter; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUtils; public class Simple extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String qstring=request.getQueryString(); Hashtable query; if(qstring == null) qstring=""; try { query=HttpUtils.parseQueryString(qstring); } catch(IllegalArgumentException e) { query=new Hashtable(); String tmp[]=new String[1]; tmp[0]=qstring; query.put("bad query",tmp); } response.setContentType("text/html"); out=response.getWriter(); out.println("<HTML><HEAD><TITLE>Simple Servlet</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>Simple Servlet</H1>"); for(Enumeration e=query.keys() ; e.hasMoreElements() ...

Get Apache: The Definitive Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.