Sample Java Servlet
In this example we are going to see how to create a simple Java Servlet. As Oracle states in it’s site:
Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. This leaves you free to select a “best of breed” strategy for your servers, platforms, and tools.
Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls and receive all the benefits of the mature Java language, including portability, performance, reusability, and crash protection.
Today servlets are a popular choice for building interactive Web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.
You might want to check out the latest information on JavaServer Pages (JSP) technology.
package com.javacodegeeks.snippets.enterprise; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SampleJavaServlet extends HttpServlet { private static final long serialVersionUID = -2128122335811219481L; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>JCG Snippets</title>"); out.println("</head>"); out.println("<body>"); out.println("Hello JCG Snippets @ " + new Date()); out.println("</body>"); out.println("</html>"); out.close(); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>JCG Snippets Web Project</display-name> <servlet> <servlet-name>JCG Snippets Application</servlet-name> <servlet-class>com.javacodegeeks.snippets.enterprise.SampleJavaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JCG Snippets Application</servlet-name> <url-pattern>/jcgservlet</url-pattern> </servlet-mapping> </web-app>
URL:
http://myhost:8080/jcgsnippets/jcgservlet
Output:
Hello JCG Snippets @ Wed Nov 16 18:58:27 EET 2011
This was a Sample Java Servlet.