본문 바로가기

Programming/Servlet & JSP

servlet에서 ip체크, 구분하여 화면 보여주기

IpCheck.java

package com;

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("/IpCheck")
public class IpCheck extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
      
        // http://ip주소:설정한포트번호/서블렛패키지명/서블렛클래스명
        
		String ip = request.getRemoteAddr();
        // 접속하는 IP 콘솔로 출력하기
		System.out.println(ip);

		String str = "";
		if (ip.equals("구분가능한 ip주소1")) {
			str = "ip주소1 사용자님~~!! ";
		} else if (ip.equals("구분가능한 ip주소2")) {
			str = "ip주소2 사용자님~~!! ";
		} else {
			str = "고객님";
		}
		response.setCharacterEncoding("EUC-KR");
        // Encoding은 response writer 위에서 선언해주어야함
		PrintWriter out = response.getWriter();
		out.print("<html>");
		out.print("<body>");
		out.print("환영합니다," + str);
		out.print("<img src='Pikachu.png'>");
        // Servlet은 실행위치가 WebContent이므로 보여주고 싶은 이미지를 WebContent로 저장
		out.print("</body>");
		out.print("</html>");
	}

}

 

cmd > ipconfig 
local host 대신 IPv4 주소 입력해도 들어온다. 
http://localhost:8082/Servlet1/IpCheck 
http://ipAddress:8082/Servlet1/IpCheck (공유하면 들어온다.)