Java Servlet Example 3

3. Develop a servlet that displays the number of visits on the servlet. Also display the client’s hostname and IP address, as shown in Figure. Use an instance variable to store count. When the servlet is created for the first time, the count is 0. count is incremented every time the servlet’s doGet method is invoked. When the Web server stops, the count is lost.

getRemoteHost()

getRemoteAddr()

Screen Shot 2018 03 09 at 3.56.54 PM - Java Servlet Example 3

  • VisitorServlet.java (put it in the “src” folder)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/VisitorServlet") public class GreetingServlet extends HttpServlet {
static int count = 0;     
protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
response.setContentType("text/html");         
PrintWriter out = response.getWriter();         
// client's IP address         
String remoteAddr = request.getRemoteAddr();         
// client's hostname         
String remoteHost = request.getRemoteHost();         
if (count == 0){             
out.print("<h3>");             
out.print("Welcome to the fist Time </h3>");             
count++;         
} else {            
 out.print("<h3>You have visited " + count + " times");         
    count++;             
out.print("</h3>");      
   }         
out.println("Host name: ");         
out.print(remoteAddr);       
  out.println("<br>");         
out.println("IP address:");         
out.print(remoteHost);        
 out.close();    
 } }
  • 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”.) 

      Note: This step is not mandatory. You may choose not to do it. And the program will still run. 

<?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>VisitorServlet</servlet-name> 
      <servlet-class>VisitorServlet</servlet-class>  
  </servlet> 
<!--   Servlet Mappings   --> 
   <servlet-mapping> 
      <servlet-name>VisitorServlet</servlet-name> 
       <url-pattern>/VisitorServlet</url-pattern>  
  </servlet-mapping> 
</web-app>  

Note: To run this program, type inlocalhost:8080/VisitorServlet the browser URL. Click here if you don’t know how to set up a servlet project in NetBeans.

 

 

Java Servlet Example 2

HTML Form

Screen Shot 2018 03 09 at 4.00.55 PM - Java Servlet Example 2 Screen Shot 2018 03 09 at 4.01.09 PM - Java Servlet Example 2

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

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Calculator</title>
</head>
<body bgcolor="aqua">

<form method="post" action="GreetingServlet">


  <h3 style="text_align:center;">Choose an operation:
    <input type="radio" name="r1" value="add" />addition
    <input type="radio" name="r2" value="sub" />subtraction
    <input type="radio" name="r3" value="mul" />multiplication
    <input type="radio" name="r4" value="div" />division
  </h3>

  </label>
  <label>Choose 1<sup>st</sup> number:</label>
  <input type="text" name="n1" />
  <br>
  <label>Choose 2<sup>nd</sup> number:</label>
  <input type="text" name="n2" />
  <br>
  <label>
      <input type="submit" value="Submit" style="background-color: hotpink">
  </label>

</form>
</body>
</html>

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

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/FormServlet")
public class GreetingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try
        {
            response.setContentType("text/html");
            PrintWriter out= response.getWriter();
            out.println("<body style='background-color:black;color:yellow;'>");
            out.println("<h3 style='color:red;'>Output of your inputs </h3>");
            int a1= Integer.parseInt(request.getParameter("n1"));
            int a2= Integer.parseInt(request.getParameter("n2"));
            if(request.getParameter("r1")!=null)
            {
                out.println("<p>Addition</p>"+(a1+a2));
            }
            if(request.getParameter("r2")!=null)
            {
                out.println("<p>Subtraction</p>"+(a1-a2));
            }
            if(request.getParameter("r3")!=null)
            {
                out.println("<p>Multiplication</p>"+(a1*a2));
            }if(request.getParameter("r1")!=null)
        {
            out.println("<p>Division</p>"+(a1/a2));
        }
        }
        catch(Exception e)
        {
            System.out.println("error" + e.getMessage());

        }
    }
}

Note: To run this program type: localhost:8080 in the browser URL. 

Click here if you don’t don’t how to set up a NetBeans servlet project. 

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: