스프링 (31)

반응형

 

쇼핑몰 시스템

 

 

상품이 없을 때 뜨는 오류 화면을 대신하기 위해서 아래 작업 진행

 

 

exceptionNoProductId.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>

   <jsp:include page="menu.jsp" />
   <div class="jumbotron">
      <!-- container : 이 안에 내용있다 -->
      <div class="container">
         <h1 class="display-3">해당 상품이 존재하지 않습니다.</h1>
      </div>
   </div>
   
   <!-- ----------------오류 처리 내용 시작 ----------------------- -->
   <div class="container">
      <!-- getRequestURL() : http://localhost/product.jsp -->
      <!-- getQueryString() : id=P1234 -->
      <p><%=request.getRequestURL()%>?<%=request.getQueryString()%></p>
      <p><a href="products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
   </div>
   <!-- ----------------오류 처리 내용 끝 ----------------------- -->
   
   <jsp:include page="footer.jsp" />

</body>
</html>

 

 

페이지가 없을 때 뜨는 오류 화면을 대신하기 위해서 아래 작업 진행

 

 

exceptionNoPage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>

   <jsp:include page="menu.jsp" />
   <div class="jumbotron">
      <!-- container : 이 안에 내용있다 -->
      <div class="container">
         <h1 class="display-3">요청하신 페이지를 찾을 수 없습니다.</h1>
      </div>
   </div>
   
   <!-- ----------------오류 처리 내용 시작 ----------------------- -->
   <div class="container">
      <!-- getRequestURL() : http://localhost/product.jsp -->
      <!-- getQueryString() : id=P1234 -->
      <p><%=request.getRequestURL()%>%></p>
      <p><a href="products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
   </div>
   <!-- ----------------오류 처리 내용 끝 ----------------------- -->
   
   <jsp:include page="footer.jsp" />

</body>
</html>

 

 

 

product.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.vo.ProductVO"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page errorPage="/exceptionNoPage.jsp" %>
<%
	/*
	요청URI : product.jsp
	요청파라미터 : productId=P1234
	요청방식 : get(목록, 검색, 상세)
	*/
	// 싱글톤
	ProductRepository productDAO = 
		ProductRepository.getInstance();
	
	String productId = request.getParameter("productId"); // P1234
	out.print("<p>"+productId+"</p>"); // P1234
	
	ProductVO productVO = productDAO.getProductById(productId);
	out.print("<p>"+productVO+"</p>");
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" /> <!-- 파라미터가 없기 때문에 이렇게 사용 가능 -->

	<!-- --------------------상품상세 시작-------------------- -->
	<div class="jumbotron">
	   <!-- container : 이 안에 내용있다 -->
	   <div class="container">
	      <h1 class="display-3">상품 정보</h1>
	   </div>
	</div>
	<!-- 내용 -->
	<div class="container">
		<div class="row">
			<div class="col-md-5">
				<img src="/images/<%=productVO.getFilename()%>" 
					style="width:100%;">
			</div>
			<div class="col-md-6">
				<h3><%=productVO.getPname()%></h3>
				<p><%=productVO.getDescription()%></p>
				<p>
					<b>상품 코드 : </b>
					<span class="badge bage-danger">
					<%=productVO.getProductId()%>
					</span>
				</p>
				<p><b>제조사 : </b><%=productVO.getManufacturer()%></p>
				<p><b>분류 : </b><%=productVO.getCategory()%></p>
				<p><b>재고 수 : </b><%=productVO.getUnitsInStock()%></p>
				<h4><%=productVO.getUnitPrice()%></h4>
				<p>
					<!-- 폼태그, 폼페이지 
					action : 요청URI
					요청URI : addCart.jsp
					요청파라미터 : id=P1234
					요청방식 : post
					-->
					<form name="addForm" action="addCart.jsp?productId=<%=productVO.getProductId()%>"
						method="post">
						<!-- 폼데이터 -->
						<!-- 상품 주문 : 장바구니에 상품을 넣음 
						addToCart() : 핸들러 함수
						-->
						<a href="#" class="btn btn-info" onclick="addToCart()">삼품주문&raquo;</a>
						<!-- 장바구니 : 장바구니에 담겨진 상품 목록 확인 -->
						<a href="cart.jsp" class="btn btn-warning">장바구니&raquo;</a>
						<a href="products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
					</form>
			</div>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

