본문 바로가기

BackEnd/JSP

[JSP 웹 프로그래밍] 필터 2 (web.xml 파일의 필터 구성)

728x90
반응형

[JSP 웹 프로그래밍] 필터 1 (Filter 인터페이스) (tistory.com)

 

[JSP 웹 프로그래밍] 필터 1 (Filter 인터페이스)

1. 필터(filter) ▷ 클라이언트와 서버 사이에서 request와 response 객체를 먼저 받아 사전/사후 작업 등 공통적으로 필요한 부분을 처리하는 것 ▷ 클라이언트의 요청이 웹 서버의 서블릿, JSP, HTML 페

bobo12.tistory.com

 

3. web.xml 파일에 필터를 설정
   ▷ 필터를 사용하려면 어떤 필터가 어떤 리소스에 대해 적용되는지 JSP 컨테이너에 알려주어야 함
   ▷ <filter>와 <filter-mapping> 요소를 사용
   ▷ web.xml 파일에 여러 개의 필터가 설정되어 있으면 선언된 순서대로 실행

 

◎ <filter> 요소
   ▷ <filter> 요소는 웹 애플리케이션에서 자바 필터와 매개변수를 설정하는 데 사용

 

◎ <init-param> 요소
   ▷ 설정된 매개변수와 값을 자바 또는 JSP 코드에서 접근


위의 예에서 <init-param> 요소에 설정된 매개변수와 값을 자바 클래스에서 접근하려면 다음과 같이 작성

 

◎ <filter-mapping> 요소
   ▷ 특정 리소스에 대해 어떤 필터를 사용할지 설정하는 데 사용

 

◎ 폼 페이지에서 전송된 요청 파라미터를 필터로 처리하는 예제

1. AuthenFilter.java
package ch12.filter;

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

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class AuthenFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException{
		System.out.println("filter01 초기화");
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException{
		System.out.println("filter01.jsp 수행...");
		String name = request.getParameter("name");
		
		if(name == null || name.equals("")){
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter writer = response.getWriter();
			String message = "입력된 name 값은 null입니다.";
			writer.println(message);
			return;
		}
		filterChain.doFilter(request, response);
	}
	
	@Override
	public void destroy() {
		System.out.println("filter01 해제...");
	}
}​


2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
	<security-role>
		<role-name>role1</role-name>
	</security-role>
	<security-constraint>
		<web-resource-collection>
			<web-resource-name>JSP0307</web-resource-name>
			<url-pattern>/ch10/security02.jsp</url-pattern>
			<http-method>GET</http-method>
		</web-resource-collection>
		<auth-constraint>
			<description></description>
			<role-name>role1</role-name>
		</auth-constraint>
	</security-constraint>
	<login-config>
		<auth-method>FORM</auth-method>
		<form-login-config>
			<form-login-page>/ch10/login.jsp</form-login-page>
			<form-error-page>/ch10/login_failed.jsp</form-error-page>
		</form-login-config>
	</login-config>
	<error-page>
		<exception-type>java.lang.Exception</exception-type>
		<location>/ch11/exceptionType_error.jsp</location>
	</error-page>

 	<filter>
 		<filter-name>Filter01</filter-name>
 		<filter-class>ch12.filter.AuthenFilter</filter-class>
 	</filter>
 	<filter-mapping>
 		<filter-name>Filter01</filter-name>
 		<url-pattern>/ch12/filter01_process.jsp</url-pattern>
 	</filter-mapping>
	<filter-mapping>
		<filter-name>Filter01</filter-name>
		<url-pattern>/ch12/filter01_process.jsp</url-pattern>
	</filter-mapping>
</web-app>​


3. filter01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Filter</title>
</head>
<body>
	<form method="post" action="filter01_process.jsp">
		<p> 이름 : <input type="text" name="name">
			<input type="submit" value="전송">
	</form>
</body>
</html>​


4. filter01_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Filter</title>
</head>
<body>
	<%
		String name = request.getParameter("name");
	%>
	<p> 입력된 name 값 : <%= name %>
</body>
</html>​


아무것도 입력하지 않으면 '입력된 name 값은 null입니다.'라고 출력됩니다.

 

 

