세션을 이용하여 jsp 애플리케이션 만들기

조수경·2022년 1월 23일
0

JSP

목록 보기
41/45

참고자료
https://velog.io/@junhok82/%EB%A1%9C%EA%B7%B8%EC%9D%B8%EC%9D%80-%EC%96%B4%EB%96%BB%EA%B2%8C-%EC%9D%B4%EB%A3%A8%EC%96%B4%EC%A7%88%EA%B9%8CCookie-Session

1. 세션이란?

: 세션은 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법을 말한다.
세션은 웹 서버에서만 접근이 가능하기 때문에 보안에 유리하며, 브라우저마다 하나씩 존재하여 사용자를 구분하는 단위가 된다.

  1. JSP 페이지에 세션을 설정하는 메소드, 설정된 세션을 삭제하는 메소드는 무엇인가?

: 세션을 설정하는 메소드는 setAttribute(String name, Object value) 메소드이고, 세션을 삭제하는 메소드는 removeAttribute(String name) 메소드이다.

  1. 설정된 세션 정보를 얻어오는 메소드에 대해 간단히 설명하시오.

: 세션 정보 하나에 저장된 속성 값을 얻어오려면 getAttribute(String name) 메소드를 사용하고, 여러 개의 세션 속성 이름에 대한 속성 값을 얻어오려면 getAttributeNames() 메소드를 사용한다.

session.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>

<title>Session</title>
</head>
<body>
  <form method="post" action="session_process.jsp">
  	<p>아이디 : <input type="text" name="id" /></p>
  	<p>비밀번호 : <input type="text" name="pass" /></p>
  	<p><input type="submit" value="전송" /></p>
  </form>
</body>
</html>

session_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	<%
	//파람으로 네임값 받기
	String user_id = request.getParameter("id");
	String user_pass = request.getParameter("pass");
	
	//길이가 0이 아닐때
	if(user_id.length() != 0){
		//세션에 넣기
		session.setAttribute("userID", user_id);
		session.setAttribute("userPASS", user_pass);
		
		response.sendRedirect("welcome.jsp");
		
	}else{
  		  //아무것도 입력하지 않았을때
		response.sendRedirect("session.jsp");
	}
	
	%>
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

//세션은 object타입이라 형변환 해주기
//세션에 넣어줬던 userID를 id에 넣기

	<% 
	 String id = (String)session.getAttribute("userID"); 
	%>
    
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
	
	
<p><%=id%>님 환영합니다</p>
<a href="session_out.jsp">로그아웃</a>
</body>
</html>

session_out.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
<%
// 세션 전체 삭제
	session.invalidate();
	response.sendRedirect("session.jsp");

%>
</body>
</html>
profile
신입 개발자 입니다!!!

0개의 댓글