결과 화면1 : errorPage를 설정하지 않았을 때 화면

 

 

 

  • errorPage 설정 (상품이 존재하지 않을때) : 500

product.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.vo.ProductVO"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page errorPage="/exceptionNoPage.jsp" %>
<%
	/*
	요청URI : product.jsp
	요청파라미터 : productId=P1234
	요청방식 : get(목록, 검색, 상세)
	*/
	// 싱글톤
	ProductRepository productDAO = 
		ProductRepository.getInstance();
	
	String productId = request.getParameter("productId"); // P1234
	out.print("<p>"+productId+"</p>"); // P1234
	
	ProductVO productVO = productDAO.getProductById(productId);
	out.print("<p>"+productVO+"</p>");
	
	productVO.toString(); //?productId=P000 => null.toString() => 문제 발생
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
	<!-- include 액션 태그 -->
	<jsp:include page="menu.jsp" /> <!-- 파라미터가 없기 때문에 이렇게 사용 가능 -->

	<!-- --------------------상품상세 시작-------------------- -->
	<div class="jumbotron">
	   <!-- container : 이 안에 내용있다 -->
	   <div class="container">
	      <h1 class="display-3">상품 정보</h1>
	   </div>
	</div>
	<!-- 내용 -->
	<div class="container">
		<div class="row">
			<div class="col-md-5">
				<img src="/images/<%=productVO.getFilename()%>" 
					style="width:100%;">
			</div>
			<div class="col-md-6">
				<h3><%=productVO.getPname()%></h3>
				<p><%=productVO.getDescription()%></p>
				<p>
					<b>상품 코드 : </b>
					<span class="badge bage-danger">
					<%=productVO.getProductId()%>
					</span>
				</p>
				<p><b>제조사 : </b><%=productVO.getManufacturer()%></p>
				<p><b>분류 : </b><%=productVO.getCategory()%></p>
				<p><b>재고 수 : </b><%=productVO.getUnitsInStock()%></p>
				<h4><%=productVO.getUnitPrice()%></h4>
				<p>
					<!-- 폼태그, 폼페이지 
					action : 요청URI
					요청URI : addCart.jsp
					요청파라미터 : id=P1234
					요청방식 : post
					-->
					<form name="addForm" action="addCart.jsp?productId=<%=productVO.getProductId()%>"
						method="post">
						<!-- 폼데이터 -->
						<!-- 상품 주문 : 장바구니에 상품을 넣음 
						addToCart() : 핸들러 함수
						-->
						<a href="#" class="btn btn-info" onclick="addToCart()">삼품주문&raquo;</a>
						<!-- 장바구니 : 장바구니에 담겨진 상품 목록 확인 -->
						<a href="cart.jsp" class="btn btn-warning">장바구니&raquo;</a>
						<a href="products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
					</form>
			</div>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>

 

결과 화면2

 

 

 

  • errorPage 설정 (페이지가 존재하지 않을때) : 404

web.xml (변경 또는 추가)

  <error-page>
  	<error-code>404</error-code>
  	<location>/exceptionNoPage.jsp</location>
  </error-page>

 

결과 화면3

 

 

반응형
반응형

 

예외 처리 

 

 

오류 처리

: 프로그램이 처리되는 동안 특정한 문제가 발생했을 때 처리를 중단하고 다른 처리를 하는 것

오류 페이지에 발생 오류, 디렉터리 구조, 톰캣 버전 등의 정보가 나타나 있기에 웹 보안에 취약함

ex) 

 

 

 

  • 예외 처리 방법의 종류
예외 처리 방법 설명
page 디렉티브 태그 이용 errorPage, isErrorPage 속성 이용
web.xml 파일 이용 <error-code>, <exception-type> 요소 이용
try/catch/finally를 이용 자바 언어의 예외 처리 구문 이용

 

 

 

 

