How to compile a servlet class
Its a very common question that many beginners ask "How to compile a servlet". This is because you need special jars in your classpath to compile a servlet.
Compiling a servlet
Servlets are just like other simple java class but it has dependency on javax.servlet and javax.servlet.http packages.
This packages are part of servlet-api.jar file. servlet-api.jar file comes bundled with the servlet container or you can saperately download it from here.
If you are using Apache tomcat webcontainer, you can find the servlet-api.jar file under common/lib folder.
Step 1: set the classpath to include servlet-api.jar file
- Right click on my computer icon on desktop and select properties.
- Open the advanced tab and click on Environment Variables button, it will open environment variables window.
- Look under System Variables, if CLASSPATH variable is already defined, select it and click edit, it will open Edit System Variable Window. Append semicolon (;) and then path of servlet-api.jar file at the end.
- If CLASSPATH environment variable is not defined, click on New button, it will open New System Variable window.
- In the New System Variable window, enter CLASSPATH as value of Variable Name and path to the servlet-api.jar as Variable Value.
Step 2: Compiling the servlet class
Now servlet class can be compiled just like other simple java class file using javac command.
javac MyFirstServlet.java
For more information on how to set the developement environment read Setting up the developement environmet.