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() ; ) { String key=(String)e.nextElement(); String values[]=(String [])query.get(key); for(int n=0 ; n < values.length ; ++n) out.println("<B>"+key+"["+n+"]"+"=</B>"+values[n]+"<BR>"); } out.println("</BODY></HTML>"); out.close(); } }
We built this like so:
javac -classpath /home/ben/software/jars/jsdk-2.0.jar:/usr/local/jdk1.1.8/lib/ classes.zip Simple.java
That is, we supplied the path to the JSDK and the base JDK classes. All that is needed then is to enable it — the simplest way to do that is to add the directory Simple.java into the repository list for the root zone, by setting the following in zone.properties:
repositories=/home/ben/software/unpacked/ApacheJServ-1.1.2/example,/home/ben/work/ suppose-apachebook/samples/servlet-simple
That is, we added the directory to the existing one with a comma. We then test it by surfing to http://your.server/servlets/Simple.If we want, we can add some parameters, and they’ll be displayed. For example,http://your.server/servlets/Simple?name=Ben&name=Peter&something=else should result in the following:
Simple Servlet something[0]=else name[0]=Ben name[1]=Peter
If anything goes wrong with your servlet, you should find the error and stack backtrace in jserv.log.
Of course, you could create a completely new zone for the new servlet, but that struck us as overkill.