page 디렉티브 태그 이용

 

 

  •  errorPage 속성으로 오류 페이지 호출
<%@ page errorPage = "오류 페이지 URL" %>

 

 

errorPage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page errorPage="errorPage_error.jsp" %>
<!-- JSP 페이지가 실행되는 도중 오류 발생 시 오류 페이지 호출.
page 디렉티브 태그. errorPage 속성 작성 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 
		요청 URI : /ch11/errorPage.jsp?name=apple
		요청 파라미터(HTTP 파라미터, QueryString) : name=apple
		요청방식 : GET
	 -->
	 <p>name 파라미터 : <%=request.getParameter("name").toUpperCase()%> </p>
</body>
</html>

 

 

errorPage_error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<h3>오류가 발생했습니다.</h3>
</body>
</html>

 

결과 화면1-1 : 뒤에 파라미터까지 입력했을 때

 

결과 화면1-2 : redirect와 달리 예외처리임

 

=> 미리 오류 발생 시 web.xml로 페이지 설정을 해 놨을 경우에도 errorPage가 우선 처리

 

 

 

  • isErrorPage 속성 추가 이용
<%@ page isErrorPage = "true" %>

 

 

메소드 형식 설명
getMessage() String 오류 이벤트와 함께 들어오는 메시지 출력
toString() String toString()을 호출하여 간단한 오류 메시지 확인
printStackTrace() String 오류 메시지의 발생 근원지를 찾아 단계별로 오류 출력

 

 

 

 

errorPage_error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page isErrorPage="true" %>
<!-- isErrorPage 속성 : 현재 JSP 페이지를 오류 페이지로 호출하는
page 디렉티브 태그의 속성. 이때 오류 페이지에서 exception 내장 객체를
사용할 수 있음 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<h3>오류가 발생했습니다.</h3>
	
	<!-- P.361 -->
	<!-- exception : JSP에서 제공해주는 오류 처리용 기본 내장 객체 -->
	<!-- <exception-type>java.lang.NullPointerException</exception-type> -->
	<!-- 오류 이벤트의 toString()을 호출하여 간단한 오류 메시지 확인 -->
	<p>예외 유형 : <%=exception.toString()%></p> <!-- isErrorPage을 사용해야 쓸 수 있음 -->
	
	<!-- 오류 메시지의 발생 근원지를 찾아 단계별로 오류를 출력 -->
<%-- 	<p>단계별 오류 출력 : <%=exception.printStackTrace()%></p> --%>
	
	<!-- 오류 발생 시 해당 예외 객체 타입을 가져와 출력 -->
	<p>예외 유형 : <%=exception.getClass().getName()%></p>
	
	<!-- getMessage() 오류 이벤트와 함께 들어오는 메시지를 출력 -->
	<p>오류 메시지 : <%=exception.getMessage()%></p>
</body>
</html>

 

결과 화면2

 

 

 

  • => 로그인 시 오류 내용 확인할 수 있게 수정
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page isErrorPage="true" %>
<!-- isErrorPage 속성 : 현재 JSP 페이지를 오류 페이지로 호출하는
page 디렉티브 태그의 속성. 이때 오류 페이지에서 exception 내장 객체를
사용할 수 있음 -->
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<h3>오류가 발생했습니다.</h3>
	
	<%if(request.isUserInRole("manager")) {%>
		<!-- P.361 -->
		<!-- exception : JSP에서 제공해주는 오류 처리용 기본 내장 객체 -->
		<!-- <exception-type>java.lang.NullPointerException</exception-type> -->
		<!-- 오류 이벤트의 toString()을 호출하여 간단한 오류 메시지 확인 -->
		<p>예외 유형 : <%=exception.toString()%></p> <!-- isErrorPage을 사용해야 쓸 수 있음 -->
		
		<!-- 오류 메시지의 발생 근원지를 찾아 단계별로 오류를 출력 -->
		<%-- <p>단계별 오류 출력 : <%=exception.printStackTrace()%></p> --%>
		
		<!-- 오류 발생 시 해당 예외 객체 타입을 가져와 출력 -->
		<p>예외 유형 : <%=exception.getClass().getName()%></p>
		
		<!-- getMessage() 오류 이벤트와 함께 들어오는 메시지를 출력 -->
		<p>오류 메시지 : <%=exception.getMessage()%></p>
	<%}%>
