10장. 시큐리티
1. 시큐리티 개요
2. 선언적 시큐리티 처리
3. 프로그래밍적 시큐리티 처리
11장. 예외 처리
1. 예외 처리의 개요
2. page 디렉티브 태그를 이용한 예외 처리
3. web.xml 파일을 이용한 예외 처리
4. try-catch-finally를 이용한 예외 처리
1. 예외 처리의 개요
what?
문제(오류)가 발생했을 때 처리를 중단하고 다른 처리를 하는 것(오류 처리)
2. page 디렉티브 태그를 이용한 예외 처리
2.1 errorPage 속성: 오류 페이지 호출
오류 페이지: 오류 처리 페이지
<%@ page errorPage = "오류 페이지 URL"%>
2.2 isErrorPage 속성: 오류 페이지 작성
오류 페이지에서 exception 내장 객체 사용
<%@ page isErrorPage = "true" %>
<!--Exception 객체가 생성됨-->
exception 내장 객체의 메서드
메서드 | 형식 | 설명 |
getMessage() | String | 오류 이벤트와 함께 들어오는 메시지 출력 |
toString() | String | 오류 이벤트의 toString() 호출 |
printStackTrace() | String | 오류 메시지의 발생 근원지 탐색, 단계별로 오류 출력 |
exception.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception</title>
</head>
<body>
<form action="exception_process.jsp" method="post">
<p>숫자1: <input type="text" name="num1">
<p>숫자2: <input type="text" name="num2">
<p> <input type="submit" value="나누기">
</form>
</body>
</html>
form에서 입력받은 데이터를 exception_process.jsp로 가져감
exception_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page errorPage="exception_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception</title>
</head>
<body>
<%
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
int c = a/b;
out.print(num1+" / "+num2+" = "+c);
%>
</body>
</html>
에러 발생시 exception_error.jsp에서 처리함
exception_error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isErrorPage = "true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception</title>
</head>
<body>
<p>오류가 발생하였습니다.
<p>예외: <%=exception.toString() %>
<p>getClass().getName(): <%=exception.getClass().getName() %>
<p>getMessage(): <%=exception.getMessage() %>
</body>
</html>
정수를 0으로 나눌시 오류 발생
3. web.xml 파일을 이용한 예외 처리
web.xml의 <error-page> 태그에서 오류 코드/오류 유형/오류 페이지 호출
요소 | 설명 |
<error-code> | 오류 코드 설정 |
<exception-type> | 자바 예외 유형의 정규화된 클래스 이름 설정 |
<location> | 오류 페이지의 URL 설정 |
3.1 오류 코드로 오류 페이지 호출
<web-app>
<error-page>
<error-code>404</error-code>
<location>/errorCode_404.jsp</location>
<error-page>
<web-app>
404 오류 발생시 webapp 폴더의 errorCode_404.jsp로 이동
3.2 예외 유형으로 오류 페이지 호출
<web-app>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/errorNullPointer.jsp</locatioin>
</error-page>
<web-app>
NullPointerException 오류 발생시 webapp 폴더의 errorNullPointer.jsp로 이동
4. try-catch-finally
java와 유사함
※서블릿에서의 jsp 호출: forward/include
1)forward()★
JSP 페이지를 호출하면 서블릿 프로그램 실행 종료, JSP 페이지로 넘어가서 실행하고 프로그램 종료
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("jspFile");
request.setAttribute("name", "value");
rd.forward(request, response);
2)include()
JSP 페이지 실행 후 나머지 서블릿 프로그램 실행
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("jspFile");
rd.include(request, response);
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception</title>
</head>
<body>
<%
try {
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
int c = a/b;
} catch (NumberFormatException e) {
RequestDispatcher dispatcher = request.getRequestDispatcher("tryCatch_error.jsp");
dispatcher.forward(request, response);
}
%>
</body>
</html>
12장. 필터
1. 필터의 개요
2. Filter 인터페이스의 구현 클래스
3. web.xml 파일의 필터 구성
1. 필터의 개요
what?
클라이언트와 서버 사이에서 request와 response 객체를 먼저 받아 사전/사후 작업을 처리하는 것
클라이언트의 요청(request)이 웹 서버의 서블릿, JSP, HTML 페이지 같은 정적 리소스에 도달하기 전과 정적 리소스에서 클라이언트로 응답하기 전에 필요한 전처리를 가능하게 함
①Filter 인터페이스 구현 자바 클래스 생성
②web.xml에 자바 클래스 등록
필터의 기능
1)request 필터
- 인증(사용자 인증)
- 요청 정보를 로그 파일로 작성★
- 암호화 인코딩 작업
2)Response 필터
- 응답 결과 데이터 압축
- 응답 결과에 내용 추가/수정
- 총 서비스 시간 측정
2. Filter 인터페이스의 구현 클래스
import javax.Servlet.Filter;
public class 클래스 이름 implements Filter{
@override
init()
@override
doFilter()
@override
destroy()
}
2.1 init()
역할: 초기화
한 번만 호출됨
JSP 컨테이너 내에서 초기화 작업을 수행할 필터 인스턴스를 생성한 후 한 번만 호출됨
public void init(FilterConfig filterConfig) throws ServletException
※FilterConfig 인터페이스 메서드의 종류
메서드 | 반환 유형 | 설명 |
getFilterName() | String | web.xml 파일에 설정된 필터 이름 반환 |
getthisParameter(String name) | String | web.xml 파일에 설정된 매개변수에 대한 매개변수값 |
getIntParameterNames() | Enumeration<String> | web.xml 파일에 설정된 모든 매개변수 이름을 포함하는 Enumeration 객체 타입 |
getServletContext() | ServletContext | ServletContext 객체 반환 |
2.2 doFilter()메서드
JSP 컨테이너가 필터를 리소스에 적용할 때마다 호출되는 메서드.
필터가 어떤 기능을 수행할 필요가 있을 때마다 호출
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException
SetvletRequest: 체인을 따라 전달하는 요청
ServletResponse: 체인을 따라 전달할 응답
FilterChain: 체인에서 다음 필터 호출(마지막 필터이면 체인 끝에서 리소스 호출)
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException{
System.out.println("JSP 처리 전 필터 수행...");
filterChain.doFilter(request, response);
System.out.println("JSP 처리 후 필터 수행...");
}
2.3 destroy() 메서드
필터 인스턴스 종료 전에 호출하는 메서드
JSP 컨테이너가 필터 인스턴스를 삭제하기 전에 청소 작업을 수행하는 데 사용
public void destroy()
3. web.xml 파일의 필터 구성
필터 적용 대상 리소스를 JSP 컨테이너에 알려주어야 함→web.xml 파일에 필터 설정
<filter>
<filter-name> </filter-name>
<filter-class> </filter-class>
[<init-param>
<param-name> </param-name>
<param-value> </param-value>
</init-param>]
</filter>
<filter-mapping>
<filter-name> </filter-name>
<url-pattern> </url-pattern>
</filter-mapping>
1)<filter>
filter-name: 필터 이름 설정
filter-class: 자바 클래스 이름
init-param: 매개변수와 값 설정
2)<filter-mapping>
filter-name: 필터 이름 설정
url-pattern: URL 패턴 설정
3.1<filter>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>ch12.com.filter.LoggingFilter</filter-class>
<init-param>
<param-name>param</param-name>
<param-value>admin</param-value>
</filter>
★<init-param> 요소에 설정된 매개변수와 값을 자바/JSP 코드에서 접근하는 형식
String value = getServletConfig().getInitParameter("매개변수 이름");
<init-param> 요소에 설정된 배개변수와 값을 자바/JSP 코드에서 접근하는 형식
String value = getServletConfig().getInitParameter("param");
3.2 <filter-mapping>
특정 리소스에 어떤 필터를 사용할지 설정
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
1)<filter>의 <filter-name>과 통일
2)/*: webapp 안의 모든 요청 URL
'정리노트' 카테고리의 다른 글
[JSP] (0) | 2023.12.15 |
---|---|
[JSP] 필터 (0) | 2023.12.14 |
[JSP] 다국어 처리, 시큐리티 (0) | 2023.12.12 |
[JSP] 유효성 검사, 다국어 처리 (0) | 2023.12.11 |
[JSP] 마인드맵 정리 (0) | 2023.12.08 |