Session
Session
: 앞서 올린 쿠키랑 비슷하게 클라이언트와 서버의 연결 정보를 저장하는 기능을 한다.
브라우저에 저장하는 쿠키와 다르게 세션은 서버에 저장한다!
login.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>
<%
if(session.getAttribute("memberId")!=null)
response.sendRedirect("loginOk.jsp");
%>
<form action="loginCon" method='post'>
ID : <input type="text" name = "mID"><br>
PW : <input type="password" name="mPW"><br>
<input type="submit" value="login">
</form>
</body>
</html>
login.jsp로 로그인 형식을 만들어주고
LoginCon.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/loginCon")
public class LoginCon extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String mID = request.getParameter("mID");
String mPW = request.getParameter("mPW");
out.println("mID: "+mID);
out.println("mPW: "+mPW);
HttpSession session = request.getSession();
session.setAttribute("memberId", mID);
response.sendRedirect("loginOk.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
login.jsp에서 넘어온 아이디와 패스워드 값을 받아와 아이디값으로 세션을 생성한 후 로그인 완료 jsp로 넘긴다.
loginOk.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>
<%
session = request.getSession();
out.println("memberId: "+ session.getAttribute("memberId")+"<br>");
%>
<form action="logout" method="post">
<input type="submit" value="logout">
</body>
</html>
넘어온 세션값(아이디)을 출력해주고 !
logout을 누르면 logout 서블릿으로 넘어가면서 세션이 해제된다. 그리고 세션이 해제되었기때문에 다시 로그인 할 수 있는 창으로 넘어간다.
LogoutCon.java
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/logout")
public class LogoutCon extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Comments