### --------------------------
### Web Application
### --------------------------
## Servlet
-- 역할: Controller
-- 요청 ~ 응답 제어
1. 요청파악: 로그인, 로그아웃, 전체조회, 내정보조회, 아이디찾기 등
=> html, jsp
=> <form>
<input type="text" name="memberId">
</form>
2. 요청데이터 추출: 요청객체(HttpServletRequest request)
=> 요청객체에 한글 인코딩 설정: request.setCharacterEncoding("utf-8");
=> request.getParameter("memberId"): String
=> request.getParameterValues("xxx"): String[]
=> ...
3. 데이터 검증(validation)
4. Model 요청 의뢰(검증받은 사용자 입력데이터)
=> Model : Service 클래스 (업무로직/서비스로직)
=> Model : DAO 클래스(DB관련 CRUD)
=> Model : DTO 클래스(도메인 데이터)
5. Model로 부터 요청에 대한 응답결과를 받아서 응답을 위한 설정
=> request.setAttriubute("key", Object) : 요청~응답 scope
=> sessiong.setAttriubute("key", Object) : 로그인~로그아웃 scope
6. 응답페이지 이동
=> forward : 기존 요청객체에 설정된 정보를가지고 이동
=> redirect: 새로운 요청으로 페이지 이동(기존 정보는 사라짐)
## JSP Tag
-- 역할: 화면처리(View)
-- <% %>
1. comment tag
>> <!-- html comment -->
>> <% // 한줄 자바 주석 %>, <% /* 여러줄 자바 주석 */ %>
>> <%-- jsp 주석 --%>
2. diretive tag
<%@ page %>
=> contentType
=> import
=> errorPage, isError
<%@ include %>
=> file
<%@ taglib %>
=> 의존관계 jstl.jar : pom.xml
=> prefix, uri
3. declaration tag
<%! 멤버변수 선언; 메서드 선언; 라이프사이클메서드재정의; %>
4. expression tag:
<%= 값 %>
값을 출력하는 서비스
vaule, 변수명, 결과값을반환하는메서드호출(), 수식, new 클래스이름()
out.write(값); => out.write(값;);
주의사항!!! : ";" 세미콜론이 와서는 안됨
=> _jspService() {} 서비스 수행코드로 변환 태그
5. scriptlet tag
<% 자바 서비스 수행코드; %>
=> _jspService() {} 서비스 수행코드로 변환 태그
## 라이프 사이클
-- Servlet 라이프 사이클
1. public void init() : 초기화, 서비스 시작전에 호출
2. public void destroy() : 자원해제(서비스 종료시, 기존서비스 변경시 호출)
3. 서비스 메서드
public void service(ServletRequest, ServletResponse)
public void service(HttpServletRequest, HttpServletResponse)
public void doGet(HttpServletRequest, HttpServletResponse)
public void doPost(HttpServletRequest, HttpServletResponse)
-- JSP 라이프 사이클
1. jspInit()
2. jspDestroy()
3. _jspServic()
=> <%= %>, <% %> 태그로 작성된 서비스 코드로 자동 변환 구현
## JSP 내장객체
-- <%= %>, <% %> 태그로 작성된 서비스 코드로 자동 변환시에 제공되는 내장객체
-- _jspServic() 메서드 내부에 선언된 지역변수
-- <%= %>, <% %> 태그 내부에서만 사용가능함
-- request : HttpServletRequest (요청객체)
-- response : HttpServletResponse (응답객체)
-- session : HttpSession (세션객체)
-- out : JspWriter (출력스트림)
-- application : ServletContext
>> 웹어플리케이션환경객체
>> 해당 웹어플리케이션에 있는 모든 서블릿(jsp) 공유가능한 객체
## 경로 설정
1. 절대경로
http://ip:port/contextPath/resource
-- 서버 ip
-- 서버 port
-- 서버 배포된 contextPath(웹어플리케이션 배포이름)
2. contextPath
/contextPath/resource
-- 서버 배포된 contextPath(웹어플리케이션 배포이름)
-- "contextPath" 하드 코딩하지 않고 동적으로 가져와서 사용가능함
<c:set var="root" value="${pageContext.request.contextPath}" />
3. url-pattern
url-pattern
-- 현재 브라우저 url 기준으로 상대경로 lookup
-- include(조각페이지), sub-folder로 자원 분리한 경우에 경로 설정 불편
## JSP 페이지 자원에 대한 경로 설정하기
-- 사전 설정: contextPath 설정하기: /MMS02
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core">
<c:set var="root" value="${pageContext.request.contextPath}" />
1. css
<link href="${root}/assets/css/common.css" rel="stylesheet">
2. javascript
<script src="${root}/assets/js/common.js" type="text/javascript"></script>
3. image
<img src="${root}/assets/img/logon.png">
4. <a href="${root}/member/memberInpus.jsp">회원가입</a>
5. 조각페이지 삽입
<!-- footer.jsp 조각페이지 삽입 : 경로설정시에 자동으로 현재 컨텍스트패스를 기준으로 상대경로로 지정됨, 컨텍스트패스 표기해서는 안됨 -->
<%@ include file="/include/footer.jsp" %>
6. <form method="post" action="${root}/controller">
## servlet 에서 응답페이지 경로 설정하기
1. forward
-- 현재 컨텍스트패스가 자동으로 설정되어서, 현재 컨텍스트패스를 기준으로 상대경로 지정함
-- 즉, 컨텍스트패스가 들어가서는 안됨
request.getRequestDispatcher("/sub-folder/memberList.jsp").forward(request, response);
request.getRequestDispatcher("/index.jsp").forward(request, response);
2. redirect:
response.sendRedirect(root + "/sub-folder/file.jsp");
## EL/JSTL
-- JSTL 의존관계 라이브러리 가져오기 : pom.xml
-- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"> : jsp 지시어태그 선언
-- 변수선언
<c:set var="" value="" />
-- 조건비교
<c:if test="조건">....</c:if>
-- 출력
<c:out value="" default="" />
## EL(Expression Language)
${expression}
## 조각페이지
1. <%@ include file="조각페이지url" %>
2. <jsp:include page="조각페이지url" />
3. <jsp:include page="조각페이지url">
<jsp:param name="변수명" value="값" />
<jsp:include>
-- test.jsp : 조각페이지 삽입 사용하기
<!-- footer.jsp 조각페이지 삽입 : 경로설정시에 자동으로 현재 컨텍스트패스를 기준으로 상대경로로 지정됨, 컨텍스트패스 표기해서는 안됨 -->
<%@ include file="/include/footer.jsp" %>
<jsp:include page="/include/footer.jsp" />
<jsp:include page="/include/footer.jsp">
<jsp:param name="phone" value="1577-7878" />
</jsp:include>
-- footer.jsp(조각페이지)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<footer>
© 2022. SSAFY8<br>
<c:if test="${not empty param.phone}">
${param.phone}
</c:if>
<c:if test="${empty param.phone}">
1234-1234
</c:if>
<br>
<c:choose>
<c:when test="${!empty param.phone}">${param.phone}</c:when>
<c:otherwise>1234-1234</c:otherwise>
</c:choose>
<br>
<c:out value="${param.phone}" default="1234-1234" />
</footer>
</body>
</html>
## 세션
-- 로그인 ~ 로그아웃
-- 로그인 ~ 타임아웃
-- tomcat\conf\web.xml> 서버 기본설정 30분
<session-config>
<session-timeout>30</session-timeout>
</session-config>
-- tomcat\conf\webapps\contextPath\WEB-INF\web.xml> 해당 컨텍스트 타임아웃 설정
## http 프로토콜 특성
1. connection-less
>> 요청~응답 컨넥션 끊어버림
2. status-less
>> 상태정보 저장되지 않음
## Session Management
-- 세션정보 관리 방법
-- API: javax.servlet.http
1. Cookie
2. HttpSession
3. URL-Rewriting: 실제 프로젝트에서 사용하지 않음
## HttpSession
--세션 정보 서버저장, object,갯수, 타입, 크기 제한없음
-- JSP : 자동으로 내장객체 생성됨
-- 서블릿:
HttpSession session = request.getSession(); // true
HttpSession session = request.getSession(boolean);
>> true
=> 세션이 없으면 : new 세션객체 생성됨
=> 세션이 존재하면: 기존 세션객체 반환
=> 사용자 인증시에 사용
>> false
=> 세션이 없으면 : null 반환
=> 세션이 존재하면: 기존 세션객체 반환
=> 회원전용(사용인증) 서비스 이용시 사용
=> jsp 페이지 이동시에 자동으로 무조건 세션객체 생성이 되므로
=> 세션유무를 가지고 사용자 인증여부체킹하지말고
=> 인증시에 설정해놓은 속성(attribute)을 통해서 인증 여부 체킹
##cookie
--상태정보 사용자 시스템, 문자열 가능, 크기 제한, 갯수 제한
1,생성 : cookie(java.lang.String name, java.lang.String value)
Cookie c1 = new Cookie("memberId", memberid);
Cookie c2 = enw Cookie("grade", grade);
2, 상태정보 추가 : HttpServletResponse\addCookie(Cookie cookie)
response.addCookie(c1);
response.addCookie(c2);
3, 응답데이터와 함께 전송
응답시에 데이터 + 쿠키 전송
4, 재요청 시에 cookie 정보 가져오기 : HttpServletRequest#getCookies() : Cookie[]
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie c : cookies){
String name = c.getName();
String value = c.getValue();
}
}
'Web' 카테고리의 다른 글
[backend]월말평가대비 servlet API (0) | 2022.09.30 |
---|---|
[WEB] 예외처리 (0) | 2022.09.22 |
[WEB]JSP,EL,JSTL (0) | 2022.09.20 |
[WEB]JDBC (0) | 2022.09.20 |
[Backend-web]JSP (0) | 2022.09.15 |