웹스토어 필터(Filter) 적용 로그 만들기
웹스토어에 사용할 로그파일 만들기
웹스토어 필터 콘솔에 출력하는 예제
LogFilter.java
package kr.gov.filter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
public class LogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("webStroe 초기화");
}
public String getURLPath(ServletRequest request) {
HttpServletRequest hRequest = null;
String currentPath = "";
String queryString = "";
if(request instanceof HttpServletRequest) {
hRequest = (HttpServletRequest)request; //다운캐스팅
currentPath = hRequest.getRequestURI();
// post, get에 따라서 달라져서 분리 해줌.
queryString = (queryString == null) ? "" : "?" + hRequest.getQueryString();
}
return currentPath + queryString;
}
public String getCurrentTime() {
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sFormat.format(new Date());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("접속한 클라이언트 IP : " + request.getRemoteAddr());
long start = System.currentTimeMillis();
System.out.println("접근한 URL 경로 : " + this.getURLPath(request));
System.out.println("요청 처리 시작 시각 : " + this.getCurrentTime());
chain.doFilter(request, response);
long end = System.currentTimeMillis();
System.out.println("요청 처리 종료 시각 : " + this.getCurrentTime());
System.out.println("요청 처리 소요 시각 : " + (end - start) + "ms");
System.out.println("======================================================");
}
@Override
public void destroy() {
System.out.println("webStroe 필터해제");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>WebStore</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 404에러가 발생하면 자동으로 exceptionNoPage.jsp 페이지 보여주게 된다. -->
<error-page>
<error-code>404</error-code>
<location>/exceptionNoPage.jsp</location>
</error-page>
<!-- 시큐리티 역할 추가 -->
<security-role>
<description>관리자</description>
<role-name>admin</role-name>
</security-role>
<!-- 제약조건 추가 -->
<security-constraint>
<display-name>WebStore Security</display-name>
<web-resource-collection> <!-- 웹자원 제약조건 설정 -->
<web-resource-name>WebStore</web-resource-name> <!-- 프로젝트 이름 -->
<description></description>
<url-pattern>/addProduct.jsp</url-pattern> <!-- 상품등록 페이지 -->
</web-resource-collection>
<auth-constraint> <!-- 권한 제약조건 설정 -->
<description>권한 관리자명</description>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config> <!-- 시큐리티 인증 설정 -->
<auth-method>FORM</auth-method> <!-- 폼 인증처리 방식 -->
<form-login-config>
<form-login-page>/login.jsp</form-login-page> <!-- 로그인이 성공할 경우 -->
<form-error-page>/login_failed.jsp</form-error-page> <!-- 로그인이 실패할 경우 -->
</form-login-config>
</login-config>
<!-- 필터 적용 -->
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>kr.gov.filter.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
콘솔창 출력화면
웹스토어 로그 필터 적용 예제
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>WebStore</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 404에러가 발생하면 자동으로 exceptionNoPage.jsp 페이지 보여주게 된다. -->
<error-page>
<error-code>404</error-code>
<location>/exceptionNoPage.jsp</location>
</error-page>
<!-- 시큐리티 역할 추가 -->
<security-role>
<description>관리자</description>
<role-name>admin</role-name>
</security-role>
<!-- 제약조건 추가 -->
<security-constraint>
<display-name>WebStore Security</display-name>
<web-resource-collection> <!-- 웹자원 제약조건 설정 -->
<web-resource-name>WebStore</web-resource-name> <!-- 프로젝트 이름 -->
<description></description>
<url-pattern>/addProduct.jsp</url-pattern> <!-- 상품등록 페이지 -->
</web-resource-collection>
<auth-constraint> <!-- 권한 제약조건 설정 -->
<description>권한 관리자명</description>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config> <!-- 시큐리티 인증 설정 -->
<auth-method>FORM</auth-method> <!-- 폼 인증처리 방식 -->
<form-login-config>
<form-login-page>/login.jsp</form-login-page> <!-- 로그인이 성공할 경우 -->
<form-error-page>/login_failed.jsp</form-error-page> <!-- 로그인이 실패할 경우 -->
</form-login-config>
</login-config>
<!-- 필터 적용 -->
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>kr.gov.filter.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 필터(파일기록) 적용 -->
<filter>
<filter-name>LogFileFilter</filter-name>
<filter-class>kr.gov.filter.LogFileFilter</filter-class>
<init-param>
<param-name>filename</param-name> <!-- 로그 기록을 남길 파일 경로 지정 -->
<param-value>C:\\workspace-jsp\\log\\webstore.log</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFileFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
LogFileFilter.java
package kr.gov.filter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
public class LogFileFilter implements Filter {
PrintWriter writer = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("LogFileFilter 초기화");
String filename = filterConfig.getInitParameter("filename");
if(filename == null) {
throw new ServletException("로고 파일의 이름을 찾을수 없습니다.");
}
try {
writer = new PrintWriter(new FileWriter(filename, true), true);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getURLPath(ServletRequest request) {
HttpServletRequest hRequest = null;
String currentPath = "";
String queryString = "";
if(request instanceof HttpServletRequest) {
hRequest = (HttpServletRequest)request; //다운캐스팅
currentPath = hRequest.getRequestURI();
// post, get에 따라서 달라져서 분리 해줌.
queryString = (queryString == null) ? "" : "?" + hRequest.getQueryString();
}
return currentPath + queryString;
}
public String getCurrentTime() {
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sFormat.format(new Date());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
writer.println("접속한 클라이언트 IP : " + request.getRemoteAddr());
long start = System.currentTimeMillis();
writer.println("접근한 URL 경로 : " + this.getURLPath(request));
writer.println("요청 처리 시작 시각 : " + this.getCurrentTime());
chain.doFilter(request, response);
long end = System.currentTimeMillis();
writer.println("요청 처리 종료 시각 : " + this.getCurrentTime());
writer.println("요청 처리 소요 시각 : " + (end - start) + "ms");
writer.println("======================================================");
}
@Override
public void destroy() {
System.out.println("LogFileFilter 필터 해제");
writer.close();
}
}
welcom.jsp 실행
addProduct.jsp 실행 로그인 로그아웃 로그