Saturday, September 12, 2015

IP : Java Servlet. Code for displaying "Hello World"


First install tomcat apache server using this post :

http://semlabs.blogspot.com/2015/09/installing-tomcat-server.html

I am assuming you have your tomcat files in /opt/ , or else, change the path accordingly in the below steps and replace "/opt/".

Put this "hello" folder in /opt/tomcat/webapps/

hello - code.

The above folder contains all the code needed to print "Hello World" in your server response page.

To start tomcat server, type these commands in the terminal :

cd /opt/tomcat/bin/

./startup.sh

and type this in your browser :

http://localhost:8080/hello/HelloWorld

This should print "Hello World".

Here "hello" is the web-app , and "HelloWorld" is the url map for the servlet class file, which is also named "HelloWorld".

This is how I coded this Servlet :
  • Created a folder called "hello" in /opt/tomcat/webapps
  • Created a folder called "WEB-INF" inside "hello" folder
  • Created two folders called "classes" and "src" in "WEB-INF" folder.
  • The "WEB-INF" and "classes" folders are very important and must be named same way. I mean, it is case sensitive, and is important.
  • To understand the hierarchy in a better manner, download my "hello" folder!
  • Then created HelloWorld.java and coded it based on Servlet programming and placed it in "src" folder.
  • Created web.xml and defined the servlet name, servlet class name and defined the mapping.
  • Compiled the HelloWorld.java like this :

         javac -cp /opt/tomcat/lib/servlet-api.jar HelloWorld.java




  • Placed the HelloWorld.class file produced the previous step in "classes" folder.
  • Started the server using commands mentioned above and checked the output.


  • To know more about what each of these things mean, and to also know how to code it, look at this pdf by tutorialspoint :

    Servlets

    For any doubts or problems, mail me. This is the most basic Servlet program. This should give you a feel of how to code Servlets! :)

    No comments:

    Post a Comment

    Note: Only a member of this blog may post a comment.