</body>
</html>

 

결과 화면3 : 로그인 후 확인 화면

 

 

 

web.xml 파일 이용

 

 

요소 설명
<error-code> 오류 코드를 설정
<exception-type> 자바 예외 유형의 정규화된 클래스 이름 설정
<location> 오류 페이지의 URL 설정

 

주요 오류 코드의 종류

 

 

web-app의 안, 가장 하단에 추가하기

web.xml

  <!-- 오류가 나면 오류 타입에 맞춰 오류 처리 jsp로 매핑 -->
  <!-- 404 : page not found. URL에 해당되는 jsp가 없음 -->
  <!-- 
  [주요 오류 코드 종류]
  200 : 요청이 정상적으로 처리됨
  307 : 임시로 페이지가 리다이렉트 됨
  400 : 클라이언트의 요청이 잘못된 구문으로 구성됨
  401 : 접근이 허용되지 않음
  404 : 지정된 URL을 처리하기 위한 자원이 존재하지 않음
  405 : 요청된 메소드가 허용되지 않음
  500 : 서버 내부 오류(JSP에서 예외 발생)
  503 : 서버 과부하나 보수 중인 경우. 서버가 일시적으로 서비시를 제공할 수 없음
	 -->
  <error-page>
  <!-- 오류 코드 설정 
     오류 코드 : 웹 서버가 제공하는 기본 오류 페이지에 나타나는 404, 500과 같이
     사용자의 요청이 올바르지 않을 때 출력되는 코드. 응답 상태 코드.
     
     JSP페이지에서 발생하는 오류가 web.xml 파일에 설정된 오류 코드와 일치하는
     경우 오류 코드와 오류 페이지를 보여줌
   -->
  	<error-code>404</error-code>
  	<location>/error/error404.jsp</location>
  </error-page>
  
  <error-page>
  	<!-- 프로그래밍 오류 ex ) 10/0과 같이 잘못된 코드 -->
  	<error-code>500</error-code>
  	<location>/error/error500.jsp</location>
  </error-page>

 

 

경로 안에 이미지 파일 추가

 

경로 안에 jsp 파일 생성

 

 

error404.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>404오류</title>
</head>
<body>
	<img src="/images/404.jpg" />
</body>
</html>

 

 

error500.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>500오류</title>
</head>
<body>
	<img src="/images/500.jpg" />
</body>
</html>

 

결과 화면4 : 404 화면

 

 

 

  • error-code 이용

errorCode.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 폼페이지 
	요청URI : errorCode_process.jsp?num1=10&num2=5
	요청파라미터 : num1=10&num2=5
	요청방식 : post
	-->
	<form action="errorCode_process.jsp" method="post">
		<p>숫자1 : <input type="number" name="num1" placeholder="숫자1" required></p>
		<p>숫자2 : <input type="number" name="num2" placeholder="숫자2" required></p>
		<p><input type="submit" value="나누기" /></p>
	</form>
</body>
</html>

 

 

errorCode_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<!-- 폼페이지 
	요청URI : errorCode_process.jsp?num1=10&num2=5
	요청파라미터 : num1=10&num2=5
	요청방식 : post
	-->
	<%
		String num1 = request.getParameter("num1"); //10
		String num2 = request.getParameter("num2"); //5
		
		// 문자 타입을 숫자 타입으로 형변환
		int a = Integer.parseInt(num1);
		int b = Integer.parseInt(num2);
		/*page 디렉티브의 errorPage속성이 없으므로 web.xml의 
		error500.jsp에서 오류를 처리함
		<error-page>
			<error-code>500</error-code>
			<location>/error/error500.jsp</location>
		</error-page>
		*/
		
		int c = a / b; // by zero 오류 발생
		out.print(num1 + " / " + num2 + " = " + c);
	%>
