JSP 4일 (23.03.28)

Jane·2023년 3월 28일
0

IT 수업 정리

목록 보기
90/124

1. JSP 지시자 사용

1-1. jsp 파일 include 하기

  • <%@ %> 안에 include file="경로" 적는다.

넣고 싶은 파일 : include01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>include 01 jsp</h1>
</body>
</html>

메인 파일 : include.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<main>
	<h1>여기는 main입니다.</h1>
	<%@include file="include01.jsp" %>
</main>
</body>
</html>

1-2. 주석 처리하기

  • <%-- --%> : 주석 표시
    ("Ctrl + Shift + /" 같이 누르기)

<%-- <% 
	String radius = request.getParameter("radius");
	Circle circle = new Circle(Double.valueOf(radius));
%>
 --%>

2. 액션 태그

2-1. jsp:forward

  • 실행하는 부분은 main.jsp
  • forward를 하면 아예 forward 지정된 jsp(sub.jsp)로 넘어가게 된다.
    그러므로 뒷부분에 적은 main.jsp의 내용을 하나도 읽지 않게 된다.

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Main JSP</title>
</head>
<body>
<h1>메인 페이지입니다</h1>
<jsp:forward page="sub.jsp" />
<h1>꼬리말입니다</h1>
</body>
</html>

sub.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>서브 페이지 입니다. sub jsp file</h3>
</body>
</html>

  • jsp:include와 jsp:forward의 차이는?

main.jsp (jsp:forward를 jsp:include로 바꿈)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Main JSP</title>
</head>
<body>
<h1>메인 페이지입니다</h1>

<jsp:include page="sub.jsp" />

<h1>꼬리말입니다</h1>

</body>
</html>

2-2. parameter 받아오기 (jsp:param)

forward.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>forward</title>
</head>
<body>
<jsp:forward page="forward_param.jsp">
	<jsp:param name="id" value="abcde" />
	<jsp:param name="pw" value="1234" />
</jsp:forward>
</body>
</html>

forward_param.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>forward</title>
</head>
<body>
<%
	String id, pw;
%>

<%
	id = request.getParameter("id");
	pw = request.getParameter("pw");
%>

ID : <%= id %><br />
PW : <%= pw %><br />


</body>
</html>

3. 쿠키

  • 쿠키 : 어떤 정보를 남겨서 지속적으로 유지하기 위한 수단
    4KB, 300개까지
    key-value 형태의 정보를 갖고 있다.

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>login</title>
<style>
span{
display:inline-block;
width:40px;
text-align:center;
}

</style>
</head>
<body>

	<form action="login_ok.jsp" method="post">
		<span>ID</span> : <input	type="text" name="id" size="10"/><br />
		<span>PW</span> : <input	type="text" name="pw" size="10"/><br />
		 <input	type="submit" value="전송" />
	</form>

</body>
</html>

login_ok.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>login ok</title>
</head>
<body>
<%!
      String id, pw;
   %>
   <%
      id = request.getParameter("id");
      pw = request.getParameter("pw");
      
      if(id.equals("abcd") && pw.equals("1234")){
         Cookie cookie = new Cookie("id",id);
         // 쿠키 객체 생성 후 아이디의 쿠키를 남긴다.
         cookie.setMaxAge(60);
         // 1시간 동안 웹 브라우저에 저장.
         
         response.addCookie(cookie);
         response.sendRedirect("welcome.jsp");
         // redirect : 유저가 해당 페이지로 접속하게 한다.
      }else{
         response.sendRedirect("login.jsp");         
      }
      
   %>


</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>
<% 
	Cookie[] cookies = request.getCookies();

	for(int i=0; i<cookies.length; i++){
		out.println(cookies[i].getValue() + "<br>");
	}

	// 쿠키 삭제 : setMaxAge(0)

%>
</body>
</html>
  • forward와 redirect의 차이는?

4. 세션

  • 세션 : 쿠키처럼 어떤 정보를 남겨서 지속적으로 유지하기 위한 수단이지만,
    클라이언트의 특정 위치에서 저장하는 것이 아니라, 서버에서 객체로 존재하는 것이다.

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>login</title>
<style>
span{
display:inline-block;
width:40px;
text-align:center;
}

</style>
</head>
<body>
	<form action="loginok_session.jsp" method="post">
		<span>ID</span> : <input	type="text" name="id" size="10"/><br />
		<span>PW</span> : <input	type="text" name="pw" size="10"/><br />
		 <input	type="submit" value="전송" />
	</form>

</body>
</html>

loginok_session.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>loginok_session</title>
</head>
<body>
<%!
      String id, pw;
   %>
   <%
      id = request.getParameter("id");
      pw = request.getParameter("pw");
      
      if(id.equals("abcd") && pw.equals("1234")){
            	  
    	 session.setAttribute("id", id); // session은 내장 객체, 객체생성을 하지 않아도 만들어진다.
    	 session.setAttribute("pw", pw);
    	  
         response.sendRedirect("welcome_session.jsp");         
      }else{
    	 
         response.sendRedirect("login.jsp");         
      }
      
   %>
</body>
</html>

welcome_session.jsp

<%@page import = "java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>

<% 
	String id = (String)session.getAttribute("id");
	String pw = (String)session.getAttribute("pw");
	// session의 return 타입은 Object
%>

<%= id %> 님이 접속했습니다.
비밀번호는 <%= pw %>

<hr />

   <%
      Enumeration enumeration = session.getAttributeNames();
      
      while(enumeration.hasMoreElements()){
         String sName = enumeration.nextElement().toString();
         String sValue = (String)session.getAttribute(sName);
         
         out.print(sName + " : " + sValue + "<br>");
      }
   
      out.println("======================<br>");
      
      /* 특정 세션 데이터 삭제*/
      session.removeAttribute("pw");
      
      
      enumeration = session.getAttributeNames();
      while(enumeration.hasMoreElements()){
          String sName = enumeration.nextElement().toString();
          String sValue = (String)session.getAttribute(sName);
          
          out.print(sName + " : " + sValue + "<br>");
       }
      
      /* 모든 데이터 삭제 */
      
      out.println("======================<br>");
      session.invalidate();
      
      // 세션 무효화 확인
      if(request.isRequestedSessionIdValid()){
          out.print("session valid");
       }else{
          out.print("session Invalid");
       }
   
   %>


</body>
</html>
  • 무효화된 세션을 enumeration으로 체크하면 내부 서버 오류 표시 + 세션 무효화가 뜬다.
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글