Thursday 2 August 2012


Tomcat 6 Web Application,  tutorial.

In this tutorial we will create a web application from scratch!

You must have:
JDK
Ant
Eclipse

1) Get Tomcat
          - Got to google, type: “tomcat download”, click on http://tomcat.apache.org/.
          - Lets get 6, choose & from left menu and click on it.
          - Under “Binary distributions”, under “Core” click on zip.
          - Save it in directory say “C:\temp” (from now we’ll refer to it as temp).

2) Go to temp and open the archive, see what’s inside. Now extract archive to “C” drive. Now you should have a directory called “apache-tomcat-6.0.29” for this tutorial lets refer to this directory as “TOMCAT_HOME”.

3) Now lets start it! Go to “TOMCAT_HOME\bin”, clisk on “startup.bat”. An applet (lets refer to it as server applet for this tutorial) should appear showing the log and at the bottom saying “INFO: Server startup in 1027 ms”. Now type in the browser addres, the following: http://localhost:8080/. You should see tomcat page come up, on this page you would see following: If you're seeing this page via a web browser, it means you've setup Tomcat successfully. Congratulations!

4) Now lets add configuration to see console completely. Navigate to TOMCAT_HOME\conf and open tomcat-users.xml and add the following:

cfg 1
<role rolename="manager"/>
<user username="tomcat" password="tomcat" roles="manager"/>
Try clicking on the left panel Status and Tomcat Manager links. Now kill the server we started at first, by closing the server applet.

5) Now lets add Tomcat to eclipse. Open eclipse, create a new workspace ( “tomcatTutorialWS”) if you don’t have one. Switch to Java EE perspective, right click in “Servers” tab and click on new à server.  From the list, under Apache choose Tomcat 6, click “next”, click on browse and choose TOMCAT_HOME directory and press ok, click next, and click finish. Double click on server that just appeared under servers, under Server Location, choose “Use Tomcat installation”, under Deploy path click Browse and choose “TOMCAT_HOME\webapps” and press ok. Now under Tinmeouts time 1000 for Start and Stop. Now press CTRL + S to save configuration.
Right click on tomcat under servers and click à start. In the Project Explorer view you should see Servers project appear. Right click on project name, choose new à folder. Click “Advanced” on the bottom, choose link to alternative location, click browse to TOMCAT_HOME\conf and press ok. Click Finish. You should now see the configuration folder on the left, under Servers project. You may have to edit tomcat-users.xml under Servers under conf folder again and restart the server.

Now, we are done setting-up the server with eclipse.


Application

1) Lets create a small WEB application with a servlet.

2) Create a Java project in eclipse.
          - Switch to Java perspective.
          - Right click on package explorer, new à Java Project.
- Type in the name tomcatWebApp (we’ll refer to it as project), click next, click finish.
- Right click on project name, new à folder, in “Folder Name”, type lib, click finish.
- Now lets copy all libraries we might need from TOMCAT_HOME\lib to project\lib.
- Now lets add all those jars to project classpath. Right click on project name, choose “Properties”. Select Java Build Path, click on “libraries” tab on the right, click on “Add Jars” on the right button. Select project, select lib, select al JAR files in there, press ok, press ok on Properties screen.
- We will create a WAR project, it needs to have WEB-INF folder inside the folder, needs to be an web.xml file.
- Lets create a folder called resources in the root of the project, inside resources folder lets create a WEB-INF folder.
- Instead of creating web.xml file from scratch, lets copy one from examples provided with tomcat installation. Navigate to “TOMCAT_HOME\webapps\examples\WEB-INF” and copy web.xml file. Now paste file under “project\resources\WEB-INF\”.
3) Edit web.xml file
          - Double click on the new web.xml file we pasted.
          - Edit it, so it looks like the following:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

    <description>
      Test Tomcat
    </description>
   
    <display-name>Tomcat Test</display-name>
   
    <filter>
        <filter-name>Time Filter</filter-name>
        <filter-class>com.test.tomcat.filters.TimeFilter</filter-class>
    </filter>

    <listener>
        <listener-class>com.test.tomcat.listeners.MainListener</listener-class>
    </listener>

    <!-- Define servlets that are included in the example application -->
    <servlet>
      <servlet-name>TomcatTestServlet</servlet-name>
      <servlet-class>com.test.tomcat.servlets.TomcatTestServlet</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>TomcatTestServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

4) Create packages and classes.
- under project right click on src folder and choose New à package. In the “Name” filed type: “com.test.tomcat.filters”. Press finish. Do the same for “com.test.tomcat.listeners”, “com.test.tomcat.servlets”.
- Now right click on “com.test.tomcat.servlets” package, new à Class. Type in “TomcatTestServlet”. Click finish. Now do same for all other corresponding packages, refer to web.xml above.

5) Lets code finally!
          - Open servlet class and make it extend HTTPServlet. Then Click on Source above and choose Override/Implement methods. Choose doGet and doPost, press ok. Now paste in doGet, so it look like this:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
         
          resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

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

         String title = "Testing Tomcat";

         out.println("<title>" + title + "</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");

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

Save your file. Now make sure your listener looks like this:

public class MainListener implements ServletContextListener {

     @Override
     public void contextDestroyed(ServletContextEvent ctx) {
          System.out.println("Do nothing");
         
     }

     @Override
     public void contextInitialized(ServletContextEvent ctx) {
         
          System.out.println("Do nothing");
         
     }

}
Save the file. Now here is the Filter

public class TimeFilter implements Filter {

     @Override
     public void destroy() {
          // TODO Auto-generated method stub
         
     }

     @Override
     public void doFilter(ServletRequest arg0, ServletResponse arg1,
              FilterChain arg2) throws IOException, ServletException {
          // TODO Auto-generated method stub
         
     }

     @Override
     public void init(FilterConfig arg0) throws ServletException {
          // TODO Auto-generated method stub
         
     }

}
6) Create build file. We need to create the build file, which will compile and package the whole application, then move it to “TOMCAT_HOME\webapps” folder.
- right click on project name, new à File, in “File Name” type “build.xml”. Click Finish. A new file with a symbol of ant should appear under the project. Double click it. Here are the contents

<?xml version="1.0" encoding="UTF-8"?>
<!-- ======================================================================
     Nov 4, 2010 3:21:59 PM                                                       

     Test Tomcat   
   
                   
     iakoupov                                                               
     ====================================================================== -->
<project name="Test Tomcat" default="deploy" basedir=".">
    <description>
            Tomcat Test
    </description>

      <path id="lib">
                  <fileset dir="lib" includes="*.jar"/>
      </path>
     
    <!-- =================================
          target: default             
         ================================= -->
    <target name="deploy" depends="" description="compile, package and deploy application">
       
      <!-- compile -->
      <mkdir dir="./resources/WEB-INF/classes/"/>
     
      <javac classpathref="lib" srcdir="src" destdir="./resources/WEB-INF/classes/"/>
     
      <!-- deploy -->
     
      <mkdir dir="C:/apache-tomcat-6.0.29/webapps/tomcatTest" />
     
   
      <copy todir="C:/apache-tomcat-6.0.29/webapps/tomcatTest/">
            <fileset  dir="./resources"/>
      </copy>
     
      <delete dir="./resources/WEB-INF/classes/"/>
     
     
    </target>


</project>

Now right click on the build file, choose Run As à Ant Build. Then launch Tomcat and point to http://localhost:8080/tomcatTest/. You should see a white screen and title “Testing Tomcat”.

Congratulations you have created a web application!       

No comments:

Post a Comment