Tomcat 7: Deploying a simple Servlet

Now you've deployed a simple JSP, you can now alter that to deploy a simple servlet.

First change the web.xml file to point to a servlet. Not the new servlet-class tag.

 <web-app xmlns="" 
   <display-name>Hello, World Application</display-name>
   <description> A simple servlet </description>

And now create the file in src/org/denevell/tomcat/

 public final class Hello extends HttpServlet {
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
      throws IOException, ServletException {
        PrintWriter writer = response.getWriter();

We're extending a servlet class, and overriding the doGet method that deals with HTTP GET requests. The first parameter is what's sent to the serlvet and the second is what's going back to the client. In it we simply set the content type, get its writer and write something to it.

We now need to update our build.xml to ensure we're compiling this class. Note we've set a new property to point to your tomcat directory, added the libraries in a classpath, and created a new javac and copy task in the compile target.

    <property name="catalina.home" value="/usr/share/tomcat7" />
    <path id="compile.classpath">
      <fileset dir="${catalina.home}/bin">
        <include name="*.jar"/>
      <pathelement location="${catalina.home}/lib"/>
      <fileset dir="${catalina.home}/lib">
        <include name="*.jar"/>
    <target name="compile" depends="prepare">
      <javac srcdir="${src.home}" includeantruntime="false" destdir="${build.home}/WEB-INF/classes">
        <classpath refid="compile.classpath"/>
      <copy todir="${build.home}/WEB-INF/classes">
        <fileset dir="${src.home}" excludes="**/*.java"/>

Now you can deploy that servlet and see your new servlet at (if you've deployed it to hiya/ again):

java-tomcat java-tomcat-setup java-ant java-tomcat-httpservlet java

Edit on github
comments powered by Disqus
Click me