Jack E. Moore III
Jack E. Moore III

Reputation: 29

How do I construct a java servlet in tomcat 7 using a javac compiled class file?

I know it has something to do with WEB-INF\classes. But here is the code I compiled after putting the appropriate .jar files in my class path.

import java.io.* ;
import javax.servlet.http.* ;

public class BeeServlet extends HttpServlet
{

    public void doGet( HttpServletRequest request , HttpServletResponse response )
    {
        response.setContentType("text/html");
        try
        {
            PrintWriter out = response.getWriter();
            out.println( "a-buzz-buzz ..." );
            out.close();
        }
        catch( Exception e )
        {
            System.out.println( "cannot get writer: " + e );
        }
    }
}

It compiles fine, but I have not found any type of like example as in where to put it and how to call it with the localhost:8080 URL. I'm doing this without an IDE to try to learn as best I can but this point is simply confusing to me...

EDIT- I had compiled this code. I put it into the tomcat 7.0/webapps/BeeServlet/WEB-INF/classes directory like all the tutorials say to do. I type in localhost:8080/BeeServlet, and nothing happens. This just doesn't make sense.

Upvotes: 1

Views: 3798

Answers (2)

JB Nizet
JB Nizet

Reputation: 692151

The structure of a webapp is the following:

root
  - WEB-INF
      - classes
          - .class files, respecting the package hierarchy
      - lib
          - .jar files used by your application, other than the servlet and JSP jar files
      - web.xml
  - whatever you want

deploy the root directory under webapps, or make a war file containing the contents of the root directory and deploy this war file, and you'll get a webapp.

The web.xml is not necessary since servlet 3.0 (Tomcat 7), if you declare the servlet and its mappings using annotations. Otherwise, you need one.

Upvotes: 1

harpun
harpun

Reputation: 4110

You need a web application deployment descriptor (web.xml), which provides a mapping of the URL to your Servlet and a certain directory structure for your project on the web server. Usually this structure is created for you if you use a web application project template in an IDE.

Theory to read: http://tomcat.apache.org/tomcat-7.0-doc/appdev/deployment.html

Tutorial: http://www.nogoodatcoding.com/howto/deploy-a-servlet-on-tomcat

Example of web.xml file: running and deploying servlet with eclipse and tomcat 7

Upvotes: 1

Related Questions