◎ 필터 처리로 매개변수와 값을 전달받아 로그인 인증 처리하는 예제

1. InitParamFilter.java
package ch12.filter;

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

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class InitParamFilter implements Filter {
	private FilterConfig filterConfig = null;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException{
		System.out.println("filter02 초기화...");
		this.filterConfig = filterConfig;
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException{
		System.out.println("filter02.jsp 수행...");
		
		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");
		
		String param1 = filterConfig.getInitParameter("param1");
		String param2 = filterConfig.getInitParameter("param2");
		
		String message;
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter writer = response.getWriter();
		
		if(id.equals(param1) && passwd.equals(param2)){
			message = "로그인 성공했습니다.";
		} else {
			message = "로그인 실패했습니다.";			
		}
		
		writer.println(message);
		
		filterChain.doFilter(request, response);
	}
	
	@Override
	public void destroy() {
		System.out.println("filter02 해제...");
	}
}​


2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
...(생략)...
	<filter>
		<filter-name>Filter02</filter-name>
		<filter-class>ch12.filter.InitParamFilter</filter-class>
		<init-param>
			<param-name>param1</param-name>
			<param-value>admin</param-value>
		</init-param>
		<init-param>
			<param-name>param2</param-name>
			<param-value>1234</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>Filter02</filter-name>
		<url-pattern>/ch12/filter02_process.jsp</url-pattern>
	</filter-mapping>
</web-app>​


3. filter02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Filter</title>
</head>
<body>
	<form method="post" action="filter02_process.jsp">
		<p> 아이디 : <input type="text" name="id">
		<p> 비밀번호 : <input type="text" name="passwd">
		<p> <input type="submit" value="전송">
	</form>
</body>
</html>​

 



4. filter02_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Filter</title>
</head>
<body>
	<%
		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");	
	%>
	<p> 입력된 id 값 : <%= id %>
	<p> 입력된 pw 값 : <%= passwd %>
</body>
</html>​


◎ 로그인 성공/실패 화면

 

 

◎ 이전 예제의 웹 페이지를 이용해 필터로 로그 기록하기

1. LogFileFilter.java
package ch12.filter;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class LogFileFilter implements Filter {
	
	PrintWriter writer;
		
	@Override
	public void init(FilterConfig filterConfig) throws ServletException{
		String filename = filterConfig.getInitParameter("filename");
		if(filename==null) throw new ServletException("로그 파일의 이름을 찾을 수 없습니다.");
		try {
			writer = new PrintWriter(new FileWriter(filename, true), true);
		} catch(IOException e) {
			throw new ServletException("로그 파일을 열 수 없습니다.");
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException{
		
		writer.printf("현재 일시 : %s %n", getCurrentTime());
		String clientAddr = request.getRemoteAddr();
		writer.printf("클라이언트 주소 : %s %n", clientAddr);
		
		filterChain.doFilter(request, response);
		
		String contentType = response.getContentType();
		writer.printf("문서의 콘텐츠 유형 : %s %n", contentType);
		writer.printf("---------------------------------");
	}
	
	@Override
	public void destroy() {
		writer.close();
	}
	
	private String getCurrentTime() {
		DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		return formatter.format(calendar.getTime());
	}
}​


2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
...(생략)...
	<filter>
		<filter-name>Filter02_2</filter-name>
		<filter-class>ch12.filter.LogFileFilter</filter-class>
		<init-param>
			<param-name>filename</param-name>
			<param-value>c:\\logs\\monitor.log</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>Filter02_2</filter-name>
		<url-pattern>/ch12/filter02_process.jsp</url-pattern>
	</filter-mapping>
</web-app>​


로그인 창으로 전송하면 현재 정보에 대한 monitor.log 파일이 만들어집니다.

 

web.xml에 필터 부분을 작성하면 현재 입력한 값과 비교해 값들을 걸러주고 필요한 값들을 출력할 수 있도록 만듭니다.

 

필터를 이용하면 필요한 부분을 출력할 수 있는데 이것은 로그인할 때 많이 사용할 것 같네요!!

 

많은 분들의 피드백은 언제나 환영합니다!  많은 댓글 부탁드려요~~

 

728x90
반응형