</body>
</html>

 

결과 화면5 : 0으로 나누기에 오류 발생 예정

 

결과 화면6

 

 

 

  • exception-type의 NullPointerException 이용

 

주요 예외 유형의 종류

 

 

web.xml

하단에 추가

  <error-page>
  	<!-- excetion 타입 -->
  	<exception-type>java.lang.NullPointerException</exception-type>
  	<!-- 오류페이지 설정 -->
  	<location>/error/errorNullPointer.jsp</location> <!-- jsp가 있어야 함!! -->
  </error-page>

 

 

=> nullPointerException이 발생할 경우 위의 errorNullPointer.jsp로 이동됨

 

 

 

try/catch/finally를 이용

 

 

tryCatch.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!-- 폼페이지 
	요청URI : tryCatch_process.jsp
	요청파라미터 : {num1=10&num2=5}
	요청방식 : post
	-->
	<form action="tryCatch_process.jsp" method="post">
		<p>숫자1 : <input type="number" name="num1" placeholder="숫자1" required></p>
		<p>숫자2 : <input type="number" name="num2" placeholder="숫자2" required></p>
		<p><input type="submit" value="나누기" /></p>
	</form>
</body>
</html>

 

 

tryCatch_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<!-- 폼페이지 
	요청URI : tryCatch_process.jsp
	요청파라미터 : {num1=10&num2=5}
	요청방식 : post
	-->
	<%
		try{
			String num1 = request.getParameter("num1"); //10
			String num2 = request.getParameter("num2"); //5
			
			// 문자 타입을 숫자 타입으로 형변환
			int a = Integer.parseInt(num1);
			int b = Integer.parseInt(num2);
			/*page 디렉티브의 errorPage속성이 없으므로 web.xml의 
			error500.jsp에서 오류를 처리함
			<error-page>
				<error-code>500</error-code>
				<location>/error/error500.jsp</location>
			</error-page>
			*/
			
			int c = a / b; // by zero 오류 발생
			out.print(num1 + " / " + num2 + " = " + c);
		} catch(ArithmeticException e) {
			out.print("<img src='/images/error.jpg' />");
		}
	%>
</body>
</html>

 

결과 화면7

 

결과 화면8

 

 

=> try-catch > errorPage > web.xml 순으로 우선 순위가 있음

 

 

 

+forward와 Redirct 차이

 

tryCatch_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page errorPage="errorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<!-- 폼페이지 
	요청URI : tryCatch_process.jsp
	요청파라미터 : {num1=10&num2=5}
	요청방식 : post
	-->
	<%
		try{
			String num1 = request.getParameter("num1"); //10
			String num2 = request.getParameter("num2"); //5
			
			// 문자 타입을 숫자 타입으로 형변환
			int a = Integer.parseInt(num1);
			int b = Integer.parseInt(num2);
			/*page 디렉티브의 errorPage속성이 없으므로 web.xml의 
			error500.jsp에서 오류를 처리함
			<error-page>
				<error-code>500</error-code>
				<location>/error/error500.jsp</location>
			</error-page>
			*/
			
			int c = a / b; // by zero 오류 발생
			out.print(num1 + " / " + num2 + " = " + c);
		} catch(ArithmeticException e) {
			//오류가 발생하면 tryCatch_error.jsp로 포워딩.
	        /*
	           1) forwarding : jsp해석 -> 컴파일 -> html 리턴받음. 데이터를 전달할 수 있음. 
	           2) redirect : URL을 재요청. 데이터를 전달하기 어려움.
	        */
	        //request객체와 response객체를 전달함
	        //tryCatch_error.jsp에서도 요청파라미터인 ?num1=12&num2=0을 사용할 수 있음
				
			RequestDispatcher dispatcher = 
					request.getRequestDispatcher("/ch11/tryCatch_error.jsp");
			dispatcher.forward(request, response); // forward로 인해 request 객체가 tryCatch_error로 따라감
		}
	%>
</body>
</html>

 

 

