Monday, September 1, 2008

My Hello world JSP... :)

Here is a short tutorial of how to create a simple hello world servlet and deploy it in a ApacheTomcat Server.
This is intended for the people who are very new to the JSP and servlets.
Ppl who are experts in the JSP and Servlets find this post very childish.... :D.

On an Overall view we will be doing the following simple steps.
Create a Severlet and its Deployment descripter.
Deploy it in a web server.
Run the page to test the servlet.

Step 1: Create a Project directory some where on your Hard drive.
Example: Create the main project directory HelloWorldApp and three subdirectories with name classes,etc and src respectively.



Step 2: Create a file with name HelloWorldServlet.java, You can copy paste the following code.Your are a java developer... so you can add in some more code here as well... :)




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

public class HelloWorldServlet extends HttpServlet{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{

PrintWriter out = response.getWriter();
java.util.Date today = new java.util.Date();
out.println("<html>"+
"<body>"+
"<h1 align=left>Hello World !!!</h1>"+
"<br>"+"Now the date and time is : "+today+"</body>"+"</html>");
}


}


Step 3: Create a deployment descriptor file i.e web.xml in the etc folder of your project.
Copy paste the following code.






HelloWorld Servlet
HelloWorldServlet


HelloWorld Servlet
/SayHello




Step 4:Compile your servlet classe and generate the class file under the classes folder of your project


F:\DevCore\HelloWorldApp>javac -classpath C:\ApacheTomcat6018\lib\servlet-api.jar -d classes src\HelloWorldServlet.java






Step 5: Create a folder HelloWorldApp under the Tomcat webapps folder.
Create a subfolder WEB-INF under the HelloWorldApp folder
Create a subfolder classes under the WEB-INF folder

Step 6: Copy the web.xml folder from your project directory ot the HelloWorldApp/WEB-INF folder under the Tomcat.
Copy the HelloWorldServlet.class file to the HelloWorldApp/WEB-INF/classes folder under the Tomcat.






Step 7: Start/Restart Apache Tomcat

Step 8: Enter the url "http://localhost/HelloWorldApp/SayHello" into your favourite Web browser...



Hurrah!!!.., here is your JSP Page running...

Ref : Chapter-1, Head First JSP and Servlets

No comments: