Java Servlet Example 1

Write a servlet to display a table that shows ODD numbers and EVEN numbers from number 1 to 10, as shown in the figure below. 

Screen Shot 2018 03 09 at 4.02.12 PM - Java Servlet Example 1

 

  • EvenOddServlet.java (put it in the “src” folder) 

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class EvenOddServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws 
ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        // Send the message
        pw.println("<table border='1'>");
        pw.println("<tr>");
        pw.println("<th style='background-color:red;'> Even </th>");
        for (int i = 1; i <= 10; ++i) {
            if (i % 2 == 0) {
                pw.println("<td>" + i + "</td>");
            }
        }
        pw.println("</tr>");
        pw.println("<tr>");
        pw.println("<th style='background-color:red;'> Odd </th>");
        for (int i = 1; i <= 10; ++i) {
            if (i % 2 != 0) {
                pw.println("<td>" + i + "</td>");
            }
        }
        pw.println("</tr>");
        pw.println("<table>");
    }
}

  • index.jsp (put it in the “web” folder) 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>

  </body>
</html>

  • web.xml (put it in the “WEB-INF” folder which resides inside the “web”) 

<?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>myweb</display-name>

    <!-- Servlet Definitions  -->
   <servlet>
      <servlet-name>EvenOddServlet</servlet-name>
      <servlet-class>EvenOddServlet</servlet-class>
   </servlet>
<!--   Servlet Mappings   -->
   <servlet-mapping>
      <servlet-name>EvenOddServlet</servlet-name>
       <url-pattern>/EvenOddServlet</url-pattern>
   </servlet-mapping>
 </web-app>

 Note: To run this go to your browser and type: localhost:8080/EvenOddServlet

If you don’t know how to set up a servlet project in NetBeans, you may use this video as a reference: