Servlet 구조 패턴
1) 파라미터 추출 - DTO 객체 준비
2) 비니지스 로직 실행 - 출력 DTO 객체 ➔ Command pattern으로 추상화
3) 결과를 request scope에 저장
4) forward / redirect ➔ 정형: 추상화
- EL : only 값 출력
- JSTL : 태그를 써서 로직 처리를 지원
- JSP Expression tag
<%=값(request.getAttribute(키))%>➞ 불편하다🤔
⇨ EL이 해결해줌돠
✅ 최종적인 결과가 값 (표현식, Expression) - 이것을 출력하기 위한 언어
✅ JSP에서 변수를 출력할 때 사용
* JavaBean
- 기본 생성자
- 속성(필드, property)은 private으로 선언
- Getter / Setter
- Serializable 인터페이스를 구현
➞ (For 객체를 파일에 저장하거나 네트워크를 통해 전송, 요즘은 필수X)- 주로 데이터 보관 및 전달 목적, 복잡한 비즈니스 로직 포함X
pageScoperequestScopesessionScopeapplicationScope. : 자바빈, Map에 접근[] : 배열, List 접근() : 우선 순위empty : null인지 판단산술, 논리, 비교 연산자~${member.name} member.getName() : 'member' 인스턴스의 'name' property 출력~member.get("name") : 키${member["name"]}member.getName()member.get("name")<%
int age = 10; //지역변수
request.setAttribute("age", 40);
request.setAttribute("agenull", null);
%>
<html>
<head>
<title>Title</title>
</head>
<body>
변수 age : <%=age%> <br>
EL age: ${age} <br>
변수 null : <%=agenull%> <br>
EL null: ${agenull}
</body>
</html>
<%=age%> : 변수 age${age} : scope의 key 명 (scope에서 해당 key를 찾음)Scope
- 키 찾는 순서
: Page < Request < Session < Application
<!--login_form.jsp-->
<form action="login" method="get">
<fieldset>
<legend>로그인 폼</legend>
<ul>
<li>
<label for="userid">아이디</label>
<input type="text" id="userid" name="userid">
</li>
<li>
<label for="passwd">비밀번호</label>
<input type="password" id="passwd" name="passwd">
</li>
<li>
<input type="submit" value="로그인">
</li>
</ul>
</fieldset>
</form>
//LoginServlet
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1) 파라미터 추출
String userid = request.getParameter("userid");
String passwd = request.getParameter("passwd");
// 2) 비지니스 로직 실행 (로그인 체크) - 했다 치고
// 3) 결과 request scope에 저장
request.setAttribute("userid", userid);
request.setAttribute("passwd", passwd);
// 4) forward or redirect
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
<!--login.jsp-->
<body>
사용자 아이디 : ${userid}<br>
사용자 비밀번호 : ${passwd}
</body>
//LoginServlet
LoginDTO loginDTO = new LoginDTO(userid, passwd);
request.setAttribute("login", loginDTO);
//login.jsp
DTO 아이디: ${login.id} <br>
DTO 비밀번호: ${login.passwd}
VO 객체 vs DTO 객체
- VO : 데이터베이스 테이블과 일치시키는 클래스 (DAO에서 사용)
- DTO : 테이블과 상관X, 비니지스 로직을 수행하기 위해 운영하는 객체 (Controller, Service 에서 사용)
//ScopeServlet
@WebServlet("/scope")
public class ScopeServlet extends HttpServlet {
ServletContext sc; //application scope
@Override
public void init(ServletConfig config) throws ServletException {
sc = config.getServletContext();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Application Scope
sc.setAttribute("scopeName", "application scope값");
//Session Scope
HttpSession session = request.getSession();
session.setAttribute("scopeName", "session scope값");
//Request Scope
request.setAttribute("scopeName", "request scope값");
//DTO 캡슐화
Member member = new Member("홍길동", "hong"); // name, userid
request.setAttribute("member", member);
request.getRequestDispatcher("scope.jsp").forward(request, response);
}
}
<!--scope.jsp-->
<body>
<h1>Scope 데이터 보기</h1>
page scope : ${pageScope.scopeName} <br>
request scope : ${requestScope.scopeName} <br>
session scope : ${sessionScope.scopeName} <br>
application scope : ${applicationScope.scopeName}<br>
<br>
\${scopeName} 자동 찾기 : ${scopeName} <br>
VO객체-Member name : ${member.name} <br>
VO객체-Member userid : ${member.userid}
</body>
✅ 로직 처리를 위한 라이브러리
✅ 액션 태그를 사용자가 직접 제작 가능 - 커스텀 태그
✅ 커스텀 태그들 중 자주 사용되는 태그들 묶어서 아파치 그룹에서 제공 ⇨ JSTL
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>out : 지정된 값 출력if <c:if test="조건식" (var="저장할 변수명" scope="저장할 scope")> 문장 </c:if>forEach (ex.목록보기)<c:forEach var="변수명" items="객체명"> 문장 </c:forEach><c=forEach begin="시작인덱스" end="끝인덱스" step="증가값" varStatus="other변수"> 문장 </c:forEach>choose - when - otherwise ≒ switchurl : url 생성forTokens : StringTokenizer 클래스 기능formatNumber<fmt:formatNumber value="값" typ="타입" pattern="패턴" />formatDate<fmt:formatDate value="값" typ="타입" pattern="패턴" /><fmt:formatDate value="${today}" pattern="YYYY-MM-dd a hh:mm:ss"/><br>
<fmt:formatDate value="${today}" pattern="YYYY-MM-dd hh:mm:ss"/><br>
