RestrictUserIP.java Source code

Java tutorial

Introduction

Here is the source code for RestrictUserIP.java

Source

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RestrictUserIP extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out;
        /**
         * Status code (401) indicating that the request requires HTTP
         * authentication.
         */
        if (req.getRemoteAddr().equals("142.3.28.87")) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        resp.setContentType("text/html");
        out = resp.getWriter();
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<H1>");
        out.println("Hello!");
        out.println("<BR>");
        out.println("Your IP Address: " + req.getRemoteAddr());
        out.println("</H1>");
        out.println("</body>");
        out.println("</html>");
        out.close();
    }
}