Friday 6 February 2009

Servlet Basic Tutorial

This is the Servlet Basic tutorial. I'll guide you to run your first Servlet through the rest of this post.
First of all, you have to install java. You can download the latest Java version from here
I use Apache Tomcat for the server which you can download it here then install both of them to your computer.

After installing(I assume that you install both to their default path installation), you can begin editing your first servlet. To make it easier, I use template for Servlet class. The template will look like this :

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

//MyServet is the class name
public class MyServlet extends HttpServlet{

//Method for handling Get
//Default method is Get
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

response.setContentType("text/html"); // this should be called first

PrintWriter out = response.getWriter(); // Returns a PrintWriter

out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");

//Logic goes here
//Example :
out.println("<font color='blue'>");
out.print("Hello Word");
out.println("</font>");

out.println("</body>");
out.println("</html>");

out.close();

}

//Method for handling Post
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//you can leave it blank , if you don't use post method
}

}

From the root server directory, the default root directory is "webapps" or in the absolute path "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps" if your Tomcat version is 5.X. Make a new folder,name it "exercise". Now, in webapps folder, there is a folder named "exercise". Create the file structure like this :
>exercise(directory)
--->WEB-INF(directory)
------>web.xml(file)
------>classes(directory)
------>MyServlet.java(file)
------>servlet-api.jar(file)
------>lib(directory)

You can download servlet-api.jar here

Open MyServlet.java with your favorite editor. I use notepad++ in this tutorial which you can also download it here
Now, we'll make the classical "Hello World" application to your first servlet. Just copy and paste the code to your editor. After it, save the file.

Open web.xml, copy the following code to that file then save.

<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>

The java source code(MyServlet.java) is now ready to be compiled. The question is "How can I compile the file?"
You can compile it by using your commmand prompt. I use Windows XP for the operating system.
Before you start, you must set the Environment variable path. You can do this by going to Control Panel -> System -> click Advanced tab then edit Path variable by adding this code ";C:\Program Files\Java\jdk1.6.0_07\bin;" (without double quotes) then OK and OK and OK. The code you can get it by exploring Java folder, every Java version can have a different path, so you must get the path by yourself. I just give you my Java path.

Let's move on! You can open the command prompt by pressing Windows + R and then you type "cmd" (without double quotes) then press ENTER.
Now, the command prompt window is opened. Then type "CD C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\exercise\WEB-INF\classes" (depends on the server installation path) then press ENTER. Type "javac -cp .;servlet-api.jar MyServlet.java" then press ENTER. You'll see that if there are no error, the new file MyServlet.class will be generated by that process. So that, in you classes folder, there are MyServlet.java, servlet-api.jar,MyServlet.class.

Run the Tomcat server now. I know you can run the server , so I don't explain it here. Open your browser, type
"http://localhost:8080/exercise/MyServlet" (without double quotes) , then press ENTER. You'll see the "Hello World" and the color of that words is BLUE. Please remember that any changes you made to MyServlet.java, after you compiled it, you must restart the server to make effects.

You can download the entire project here

Great! You've already run your first Servlet ever! Thank you for reading this tutorial, I hope you can enjoy! If there are problems you can post comments or chat with me!

4 comments:

Unknown said...

Pertamax gan ^^
hahaha...
G masi kaga ngarti nih Nis,
point utama beda servlet n jsp apaan sih ? ^^
bingung g...

Btw g uda klik google adsnya tuh ^^

Unknown said...

Tes2,
koq nama g kluarnya Nama Blog g ya,
ga bs nama g >.<

Anonymous said...

pertanyaan gw sama ma yg diatas, apa perbedaan jsp ma servlet? trus kalo di ujian, kt mesti nulis semua sintaksnya dari awal ampe akhir kayak yg di cth itu yah? bukannya susah ngafalinnya? ato cukup logicnya aja yg ditulis?

leonard said...

Actually, JSP and Servlet are the same. Tomcat will parse JSP code, and will make it Servlet. So, if you'd coded JSP, your code would be parsed by Tomcat and it will generated some Servlet as the result.

Try to open this path "C:\Program Files\Apache Software Foundation\Tomcat 5.5\work\Catalina\localhost" and you'll see how amazing it is. There would be some file generated automatically by Tomcat.