tryCatch_error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Exception</title>
</head>
<body>
	<!--
	요청URI : tryCatch_process.jsp
	요청파라미터 : request객체 안에 {num=10&num2=5}
	요청방식 : post 
	 -->
	<p>잘못된 데이터가 입력되었습니다.</p>
	<p>숫자1 : <%=request.getParameter("num1")%></p>
	<p>숫자2 : <%=request.getParameter("num2")%></p>
</body>
</html>

 

결과 화면9

 

결과 화면10

 

 

반응형
반응형

 

연습 문제 01

 

시큐리티란 무엇인가?

 

더보기

시큐리티

: 허가된 사용자만이 특정 웹 페이지에 접근할 수 있도록 제한하는 보안 기능

 

 

 

연습 문제 02

 

시큐리티의 두 가지 처리 기법에 대해 간단히 설명하시오.

 

더보기

1. 선언적 시큐리티

: web.xml 파일에 보안 구성을 작성하여 사용자 인증을 수행하는 방식

 

 

2. 프로그래밍적 시큐리티

: request 내장 객체의 메소드를 통해 사용자의 권한 부여를 처리하는 방식

 

 

 

연습 문제 03

 

FORM 기반 인증 처리 기법으로 로그인 페이지를 작성하는 방법을 설명하시오.

 

더보기
login-config>
	<auth-method>FORM</auth-method>
</login-config>

 

+ form 태그에 action 속성값, 아이디와 비밀번호 input 태그의 name 속성을 각각 j_security_check, j_username, j_password로 설정

 

 

 

연습 문제 04

 

FORM 기반 인증 처리 기법을 이용하여 다음 조건에 맞게 JSP 애플리케이션을 만들고 실행 결과를 확인하시오.

 

 

더보기

tomcat-users.xml (아래 코드 추가)

  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="java" roles="tomcat"/>
  <user username="both" password="java" roles="tomcat,role1"/>
  <user username="role1" password="java" roles="role1"/>
  <user username="admin" password="admin1234" roles="role1"/>

 

 

 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">
  <!-- 시큐리티 역할(Role) 설정 -->
  <security-role>
  	<description></description>
  	<role-name>role1</role-name> <!-- 사용시 톰캣에 존재해야함 -->
  </security-role>
  
  <!-- 2. 시큐리티 제약 사항 설정 -->
  <security-constraint>
  	<!-- 웹 자원의 이름 설정(생략가능) -->
  	<display-name>Exercise Security</display-name>
  	<!-- 웹 자원에 대한 약속 목록 -->
  	<web-resource-collection>
  		<!-- 프로젝트명 -->
  		<web-resource-name>Exercise</web-resource-name>
  		<url-pattern>/ch10/success.jsp</url-pattern>
  		<!-- HTTP 요청방식 -->
  		<http-method>GET</http-method>
  	</web-resource-collection>
  	
  	<auth-constraint>
		<!-- 권한 부여 제약 사항에 대한 설명 기술 -->
		<description></description>
		<!-- 권한이 부여된 사용자 이름 설정 -->
        <role-name>role1</role-name>
  	</auth-constraint>
  </security-constraint>
  <login-config>
	<!-- FORM 인증 처리 기법 설정 -->
	<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>
</web-app>

 

 

security.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<p><a href="success.jsp">로그인</a></p>
</body>
</html>

 

 

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<form action="j_security_check">
		<p>사용자명 : <input type="text" id="inputUsername" name="j_username" /></p>
		<p>비밀번호 : <input type="text" id="inputPassword" name="j_password" /></p>
		<p><input type="submit" name="id" /></p>
	</form>
</body>
</html>

 

 

login_failed.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<p>인증을 실패했습니다.</p>
</body>
</html>

 

 

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<p>사용자명<%=request.getRemoteUser()%>인증을 성공했습니다.</p>
</body>
</html>

 

결과 화면1

 

결과 화면2

 

결과 화면3

 

결과 화면4

 

 

 

 

연습 문제 05

 

다음 조건에 맞게 도서 웹 쇼핑몰을 위한 웹 애플리케이션을 만들고 실행 결과를 확인하시오.

 

 

 

 

반응형
1 2 3 4 5 6 ··· 11