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()
- 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.