Simple Java Servlet Example

Introduction

Servlets are Java classes that service HTTP requests. Servlet programs are embedded in web browsers. Below are examples of a few Servlet Programs.

Example 1

The following program is a Servlet that will print out a text on a web browser. For this example, we will choose the following text: “This was a Java Servlet Example”.

Java Code

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class SampleProg extends HttpServlet
{
private String message;

public void init() throws ServletException
{
message = " This was a Java Servlet Example ";
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");

// Here the text is printed out using the <h1/> header type
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy()
{
//An empty method means no action is performed here
}
}

 

Web.xml file

<servlet>
<servlet-name> SampleProg </servlet-name>
<servlet-class> SampleProg </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> SampleProg </servlet-name>
<url-pattern> /SampleProg </url-pattern>
</servlet-mapping>

 

 

Example 2

This is also an example of a servlet that will print out a text as output using a web browser. Let us take the text “Hello World” in this case.

Java Code

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("Hello World");
pw.println("</body></html>");
pw.close();//closing the stream
}
}

Web.xml file

<web-app>

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

<servlet-mapping>
<servlet-name> User </servlet-name>
<url-pattern> /welcome </url-pattern>
</servlet-mapping>
</web-app>

 

OUTPUT

To get an output, open your web browser and write in the following format: http://hostname:portno/contextroot/urlpatternofservlet

Example: http://localhost:9999/demo/welcome.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.