Servlet이란?
자바 웹 어플리케이션 구성요소 중 동적인 처리를 하는 프로그램의 역할
Servlet은 자바의 클래스이다.
서블릿을 사용하려면 HttpServlet클래스를 상속받아야한다.
Edwith 참고 >
https://www.edwith.org/boostcourse-web/lecture/16686/
Servlet의 LifeCycle
package net.control;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LifeCycle extends HttpServlet {
/*
web.xml에 LifeCycle서블릿 등록
결과확인
http://localhost:8090/mvcTest/life.do
class GenericServlet{}
class HttpServelt extends GenericServlet{}
HttpServelt 생명주기----------------------
init() 서블릿이 시작되면 한번만 호출
> service() 사용자가 요청할 때마다 호출
> destroy() 서버가 중지되면 한번만 호출
------------------------------------------
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// method=get방식 요청이 들어오면
super.doGet(req, resp);
System.out.println("doGet()호출...");
}//doGet() end
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// method=post방식 요청이 들어오면
super.doPost(req, resp);
System.out.println("doPost()호출...");
}//doPost() end
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
//method=get방식으로 요청되면 doGet() 호출
//method=post방식으로 요청되면 doPost()를
//구분해서 호출하는 역할
super.service(arg0, arg1);
System.out.println("service()호출...");
}//service() end
@Override
public void destroy() {
//서버가 중지되면 1번만 자동 호출
super.destroy();
System.out.println("destroy()호출...");
}//destroy() end
@Override
public void init() throws ServletException {
//서블릿이 최초로 호출될때 1번만 자동 호출
//초기환경 구축할때 사용
super.init();
System.out.println("init()호출...");
}//init() end
}//class end
로그인세션 구현하기
기능(control)단과 뷰(view)단을 분리한 방법이다. MVC 패턴 참고
기능단
1) loginForm.java
package net.control;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginForm extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*// TODO Auto-generated method stub
//1) 단순 경로이동하는 방법.
resp.sendRedirect("control/loginForm.jsp");*/
//2) RequestDispatcher를 통해 경로이동, 원래 폴더 경로가 나오지 않는다.
String view = "control/loginForm.jsp";
RequestDispatcher rd = req.getRequestDispatcher(view);
rd.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
//결과확인
//http://localhost:8090/MVCTest/login.do
}
2) loginProc.java
package net.control;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginProc extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
//1) 한글 인코딩.
resp.setCharacterEncoding("UTF-8");
//2) 사용자가 요청한 정보를 변수에 옮겨담기.
String uid = req.getParameter("uid").trim();
String upw = req.getParameter("upw").trim();
//*공유공간* request, session, application
//Session 객체선언
HttpSession session = req.getSession();
//Application 객체 선언
ServletContext application = req.getServletContext();
if(uid.equals("skyhigh") && upw.equals("1234")) {
req.setAttribute("r_uid", uid);
req.setAttribute("r_upw", upw);
session.setAttribute("s_uid", uid);
session.setAttribute("s_upw", upw);
application.setAttribute("a_uid", uid);
application.setAttribute("a_upw", upw);
req.setAttribute("msg", "로그인성공!!");
req.setAttribute("img", "<img src='control/checked.png' width=30>");
} else {
//로그인 실패시
req.setAttribute("r_uid", "guest");
req.setAttribute("r_upw", "guest");
session.setAttribute("s_uid", "guest");
session.setAttribute("s_upw", "guest");
application.setAttribute("a_uid", "guest");
application.setAttribute("a_upw", "guest");
req.setAttribute("msg", "로그인실패!!");
req.setAttribute("img", "<img src='control/report.png' width=30>");
}
//뷰페이지 이동
String view = "control/loginResult.jsp";
RequestDispatcher rd = req.getRequestDispatcher(view);
rd.forward(req, resp);
} catch(Exception e) {
System.out.println("요청실패" + e);
}
}
}
뷰단
1) loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h2>Login</h2>
<form name="loginfrm"
method="post"
action="loginProc.do"
onsubmit="return loginCheck(this)">
<table class="table">
<tr>
<th>아이디</th>
<td><input type="text" name="uid" size="10" placeholder="아이디를 입력하세요."
required class="form-control" ></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="upw" size="30" placeholder="비밀번호를 입력하세요."
required class="form-control"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="로그인" class="btn btn-primary">
<input type="reset" value="취소" class="btn btn-outline-secondary">
</td>
</tr>
</table>
</form>
2) loginResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>Login Result</title>
</head>
<body>
<h1>로그인 결과</h1>
<strong>1) JSP</strong>
<hr>
메세지: <%=request.getAttribute("msg")%><br>
이미지: <%=request.getAttribute("img")%>
<hr>
아이디: <%=request.getAttribute("r_uid")%><br>
비밀번호: <%=request.getAttribute("r_upw")%>
<hr>
아이디: <%=session.getAttribute("s_uid")%><br>
비밀번호: <%=session.getAttribute("s_upw")%>
<hr>
아이디: <%=application.getAttribute("a_uid")%><br>
비밀번호: <%=application.getAttribute("a_upw")%>
<hr>
</body>
</html>
'Backend' 카테고리의 다른 글
10월 02일 수 | JSP 19 - MyController (0) | 2019.10.02 |
---|---|
10월 01일 월 | JSP 18 - Servlet , EL (0) | 2019.10.01 |
09월 23일 월 | JSP 16 - JSP 미니 프로젝트 Ⅰ- cafe24 호스팅 (0) | 2019.09.23 |
09월 19일 목 | JSP 15 - JSP 미니 프로젝트 Ⅰ- 호스팅, 갤러리 (0) | 2019.09.19 |
09월 11일 수 | JSP 13 - JSP 미니 프로젝트 Ⅰ- 로그인 (0) | 2019.09.11 |
댓글