2017-12-27 4 views
0

세션에 따라 (모바일 장치 또는 웹 브라우저를 통해) HttpServletRequest 객체를 인수로 사용하지 않는 함수를 만듭니다. 모바일 장치라면 위도와 경도를 사용하거나 웹 브라우저에서 IP 주소를 가져올 수 있기를 원합니다. 이것을 달성 할 수있는 방법이 있습니까? 내가 본 모든 예제는 HttpServletRequest를 인수로 사용합니다.HttpServletRequest를 인수로 전달하지 않고 IP 주소를 가져 오는 함수를 작성하는 방법이 있습니까?

가능한 경우 을 달성하고자하는 예입니다..

public String getLocation(Session session) { 
    switch(session.getLocation()) { 
     case Mobile: 
      System.out.printf("Latitude is %s and Longitude is %s\n", session.getLatitude(), session.getLongitude()); 
      break; 
     case Web: 
      HttpServletRequest request; 
      String ipAddress = request.getRemoteAddr(); 
      System.out.printf("The IP Adress is %s", ipAddress); 
      break; 
     default: 
      System.out.print("Error\n"); 
      break; 
    } 
} 
+0

'Session' 어떤 유형

public class RequestIPSavingFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (req instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) req; final String ipAddress = request.getRemoteAddr(); Accumulator accumulator = (Accumulator) request.getSession().getAttribute("accumulator"); if (accumulator == null) { accumulator = new Accumulator(); request.getSession().setAttribute("accumulator", accumulator); } accumulator.putIpAddress(ipAddress); } chain.doFilter(req, resp); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } } 

나중에 세션 처리 코드에서, 당신은

Accumulator accumulator = (Accumulator) request.getSession().getAttribute("accumulator"); 

및 사용을 수행

어떻게 필터를 구현하는 방법? – Mureinik

+0

세션은 사용자 세션 (이름, ID 번호, 브라우저 또는 모바일 등을 통해 로그온 한 사용자)에 대한 정보가있는 구성된 클래스입니다. 이것은 내가 성취하고자하는 것의 예일뿐입니다. @Mureinik @ – MkIeKuE

답변

0

IP 주소는 요청의 속성입니다. 세션은 해당 세션을 구성하는 많은 요청에 해당 할 수 있으며 다른 IP 주소에서 올 수 있습니다. 따라서 어떤 '표준'방식으로 Session에서 유일한 IP 주소를 도출하는 것은 불가능합니다.

하지만 할 수있는 일은 요청에서 세션까지의 IP 주소를 필터에 저장하는 것입니다. 예를 들어, 각 요청은 IP 주소를 세션 속성에 쓸 수 있으므로 언제든지 해당 세션의 마지막 요청 IP 주소에 액세스 할 수 있습니다. 또는 일부 Accumulator을 구현하여 세션에 저장하고 요청의 IP 주소를 Accumulator에 입력하면 일부 로직이 구현됩니다 ('가장 인기있는'IP 주소 선택 또는 다른 작업 수행). 그것은 당신에게 달려 있습니다. accumulator.getBestIpAddress()

관련 문제