(로그인 과정 참고)
- 로그인 (세션 바인딩)
- LoginDBServlet
@WebServlet("/logindb") /////이름 수정
public class LoginDBServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request,response);
}
private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//db는 서버 context에서 이미 연결
//브라우저에서 아이디, 비밀번호 받아 MemberVO에 세팅
String id = request.getParameter("user_id");
String pwd = request.getParameter("user_pw");
MemberVO memberVO = new MemberVO();
memberVO.setId(id);
memberVO.setPwd(pwd);
//회원정보 DB에 memberVO 회원 있는지 확인
MemberDAO dao = new MemberDAO();
boolean result = dao.exists(memberVO);
out.print("<html><body>");
if (result) {
HttpSession session = request.getSession();
session.setAttribute("loggedIn", true); //로그인 여부 정보 추가
session.setAttribute("login_id", id); //아이디 정보
session.setAttribute("login_pwd", pwd); //비밀번호 정보
out.print("<p>안녕하세요 +"+id+"님</p>");
out.print("<a href='show'>회원정보 보기</a>");
} else {
out.print("<p>존재하는 회원이 아닙니다</p>");
out.print("<a href='login3.html'>다시 로그인 하기</a>");
}
out.print("</body></html>");
}
}
- ShowMember
@WebServlet("/show")
public class ShowMember extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request, response);
}
private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String id="";
Boolean loggedIn=false;
HttpSession session = request.getSession(false); //세션 존재 x => null 반환
if (session != null) {
loggedIn = (Boolean) session.getAttribute("loggedIn");
if (loggedIn==true) {
id = (String) session.getAttribute("login_id");
out.print("<html><body>");
out.print("<h2>"+id+"님은 우수회원입니다.</h2>");
out.print("<h2>발급한 할인권을 이용해 상품을 구매하실 수 있습니다.</h2>");
out.print("</body></html>");
} else {
response.sendRedirect("login3.html");
}
} else {
response.sendRedirect("login3.html"); //해당 주소로 이동 (포워드)
}
}
}
//
처음 /show 방문 시 세션 미생성
-> login3.html로 포워드됨
-> 폼 submit 클릭 시 /logindb 이동 & id,pw 요청값 전달 => 안녕하세요 hong님
-> a태그 클릭 시 /show 이동 => hong님은 우수회원입니다.~~
https://kgvovc.tistory.com/37
https://salguru.tistory.com/23
https://sgcomputer.tistory.com/239
서블릿 데이터 저장소별 상태 정보 유지
HTTP 프로토콜 => 무상태(Stateless)
: 클라이언트와 서버 간의 연결을 클라이언트 요청이 있을 때마다 매번 새롭게 연결
=> 서버가 클라이언트에게 응답을 보내는 즉시 연결 끊어짐
이전 요청에서의 처리 결과를 계속해서 다른 요청에서도 사용하고 싶으면 어딘가에 저장해서 정보를 유지해야 함 (= 상태정보)
1. 클라이언트 측에 저장
웹 브라우저에 저장
브라우저 종료 시 정보 삭제 or 유지 선택 가능
(ex) Cookie
2. 서버 측에 저장
서버의 힙 메모리 영역에 만들어진 객체에 상태정보 저장
(ex) ServletContext(), HttpSession, HttpServletRequest
이름 | 용도 + 데이터 공유 범위 | 라이프 사이클 |
request | 클라이언트 요청을 서블릿으로 전달하는 객체 해당 request를 전달받는 리소스에서만 공유 가능 (요청 단위 유지) |
Http 프로토콜 기준으로 클라이언트 요청이 response 되기 전까지 살아있음 |
session | 클라이언트 데이터를 유지 모든 서블릿 사이에서 데이터 공유가 가능 (클라이언트 단위 유지) |
브라우저가 종료되기 전까지 |
ServletContext | 서블릿 컨테이너와 서블릿 사이를 연결 모든 서블릿 사이에서 데이터 공유가 가능 (웹앱 단위 유지) |
서버가 종료되기 전까지 / 해당 웹앱 서버에서 종료되기 전까지 |
- SetAttrServlet
@WebServlet("/set")
public class SetAttrServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String ctxM = "context에 바인딩";
String sesM = "session에 바인딩";
String reqM = "request에 바인딩";
ServletContext ctx = request.getServletContext();
HttpSession ses = request.getSession();
ctx.setAttribute("context", ctxM+"<br>");
ses.setAttribute("session", sesM+"<br>");
request.setAttribute("request", reqM+"<br>");
out.print("바인딩 수행");
}
}
- GetAttrServlet
@WebServlet("/get")
public class GetAttrServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
ServletContext ctx = getServletContext();
HttpSession ses = request.getSession();
String ctxM = (String) ctx.getAttribute("context");
String sesM = (String) ses.getAttribute("session");
String reqM = (String) request.getAttribute("request");
out.print("context 값 : "+ctxM);
out.print("session 값 : "+sesM);
out.print("request 값 : "+reqM);
}
}
//
context 값 : context에 바인딩
session 값 : session에 바인딩
request 값 : null
//다른 브라우저 방문 시
context 값 : context에 바인딩
session 값 : null
request 값 : null
JSP
html, css, javascript 기반으로 jsp 요소 사용
서블릿 : 자바 코드 안에 html, css, javascript 코드 작성, 화면 구현
=> 코드 작성 불편하여 jsp 탄생하게 됨
- 동작 과정
컨테이너(웹서버) => JSP 파일을 java 파일로 변환 -> class 파일로 컴파일
class 파일 실행 -> 브라우저에 결과 전송
- 주석
<%-- --%>
※ JSP 프로젝트 시에도 build path - servlet.api 추가해야 함
memberVO, memberDAO 등 db 연결은 서블릿 활용해야 하기 때문
- first.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>첫번째 JSP</title>
<style></style>
<script></script>
</head>
<body>
<h1>쇼핑몰</h1>
<p>환영합니다</p>
</body>
</html>
=> C:\server\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\jsp01\org\apache\jsp
java, class 파일 확인됨
- include 디렉티브 태그
: jsp 파일 안에 다른 jsp 포함 => 재사용성 ↑
공통으로 사용하는 jsp 페이지를 다른 jsp 페이지에 추가 (공통 메뉴)
<%@ include file="공통기능.jsp" %>
- second.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>두번째 jsp</title>
</head>
<body>
<h1>어린이들이 좋아하는 쇼핑몰</h1>
<%@ include file="img_inc.jsp" %>
<p>페이지 끝</p>
</body>
</html>
- img_inc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>곰돌이</title>
</head>
<body>
<img src="./images/pf.png" alt="곰돌이">
</body>
</html>
- JSP 스크립트 요소 (JSP 페이지 내 자바코드 구현 방법)
1. 스크립트릿(scriptlet) <% %> => 순수 자바 코드
2. 선언문 <%! %> => 변수/메소드 선언
3. 표현식 <%=변수 %> => jsp에서 변수 값 출력 / 태그 안에 작성 가능
- third.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!
String name="홍길동";
public String getName(){
return name;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jsp 스크립트 요소</title>
</head>
<body>
<h1>안녕하세요 <%=name %>님</h1>
<p><%= getName() %>님 반갑습니다</p>
</body>
</html>
//
안녕하세요 홍길동님
홍길동님 반갑습니다
- 로그인
- login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 창</title>
</head>
<body>
<form action="sLogin.jsp" method="get" name="formLogin">
<label for="user_id">아이디 : </label>
<input type="text" id="user_id" name="user_id"><br>
<label for="user_pw">비밀번호 : </label>
<input type="text" id="user_pw" name="user_pw"><br>
<input type="submit" value="로그인"></button>
<input type="reset" value="다시 입력"></button>
</form>
</body>
</html>
- sLogin.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String id = request.getParameter("user_id");
String pw = request.getParameter("user_pw");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>아이디 : <%=id %></h2>
<h2>비밀번호 : <%=pw %></h2>
</body>
</html>
- info.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!
String name="이영희";
String height="175cm";
%>
<%
String age=request.getParameter("age");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>신상정보 출력</title>
</head>
<body>
<h1>신상 정보 출력</h1>
<h2>이름 : <%=name %></h2>
<h2>나이 : <%=Integer.parseInt(age)+10 %></h2> <!--age 문자열이므로 정수로 변환-->
<h2>키 : <%=height %></h2>
</body>
</html>
=> http://localhost:8080/jsp01/info.jsp?age=35
//
신상 정보 출력
이름 : 이영희
나이 : 45
키 : 175cm
getSession() 하기 전부터 jsessionid가 있는 건 뭘까..? 세션 객체가 생성되어야 고유아이디 부여되는 걸로 알고 있었는데..?
'Programming > 국비학원' 카테고리의 다른 글
221005 - JSP - 예외 처리, welcome 페이지, 액션 태그 (0) | 2022.10.06 |
---|---|
220930 - JSP - 스크립트릿, 스코프(Scope) (0) | 2022.10.01 |
220928 - 서블릿 - 쿠키, 세션 (0) | 2022.09.29 |
220927 - 서블릿 - 서블릿 확장 API (ServletContext 클래스), 쿠키, 세션 (0) | 2022.09.28 |
220926 - 서블릿 -커넥션 풀, 서블릿 확장 API (포워드 / 바인딩) (0) | 2022.09.27 |