faqts : Computers : Programming : Languages : Java : Servlet

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

28 of 32 people (88%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

Java: Servlet: Create: Simple: How to create a Java servlet that displays 'Hello world'? [Tomcat v6]

Apr 22nd, 2007 10:18
Knud van Eeden,


----------------------------------------------------------------------
--- Knud van Eeden --- 21 April 2007 - 16:11 -------------------------

Java: Servlet: Create: Simple: How to create a Java servlet that 
displays 'Hello world'? [Tomcat v6]

---

Steps: Overview:

 1. Install Tomcat
    (in general a web server that can handle servlets)

 2. -Download and install Java JDK
     (or similar Java Enterprise Edition JxEE)

 3. -Create your servlet source code using your favorite texteditor

    (inside the servlet put source code to generate (=print) a HTML 
page)

--- cut here: begin --------------------------------------------------

 import java.io.*;

 import javax.servlet.*;

 import javax.servlet.http.*;

 public class HelloWorld extends HttpServlet {

  public void doGet( HttpServletRequest request, HttpServletResponse 
response )

   throws IOException, ServletException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

     out.println("<html>");

     out.println("<body>");

     out.println("<head>");

     out.println("<title>Hello World!</title>");

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

     out.println("<body>");

     out.println("<h1>Hello World!</h1>");

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

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

   }
 }

--- cut here: end ----------------------------------------------------

 4. Save this as

     HelloWorld.java

    (e.g. in the c:\temp\ directory)

 5. Compile and debug it

    1. -Run javac.exe located in your Java JDK bin directory with this 
parameters

         cd C:\Program Files\Java\jdk1.6.0_01\bin\

         javac.exe -classpath "<path to your JDK>;<path to Tomcat 
servlet-api.jar>" <your filename>

         E.g. (all on one line)

         javac.exe -classpath "C:\Program 
Files\Java\jdk1.6.0_01;C:\tomcat\apache-tomcat-6.0.10\lib\servlet-
api.jar" c:\temp\HelloWorld.java

         or more general

         javac.exe -classpath "%JAVA_HOME%;%CATALINA_HOME%\lib\servlet-
api.jar" c:\temp\HelloWorld.java

    2. -This will create a file

         HelloWorld.class

       in the same directory, when you have compiled
       successfully

    3. -Copy this file

         HelloWorld.class

        to your Tomcat class directory

        (by default in a 'classes' subfolder of the WEB-INF folder of
         the Tomcat ROOT directory)

        ===

        E.g. (all on one line)

         md "C:\tomcat\apache-tomcat-6.0.10\webapps\ROOT\WEB-
INF\classes\"

         copy c:\temp\HelloWorld.class "C:\tomcat\apache-tomcat-6.0.10
\webapps\ROOT\WEB-INF\classes\"

    4. -Backup and edit the file

         web.xml

        in the directory

         "C:\tomcat\apache-tomcat-6.0.10\webapps\ROOT\WEB-INF\web.xml"

--- cut here: begin --------------------------------------------------

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 
2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 
implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

</web-app>

--- cut here: end ----------------------------------------------------

    5. -Add the following tag to it, giving the name of your servlet

--- cut here: begin --------------------------------------------------

    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

--- cut here: end ----------------------------------------------------

    6. -Add also the following tag to it, giving the URL to your 
servlet
        (this is in general /servlet/<your servlet name>)

--- cut here: begin --------------------------------------------------

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/servlet/HelloWorld</url-pattern>
    </servlet-mapping>

--- cut here: end ----------------------------------------------------

    7. -So all together your new web.xml becomes

--- cut here: begin --------------------------------------------------

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 
2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 
implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/servlet/HelloWorld</url-pattern>
    </servlet-mapping>

</web-app>

--- cut here: end ----------------------------------------------------

 6. -*Important*
     If you save this web.xml file make sure there are no empty lines
     at the top, or your Tomcat will give a lot of (XML parse)
     errors

 7. Run this servlet file in your browser

    1. -First make sure your servlet server program (=Tomcat) is
        running (e.g. by running its startup.bat batch file in the
        Tomcat 'bin' directory)

        -Thus typing in your browser the URL

          http://localhost:8080

         should show the Tomcat home page

    2. -To test your HelloWorld.class servlet file locally on your
        computer, open your browser, and type the URL:

         http://localhost:8080/servlet/HelloWorld

        ===

        Note:

        1. -You should use forward slashes in the URL

            Thus this is OK

             http://localhost:8080/servlet/HelloWorld

            but using backward slashes is not OK
            (that will give error 'Page can not be displayed')

             http://localhost:8080\servlet\HelloWorld

        2. -In the URL, put only the name of the servlet file (e.g.
            'HelloWorld') but without the .class extension

            Thus this is OK

             http://localhost:8080/servlet/HelloWorld

            but this is not OK (will give error
            HTTP Stastus 404 'The requested resource is not available')

             http://localhost:8080/servlet/HelloWorld.class

    3. -You should see in your browser

         Hello World!

===

Tested successfully on
Microsoft Windows XP Professional (service pack 2),
running
Tomcat v6
Java JDK v1.6

===

Internet: see also:

---

Language: Computer: Java: Servlet: Link: Overview: Can you give an 
overview of links?
http://www.faqts.com/knowledge_base/view.phtml/aid/40576/fid/778

----------------------------------------------------------------------