KIC/JSP

[JSP] forward

octopengj 2020. 9. 21. 23:17
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이동하는 페이지를 요청하는 페이지</title>
</head>
<body>
  <h1>forward 액션태그 연습</h1>
    <form method="post" action="move.jsp">
       이동할 페이지명:<input type="text" name="move"><p>
       <input type="submit" value="보내기">
    </form>
</body>
</html>

forward.jsp

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>요청을 받아서 처리해주는 페이지1</title>
</head>
<body>
  <h1>페이지를 이동시키는 역할</h1>
  <%
 		String move=request.getParameter("move"); // a.jsp or b.jsp
  		System.out.println("이동할 페이지명(move)=>"+move);
  %>
  <jsp:include page="<%=move %>" /><br>
  
</body>
</html>

move.jsp

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>a.jsp</title>
</head>
<body bgcolor="yellow">
  <h1>a.jsp로 오신것을 환영합니다.</h1>
</body>
</html>

a.jsp

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>b.jsp</title>
</head>
<body bgcolor="skyblue">
  <h1>b.jsp로 오신것을 환영합니다.</h1>
</body>
</html>

b.jsp

 

forward.jsp 실행화면
a.jsp 입력

 

a.jsp 이동화면

정상적으로 이동한다.

 

b.jsp 입력
b.jsp 이동화면

정상적으로 이동한다.

 

 

c.jsp 입력

 

c.jsp 이동화면

오류가 발생한다.

사용자에게 경고창으로 알려주는 코드를 작성해보자

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>요청을 받아서 처리해주는 페이지1</title>
</head>
<body>
  <h1>페이지를 이동시키는 역할</h1>
  <%
 		String move=request.getParameter("move"); // a.jsp or b.jsp
  		System.out.println("이동할 페이지명(move)=>"+move);
 		// response.sendRedirect("a.jsp"); 이동만 가능, 공유X
 		// 요청한 페이지를 검사해서 올바른지를 체크할 목적으로 사용되는 페이지
 		if(move.equals("a.jsp")) {
  %>
  <jsp:include page="a.jsp" /><br>
  <% } else if(move.equals("b.jsp")) { %>
  <jsp:include page="b.jsp" /><br>
  <%} else {%>
  <script>
    alert("당신이 요청하신 페이지는 없습니다.\n 확인 후 다시해보세요!")
    location.href="forward.jsp"
  </script>
  <%} %>
  
</body>
</html>

move.jsp 코드를 수정하였다.

결과는 아래와 같이 작동한다.

 

c.jsp 입력시 나타나는 알림창

 

'KIC > JSP' 카테고리의 다른 글

[JSP] notice  (0) 2020.09.21
[JSP] Servlet  (0) 2020.09.21
[JSP] 프로젝트 생성/삭제  (0) 2020.09.21
[JSP] 프로젝트 export / import  (0) 2020.09.21
[JSP] JSP 표만들기  (0) 2020.09.21