09. com/mvc/upgrade/common/filter/LogFilter (impl javax.servlet.Filter)
com.mvc.upgrade.common.filter패키지를 만들고 LogFilter클래스를 만들겠습니다.
LogFilter클래스를 만들때 javax.servlet.Filter 인터페이스를 상속받아주세요!
package com.mvc.upgrade.common.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogFilter implements Filter {
private Logger logger = LoggerFactory.getLogger(LogFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String remoteAddr = req.getRemoteAddr();
String uri = req.getRequestURI();
String url = req.getRequestURL().toString();
String queryString = req.getQueryString();
String referer = req.getHeader("referer");
String agent = req.getHeader("User-Agent");
StringBuffer sb = new StringBuffer();
sb.append("\n* remoteAddr : " + remoteAddr)
.append("\n* uri : " + uri)
.append("\n* url : " + url)
.append("\n* queryString : " + queryString)
.append("\n* referer : " + referer)
.append("\n* agent : " + agent)
.append("\n");
logger.info("\nLOG Filter" + sb);
chain.doFilter(req, response);
}
@Override
public void destroy() {
}
}
javax.servlet.Filter인터페이스를 상속받으면 init(), doFilter(), destory() 3개의 메소드가 오버라이드 됩니다.
init()은 필터가 만들어질때 실행되고 destory()는 필터가 종료될때 실행되는 메소드인데 잠시 그냥 넘어가겠습니다.
필드로 org.slf4j.Logger를 import하고 객체를 만들어주세요.
10. web.xml : filter
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://Java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<!-- The definition of the Root Spring COntainer shared by all Servlet and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Creates the Spring Container shared by all Servelts and Filters -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Processes application requests -->
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 서버 밖에서 존재. 요청되는거, 응답되는거 받는 역할 -->
<filter>
<filter-name>encodingFilter</filter-name>
<!-- 패키지 : org.spirngframework.web.filter -->
<!-- 클래스 : CharacterEncoding -->
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>logFilter</filter-name>
<filter-class>com.mvc.upgrade.common.filter.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>logFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
이만큼 추가됩니다.
이제 프로젝트를 실행시켜보면 콘솔창에 찍히는 내용이 있을겁니다.
String remoteAddr = req.getRemoteAddr();
ip주소 ( IPv6 형태 ) -> IPv4 형태로 나오게 하려면 localhost 대신 127.0.0.1로 요청하면됨
String uri = req.getRequestURI();
http 요청 url 중에 queryString까지 반환. (context path) / URI = URL + URN (어떤 경로에 누가 있는지?)
String url = req.getRequestURL().toString();
quertString을 제외한 경로(서블릿 포함) - protocol + servername + protnumber + serverpath
String queryString = req.getQueryString();
quertString : 경로 뒤에 있는 요청 쿼리 문자열(K=V 형태)
String referer = req.getHeader("referer");
이전페이지의 url(getHeader : 지정한 요청 헤더값을 문자열로 반환)
String agent = req.getHeader("User-Agent");
사용자 정보(browser version, os 등)
위의 내용들을 console창에 찍어보았지만 이러한 내용들을 log파일이나 db에 저장해서 기록으로 남길수도 있습니다.
'Java 관련 > Spring Legecy' 카테고리의 다른 글
[Spring] Login / Regist(로그인 / 회원가입) (0) | 2022.04.05 |
---|---|
[Spring] 스프링MVC - AOP (0) | 2022.04.04 |
[Spring] 스프링으로 게시판만들기 (0) | 2022.04.02 |
[Spring] request, response (0) | 2022.04.01 |
[Spring] encodingFilter로 한글 설정하기 (0) | 2022.03.31 |