Hello All, this time I’m going to give you a brief introduction on how to set-up and run a simple servlet. A long due part of my first introductoral tutorial (sorry for that).
A little Background Information:
- “Remind me, What was a Servlet again?”: Servlets were introduced to allow to combine HTML pages with Java-Code and thus give them a dynamic character.
- “Combine?”: Yes combine, i.e. to include the result of java-code into a HTML page.
Creating the foundation for your Servlet’s cosy little home:
Before you can start off with your first Servlet, you need to ensure that you are running a framework and that you have the right folder structure in your project.
- Set-Up a Tomcat/JBoss (For detailed information on how to do so see Setting up Tomcat or JBoss)
- Create an appropriate (project) File-Directory-Structure as follows:
- <project-folder> (This can have any name, depending on what you call your project)
- WEB-INF (!This folder is mandatory! – It also has the nice property, to “hide” what is inside of it and its sub-folder structures*)
- lib (should you use any external libraries, that need to be accessible by your code, then store them here)
- classes (here the “.class”es of your Servlet and maybe additional JavaBeans should be stored)
- <_anything-else_>, as I already mentioned above, you can store any other folders and files within the WEB-INF folder (even your source files (which you shouldnt for safety reasons*)) and it would not be visible to an external accessee.
Example:
- HelloWorldServlet
- WEB-INF
- web.xml
- classes
- beans
- HelloWorldBean.class (NOTE: in our minimal example (Implementation) we won’t include the HelloWorldBean for simplicity)
- servlets
- HelloWorldServlet.class
- sources (*)
- beans
- HelloWorldBean.java (NOTE: in our minimal example (Implementation) we won’t include the HelloWorldBean for simplicity)
- servlets
- HelloWorldServlet.java
Write your first amazing Servlet:
Now You can write your first Servlet, which I call (as ingeniously indicated above) HelloWorldServlet.java and it looks like this:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Set the content type of the response document.
response.setContentType("text/html;charset=ISO-8859-1");
// Retrieve the printwriter to write to the response document.
PrintWriter out = response.getWriter();
// Output / Respond an html document with a greeting and a date.
out.println("<html><body>");
out.println(" Hello World! ");
out.println(" It's about time: " + new Date());
out.println("</html></body>");
}
}
Compile your first amazing Servlet:
I suggest doing so using an ANT-script, as follows:
<project name="helloworldservlet" default="compile" basedir=".">
<!-- Set global properties for this build -->
<property name="src" location="sources"/>
<property name="build" location="classes"/>
<!-- Replace this with your Tomcat path. -->
<property name="tomcat" location="C:\Program Files\Tomcat_7.0.2"/>
<!-- Define the classpath. -->
<path id="classpath">
<!-- This is the jar for the Servlet-api -->
<fileset dir="${tomcat}/lib">
<include name="**/servlet-api.jar"/>
</fileset>
</path>
<!-- Create the build directory structure used by compile -->
<target name="init">
<mkdir dir="${build}"/>
</target>
<!-- The depends attribute indicates which target has to be executed before
this one. -->
<target name="compile" depends="init" >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}">
<classpath refid="classpath"/>
</javac>
</target>
<!-- Delete the ${build} and ${dist} directory trees -->
<target name="clean">
<delete dir="${build}"/>
</target>
</project>
Give your application the finishing touch:
- Create a web.xml file
- “What for?”: Basically the web.xml file – also called the Web Deployment Descriptor – is the configuration for your particular project.
- “Oh, I see and what does it look like?”
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Eine erste Webanwendung</display-name> <servlet> <!-- generally: a unique name for your servlet --> <servlet-name>HelloWorldServlet</servlet-name> <!-- generally: the path to your servlet (from classes folder)) with subfolders separated by "."s --> <servlet-class> servlets.HelloWorldServlet </servlet-class> </servlet> <servlet-mapping> <!-- generally: the unique name of the servlet you are referring to --> <servlet-name>HelloWorldServlet</servlet-name> <!-- The path to this Servlet relative to the project folder. Or more generally: the Servlet you want to be associated with the given pattern whereas a "*" can function as a wildcard (i.e. a placeholder for any kind of description).--> <url-pattern>/HelloWorldServlet</url-pattern> </servlet-mapping> </web-app>
Look what you’ve done!
- “Load” your application. It is up to you in which order you want to do the following two actions:
- A. Start either one of the servers:
- For Tomcat that is (01.10.2010): $TOMCAT_HOME_FOLDER$/bin/startup.bat
- For JBossthat is (01.10.2010): $JBOSS_HOME_FOLDER$/bin/run.bat
- B. Move the File-Directory to the right spot:
- “And where might that be?”: It depends:
- For Tomcat that is (01.10.2010): $TOMCAT_HOME_FOLDER$/webapps/
- For JBossthat is (01.10.2010): $JBOSS_HOME_FOLDER$/server/default/deploy/
- NOTE: The $ annotated parts represent variables, please insert your respective (here) folder or (generally) value there.
- “And where might that be?”: It depends:
- A. Start either one of the servers:
- Finally, access the HelloWorldServlet page: By typing the following URL: http://localhost:8080/$project_name$/HelloWorldServlet (in our example: http://localhost:8080/HelloWorldServlet/HelloWorldServlet) into your internet browser’s address bar.
Congratulations you are looking at your first Servlet :)!
NOTE: More about Servlets can be read in Thomas Stark’s Java EE 5.
* Please NOTE: Even though WEB-INF is secured against external access within the Container, it is still accessible by the underlying filesystem! So DO NOT store your source files there!
Best Regards,
David