JSP 내부 객체
개발자가 객체를 생성하지 않고 바로 사용할 수 있는 객체가 내부객체이다.
JSP 에서 제공되는 내부객체는 JSP 컨테이너에 의해 Servlet으로 변화될 때 자동으로 객체가 생성된다.
- 입출력 객체 : request, response, out
- 서블릿 객체 : page, config
- 세션 객체 : session
- 예외 객체 : exception
✅ request 객체의 이해
웹 브라우저를 통해 서버에 어떤 정보를 요청하는 것을 request라고 한다. 그리고 이러한 요청 정보는 request 객체가 관리한다.
Request 객체 관련 메소드
- getContextPath() : 웹 어플리케이션의 컨텍스트 패스를 얻음
- getMethod() : get 방식과 post 방식을 구분할 수 있다
- getSession : 세션 객체를 얻는다
- getProtocol() : 해당 프로토콜을 얻는다
- getRequestURL() : 요청 URL을 얻는다
- getRequestURI() : 요청 URI를 얻는다
- getQueryString() : 쿼리스트링을 얻는다
- Parameter 메소드
- getParameter(String name) : name 에 해당하는 파라미터 값을 구함
- getParameterNames() : 모든 파라미터 이름을 구함
- getParameterValues(String name) : name에 해당하는 파라미터값들을 구함
✅ response 객체의 이해
웹 브라우저의 요청에 응답하는 것을 response라고 하며, 이러한 응답(response)의 정보를 가지고 있는 객체를 response객체라고 함
Response관련 메소드
- getCharacterEncodinng() : 응답할 때 문자의 인코딩 현태를 구함
- addCookie(Cookie) : 쿠키를 지정함
- sendRedirect(URL) : 지정한 URL로 이동함, 특정상황에 조건에 따라 원하는 페이지로 이동하게 함(로그인 시 비회원이면 회원가입페이지로…)
| request 객체
웹 브라우저의 요청 정보를 저장하고 있는 객체
메소드
getHeader(): 요청 정보의 헤더를 반환
getMethod(): 요청 정보의 http method(get, post) 반환
getParameter(): 요청 정보의 이름(name)으로 요청 값(value)을 반환
getParameterValues(): 요청 정보의 이름으로 요청 값을 배열로 반환
setCharacterEncoding(): 요청 정보의 인코딩을 설정
| response 객체
:웹 브라우저의 요청에 대한 응답 정보를 저장하고 있는 객체
쿠키(cookie)
- 서버가 생성해서 클라이언트에게 던짐!
- 클라이언트는 쿠키 받을때마다 쿠키를 축적
- 클라이언트에 정보를 저장
- 클라이언트에만 저장하므로 서버의 부하를 줄일 수 있지만 보안상 취약
- 데이터의 저장이 1.2MB로 제한
- 텍스트 데이터만 저장
쿠키를 생성하는 방법
Cookie 객체명 = new Cookie("name","value"); 키(name)와 값(value)으로 저장되는 맵구조로 저장됨
쿠키 시간 설정
setMaxAge(): 쿠키가 유지되는 시간을 설정(초)
setMaxAge(60 * 60 * 24 * 30); // 30일
쿠키를 클라이언트에게 전달하는 방법
response.addCookie(쿠키객체);
http 통신은 클라이언트가 서버에 접속해서 html을 요청하면
서버가 응답하고(html을 던져주고) 연결이 끝이남!
이때 html 던져줄때 쿠키도 같이담아서 보내려고
response.addCookie하는것임!
+http통신이 왜 단방향인지가 궁금하다면...
쿠키의 value 값에 띄어쓰기를 포함한 문자열을 넣으면 에러가날경우!
<%@ page import="java.net.URLEncoder" %>
java.net.URLEncoder를 import해주고
쿠키객체 만들시 value값에는
<%
Cookie cookie1 = new Cookie("userid",URLEncoder.encode("app le","UTF-8"));
%>
이렇게
URLEncoder.encode("value","UTF-8")넣어줘야함
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.net.URLEncoder" %>
<%
Cookie cookie1 = new Cookie("userid",URLEncoder.encode("app le","UTF-8")); //띄어쓰기가 포함되어있을때 이렇게작
Cookie cookie2 = new Cookie("name","김사"); //쿠키name과 쿠키value
cookie1.setMaxAge(180); //쿠키시간설정
cookie2.setMaxAge(100);
response.addCookie(cookie1); //쿠키전송 response.addCookie(쿠키객체)
response.addCookie(cookie2);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>쿠키</h2>
<p>쿠키가정상적으로 설정되었습니다.</p>
</body>
</html>
브라우저에서 쿠키확인하기
크롬 f12 - application -storage-cookies-서버주소
들어가면 확인가능
쿠키를 서버에서 읽어오는 방법(사용자가 가지고있는 쿠키가 여러개일수있어서 배열로 받음)
Cookie[] 배열명 = request.getCookies();
System.out.println() => 콘솔출력
out.println() => html출력
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
//쿠기가 쌓여서 여러개일경우 getCookies는 쿠키타입의 배열을 전달
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>쿠키 읽기</h2>
<%
for(Cookie cookie : cookies){
out.println(cookie.getName() + " : " + cookie.getValue() + "<br>");
//getName()과 getValue()는 문자열 반환
}
%>
</body>
</html>
| 간단한 로그인 기능 구현
| 순서
1.login.jsp
로그인페이지라 html문서도 존재
✦로그인한 기록이 있어서 계정정보쿠키가 존재할경우
=> 환영페이지
- 로그아웃버튼을 누를경우 logout 페이지로 이동
✦쿠키가 존재하지않을경우
=>로그인페이지
- 로그인페이지에서 로그인버튼을 누르면
- 입력한 정보들이 login_ok 에 파라미터로 전달
전체코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
String userid = null;
if(cookies != null){
for(Cookie cookie : cookies){
if("userid".equals(cookie.getName())){
userid = cookie.getValue();
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키로 구현한 로그인</title>
</head>
<body>
<h2> 쿠키로 구현한 로그인</h2>
<%
if(userid ==null){
%>
<form method="post" action="3_login_ok.jsp"><!-- // 이게 중엔 서블릿(자바만있)걸로바뀜 jsp는 html까지 같이있는거라 느려터짐 -->
<p>아이디: <input type = "text" name = "userid"></p>
<p>비밀번호: <input type = "password" name = "userpw"></p>
<p><button>로그인</button></p>
</form>
<%
}else{
%>
<h3><%=userid%>님 환영합니다 !!!!</h3>
<p><a href="3_logout.jsp"> 로그아웃 </a></p>
<!-- 쿠키를 삭제하는법 기존의 같은객체이름으로 만들어서 덮어씌우는방법 -->
<%
}
%>
</body>
</html>
2.login_ok.jsp
로그인유효한지 확인하는페이지라 html문서 필요없음
login.jsp의 로그인폼에서 전송한 value 값들을 파라미터로 받게 되는데
request.getParameter("name")를 하면
태그의 name속성값을 통해 구별하여 value값들을 반환해줌
<p>아이디: <input type = "text" name = "userid"></p>
그 후 서버에서 지정한 아이디와 비밀번호 값이 일치한다면
아이디 값을 담은 쿠키객체를 만들어서 response.addCookie로 쿠기를 전송해줌
쿠키수명도 지정해주면 좋다 10분정도?
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw"); //name값으로 인식
if(userid.equals("apple") && userpw.equals("1234")){
// 로그인 성공!
Cookie cookie = new Cookie("userid",userid);
cookie.setMaxAge(60*10);
response.addCookie(cookie);
%>
60초 * 10 = 10분
location.href 와 history.back()의 차이
- location.href
refresh(새로고침)해서 이동하는거라
캐쉬값이 남아있지않음
-history.back()
저장되어있는 캐쉬값을 통해 앞으로갔다가 뒤로갔다가하는것이기 때문에
다시페이지로 돌아갔을때 적었던 값이 남아있음
서버에서 지정한 계정
아이디: apple 비밀번호: 1234
<refresh일때> //예시를 위해 로그인시 보이는 html제거
<history.back()일때>
전체코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw"); //name값으로 인식
if(userid.equals("apple") && userpw.equals("1234")){
// 로그인 성공!
Cookie cookie = new Cookie("userid",userid);
cookie.setMaxAge(60*10);
response.addCookie(cookie);
%>
<script>
alert('로그인 되었습니다');
location.href="3_login.jsp" //refresh가됨 새로고침이되는것임
</script>
<%
}else{
// 로그인 실패!
%>
<script>
alert('아이디 또는 비밀번호를 확인하세요');
history.back(); // 캐쉬가남음 캐쉬에 있는 정보를 가져다가 앞으로갓다가 뒤로갓다가 할수있는것이라서
</script>
<%
}
//열고닫고 이런식으로 이어서 쓰기 가능한데 더럽다 코드가 그래서 요새 jsp잘안쓴다
%>
3.logout.jsp
얘도 html문서는 필요없음
✷쿠키를 지우는 방법
지우는 메소드는 따로 없다!....
대신 지우고싶은 쿠키의 name값과 동일한 빈 value값의 쿠키객체를 새로생성해주고
수명을 0초로 설정한 후 덮어씌운다!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if("userid".equals(cookie.getName())){
Cookie newCookie = new Cookie("userid", ""); //이름은같게,value는 비워서 덮어씌우기
newCookie.setMaxAge(0);//시간을 0으로 설정해버리기
response.addCookie(newCookie);
}
}
}
%>
<script>
alert('logout되었습니다');
location.href='3_login.jsp';
</script>
| 세션(session)객체
- 서버에 사용자 정보를 저장
- 서버상에 존재하는 객체로 브라우저 단위당 1개씩 존재
- 쿠키에 비해 보안이 좋음
- 웹브라우저를 닫기 전까지 유지
한 사용자에 대한 세션아이디를 발급
그이후에 사용자쪽으로 쿠기에 세션아이디를 넣어서 던져쥼
- 일정시간 지나면 소멸
- 수명 기본값은 서버프로그램에 존재
- 톰캣같은경우 web.xml파일에 30분으로 기본설정되어있음
http 통신은 요청하고 받으면 통신끝
tcp/ip 통신은 요청하고도 계속 연결을 이어감
+http통신이 왜 단방향인지가 궁금하다면...
http통신은 단방향통신이라 사용자로부터 요청받고
응답해주면 연결이 끊기는데!!
이 연결을 유지해주는 기능을 하는것이 바로 세션!
세션은 톰캣이나 서버 프로그램에서 자동생성!
jsp메모리에 객체로 존재!
객체생성없이 바로 사용가능!
그래서 자동으로만들어진 세션에
속성추가하는 방향으로 사용해야함!
세션변수 만들기 & 세션아이디 불러오기
session.getId();
: 처음 서버접속시 자동생성된 session
session.setAttribute("속성명","값");
: 그 세션아이디에 속성들을 덧붙여가는 느낌으로 속성(세션변수)추가!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.setAttribute("userid","apple");
//jsp엔진에는 메모리에 session이 객체로 존재해서 객체 생성없이 바로 사용가능
//AF98FB9172D6F55276C7366A86BB8728 -> userid(apple) 세션 밑으로 속성이 만들어짐
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션</title>
</head>
<body>
<h2>세션</h2>
<p>sessionID : <%= session.getId()%> </p>
</body>
</html>
세션변수값 읽어오기
session.getAttribute("속성명");
: 반환타입은 세션타입이기때문에 (String)으로 형변환해줘야함
<%@ page language="java" contentType="text/html; charset=UTF-8";
pageEncoding="UTF-8"%>
<%
String userid = null;
if(session.getAttribute("userid") != null){
userid = (String)session.getAttribute("userid");
}else{
userid = "아이디없음";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>reading session</title>
</head>
<body>
<h2>reading session</h2>
<p>session id: <%=session.getId()%></p>
<p>session variable(id): <%=userid%></p>
</body>
</html>
세션변수 삭제하기
session.invalidate();
:세션 삭제! 쿠키는 삭제가없고 덮어씌우고해야하는 귀찮음그자체였는데
세션은 삭제가 존재해서 very 씸쁠
<%
session.invalidate();
%>
세션 아이디 시간설정
- 톰켓 web.xml (분단위 세션 시간을 설정)
<session-config>
<session-timeout>30</session-timeout>
</session-config>
| 세션을 이용한 간단한 로그인 구현
| 순서
1.login.sjp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = null;
if(session.getAttribute("userid") != null){
userid = (String)session.getAttribute("userid");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션으로 구현한 로그인</title>
</head>
<body>
<h2> 세션으로 구현한 로그인</h2>
<%
if(userid == null){
%>
<form method="post" action="6_login_ok.jsp"><!-- // 이게 중엔 서블릿(자바만있)걸로바뀜 jsp는 html까지 같이있는거라 느려터짐 -->
<p>아이디: <input type = "text" name = "userid"></p>
<p>비밀번호: <input type = "password" name = "userpw"></p>
<p><button>로그인</button></p>
</form>
<%
}else{
%>
<h3><%=userid%>님 환영합니다 !!!!</h3>
<p><a href="6_logout.jsp"> 로그아웃 </a></p>
<%
}
%>
</body>
</html>
2.login_ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw"); //name값으로 찾음
if(userid.equals("apple") && userpw.equals("1234")){
// 로그인 성공!
session.setAttribute("userid",userid);
%>
<script>
alert('로그인 되었습니다');
location.href="6_login.jsp" //refresh가됨 새로고침이되는것임
</script>
<%
}else{
// 로그인 실패!
%>
<script>
alert('아이디 또는 비밀번호를 확인하세요');
history.back(); // 캐쉬가남음 캐쉬에 있는 정보를 가져다가 앞으로갓다가 뒤로갓다가 할수있는것이라서
</script>
<%
}
//열고닫고 이런식으로 이어서 쓰기 가능한데 더럽다 코드가 그래서 요새 jsp잘안쓴다
%>
3.logout.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate();
%>
<script>
alert('logout되었습니다');
location.href='6_login.jsp';
</script>
| 세션을 이용한 장바구니 구현
결제를 안하면 뒤로돌아가기
결제를 하면 세션삭제
| 순서
1.basket.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션으로 구현한 장바구니</title>
<script>
function payment(){
alert('결제페이지로 이동합니다');
location.href='7_basket_payment.jsp'
}
</script>
</head>
<body>
<h2>세션으로 구현한 장바구니</h2>
<form method="post" action="7_basket_ok.jsp">
<p>구입할 물건을 선택하세요 :
<select name="product">
<option value="그래픽카드">그래픽카드</option>
<option value="닌텐도">닌텐도</option>
<option value="맥북프로">맥북프로</option>
<option value="모니터">모니터</option>
<option value="페라리">페라리</option>
<option value="집">집</option>
</select>
</p>
<p><input type="submit" value="담기"> | <input type="button" value="결제" onclick="payment()"></p>
</form>
<hr>
<p>
<%
List<String> list = (List)session.getAttribute("productList");
if(list != null){
for(String product : list){
out.print(product+" ");
}
}
%>
</p>
</body>
</html>
2.basket_ok // 담기를 눌렀을때
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%
request.setCharacterEncoding("UTF-8"); //set 이지만 request객체라는거!!
//String product = request.getParameter("product");
String product = request.getParameter("product") == null ? "" : request.getParameter("product");
//삼항연산자사용. 만약 넘어온 값이 없다면 "" 를 대입하는데
//이 예제에서는 항상 목록 기본값이 그래픽카드로 되어있기때문에 삼항연산자 쓸 필요까지는 없음...
List list = (List)session.getAttribute("productList");
if(list == null){
list = new ArrayList();
}
list.add(product);
session.setAttribute("productList", list);
%>
<script>
alert('<%=product%>상품이 장바구니에 추가되었습니다');
location.href='7_basket.jsp';
</script>
3.basket_payment.jsp //결제 눌렀을때
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%
int sum =0;
List<String> list = (List)session.getAttribute("productList");
if(list != null){
for(String product : list){
if("그래픽카드".equals(product)){
sum += 1300000;
}else if("닌텐도".equals(product)){
sum += 400000;
}else if("맥북프로".equals(product)){
sum += 3800000;
}else if("모니터".equals(product)){
sum += 500000;
}else if("페라리".equals(product)){
sum += 320000000;
}else if("집".equals(product)){
sum += 800000000;
}
}
%>
<script>
if(confirm('<%=sum%>원을 결제하시겠습니까?')){
alert('결제가 성공적으로 완료되었습니다.\n장바구니를 초기화합니다');
location.href='7_basket_invalid.jsp';
}else{
alert('돈이 없군요?');
history.back();
}
</script>
<%
}else{
%>
<script>
alert('결제할 상품이 없습니다');
history.back();
</script>
<%
}
%>
4.basket_invalid.jsp //결제하시겠습니까에서 확인을 눌렀을때
- sendRedirect(): 클라이언트를 원하는 페이지로 이동
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate();
response.sendRedirect("7_basket.jsp");
%>
<!--
이렇게 써도 되지만
<script>
location.href="7_basket.jsp"
</script>
-->
| 서블릿(Servlet)
- Dynamic Web Page를 만들때 사용되는 자바 기반의 웹 어플리케이션 프로그래밍 기술
- 웹 요청과 흐름을 간단한 메서드 호출만으로 체계적으로 다룰 수 있게 해주는 기술
서블릿의 특징
- 클라이언트의 Request에 대해 동적으로 작동하는 웹 어플리케이션 컴포넌트
- HTML을 사용하여 Response를 함
- Java의 스레드를 이용하여 동작
- MVC 패턴에서의 컨트롤러로 이용
: MVC: model/ view/ controller 이렇게 나눠서 웹 개발하자~하는 방법론인데
모델은 데이터베이스하고 연동되는 데이터를 담는것을 말함 DTO: db에서 실제 프로세서로 자료를 넘겨줄때 필트있고 게터 셋터 있는놈들
뷰 : 화면만 구성하는 페이지를 따로 구성하자 그건 jsp가대신하고
controller : servlet이 하자 html 없는 로직단!
- HTTP 프로토콜 서비스를 지원하는 javax.servlet.http.HttpServlet 클래스를 상속
- HTML 변경시 Servlet을 재 컴파일해야 하는 단점
src-main-java 안에 파일을 넣어야 컴파일돼서 실행됨
서블릿 컨테이너
- 서블릿을 담고 관리해주는 컨테이너
- HttpServletRequest
request 정보를 서블릿에게 전달하기 위한 목적으로 사용하며 헤더정보, 파라미터, 쿠키, URI, URL 등의 정보를 읽어들이
메소드와 Body의 Stream을 읽어들이는 메서드를 가지고있음
- HttpServletResoponse
WAS는 어떤 클라이언트가 요청을 보냈는지 알고 있고, 해당 클라이언트에게 응답을 보내기 위한 HttpServletResponse
객체를 생성하여 서블릿에게 전달하고 이 객체를 활용하여 content type, 응답코드, 응답 메세지등을 전송
서블릿의 동작 과정
1. Servlet Request, Servlet Response 객체를 생성
2. 설정 파일을 참고하여 매핑할 Servlet을 확인
3. 해당 서블릿 인스턴스 존재의 유무를 확인하여 없으면 init() 메소드를 호출하여 생성
4. Servlet Container에 스레드를 생성하고 service를 실행
5. 응답을 처리했다면 destroy() 메소드를 실행하여 Servlet Request, Servlet Response 객체를 소멸
예제
1.login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = null;
if(session.getAttribute("userid") != null){
userid = (String)session.getAttribute("userid");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>서블릿으로 구현한 로그인</title>
</head>
<body>
<h2> 서블릿으로 구현한 로그인</h2>
<%
if(userid == null){
%>
<form method="post" action="login">
<p>아이디: <input type = "text" name = "userid"></p>
<p>비밀번호: <input type = "password" name = "userpw"></p>
<p><button>로그인</button></p>
</form>
<%
}else{
%>
<h3><%=userid%>님 환영합니다 !!!!</h3>
<p><a href="logout"> 로그아웃 </a></p>
<%
}
%>
</body>
</html>
2.login.java
package com.koreait;
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;
/**
* Servlet implementation class login
*/
@WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("doGet 메소드 호출!");
// }
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//콘텐트 타입은 이렇게해서 보낼게요~
HttpSession session = request.getSession();
PrintWriter writer = response.getWriter();
//객체를 생성하는 이유는
//jsp파일은 내부객체가 존재했지만
//서블릿파일에는 내부객체가 없기때문에
//컴파일시 자동으로 추가되지않으므로 직접 객체를 생성해줘야함
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
System.out.println(userid);
System.out.println(userpw);
if(userid.equals("apple") && userpw.equals("1234")) {
session.setAttribute("userid",userid);
writer.println("<script>alert('로그인되었습니다'); location.href='9_login.jsp';</script>");
//response.sendRedirect("9_login.jsp");
}else {
writer.println("<script>alert('아이디 또는 비밀번호를 확인해주세요'); location.href='9_login.jsp';</script>");
//response.sendRedirect("9_login.jsp");
}
}
}
3.logout.java
package com.koreait;
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;
/**
* Servlet implementation class logout
*/
@WebServlet("/logout")
public class logout extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public logout() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
//로그아웃은 무조건 get으로 타고
//ctrl+shift+o 누르면 자동 import
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
HttpSession session = request.getSession();
session.invalidate();
writer.println("<script>alert('로그아웃되었습니다'); location.href='9_login.jsp';</script>");
response.sendRedirect("9_login.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
'웹 개발 > 🎆 JSP' 카테고리의 다른 글
JSP | JSP를이용한 홈페이지구현 - 게시판 (0) | 2022.11.27 |
---|---|
JSP | JSP를이용한 홈페이지구현 - 세션체크, 회원정보수정 (0) | 2022.11.27 |
JSP | JSP를이용한 홈페이지구현 - 로그인,회원가입,로그아웃 (0) | 2022.11.27 |
JSP | include,exception,pageContext,ajax (0) | 2022.11.21 |
JSP | 디렉티브태그,스크립트릿,표현문,선언문,get,post,getParameter (1) | 2022.11.17 |