SSENI's
search
sseni
말하는 감자에서 자라기
Today
Yesterday
[웹서버프로그래밍] 2022.04.05 JSP 내장객체(2), 핸들러 함수, 데이터 입력 여부 검사
# config 내장객체
- 서블릿이 최초로 메모리에 적재될 때 컨테이너는 서블릿 초기화와 관련된 정보를 읽고 javax.servlet.ServletConfig 객체에 저장
- web.xml 에 설정된 초기화 파라미터를 참조하기 위한 용도로 사용할 수 있음

# application 내장객체
- 웹 어플리케이션 (컨텍스트) 전체를 관리하는 객체
- config 객체를 통해 생성
- 톰캣의 시작과 종료 라이프사이클을 가짐
개발자를 위한 서버 정보 >

서버 자원 정보 >


로그 관련 정보 >

속성 관련 정보 >

** setAttribute(String name, Object value), getAttribute(String name), removeAttribute(String name) 중요
[실습1] application 내장객체의 활용
- application.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><TITLE> </TITLE></HEAD>
<BODY>
<div align="center">
<H2>ch06 :application 테스트</H2>
<HR>
1. 서버정보 : <%= application.getServerInfo() %> <BR>
2. 서블릿 API 버전정보 : <%= application.getMajorVersion() +"."+application.getMinorVersion() %> <BR>
3. application.jsp 화일의 실제경로 :<%= application.getRealPath("application.jsp") %> <BR>
<HR>
setAttribute 로 username 변수에 "홍길동" 설정<P>
<% application.setAttribute("username","홍길동");
application.log("username=홍길동");
application.setAttribute("count", 1) ;
%>
<a href="application_result.jsp">확인하기</a>
</div>
</BODY>
</HTML>
- application_result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE> </TITLE></HEAD>
<BODY>
<div align="center">
<H2>application 예제</H2>
<HR>
username 에 설정된 값은 : <%= application.getAttribute("username") %> <P>
<%
Integer count = (Integer)application.getAttribute("count");
int cnt = count.intValue()+1;
application.setAttribute("count",cnt);
%>
count : <%= cnt %>
</div>
</BODY>
</HTML>



# page 내장객체
- jsp 컨테이너에서 생성된 서블릿 인스턴스 객체를 참조하는 참조 변수
- jsp에서는 자기 자신을 참조할 때 사용
- page 참조 변수는 거의 사용하지 않음 (자바가 스크립트언어기 때문에)
# pageContext 내장객체
- 다른 모든 내장객체에 대한 프로그램적인 접근 방법 제공
- 많이 사용 ? HTTP 요청을 처리하는 제어권을 다른 페이지로 넘길 때 사용 (forward 액션과 동일한 기능 제공)

페이지 전달 관련 메서드 >

forward 메서드 : pageContext.forward("Helloworld.jsp")
forward 액션 : <jsp:forward page="Helloworld.jsp" />
include 메서드 : out.flush(); pageContext.include("Helloworld.jsp");
include 액션 : <jsp:include page="Helloworld.jsp" flush=true />
# exception 내장객체
- page 지시어에서 오류 페이지로 지정된 jsp 페이지에서 예외가 발생할 때 전달되는 java.lang.Throwable의 인스턴스에 대한 참조 변수
- 현재 페이지를 처리하다 발생하는 예외 상황에 대한 정보를 가져올 수 있음

# HTTP 프로토콜 특징과 내장객체 속성 관리
- jsp 는 HTTP 프로토콜의 사용하는 웹 환경에서 구동되는 프로그램
- ex. 게시판에 글을 작성하는 페이지에서 작성한 내용은 다른 jsp에서 처리해야 하고 서버는 방금 글을 작성한 사람이 누구인지 모를 수 있음
- page, request, session, application 내장객체를 통해 서로 다른 페이지에서 처리된 값을 저장하고 공유하기 위한 방법을 제공

1. application은 모든 사용자가 공유하는 데이터를 저장할 수 있으며 톰캣이 종료될 때까지 데이터를 유지할 수 있음
2. session의 경우 사용자마다 분리된 저장 영역이 있으며 page1,2,3 모두에서 공유되는 정보를 관리할 수 있음 (이 데이터는 각자 공유 영역에서 관리되며 사용자 간 공유되지 않음)
3. 페이지 흐름이 page1,2,3 순으로 진행된다고 할 때, 한 페이지에서 다른 페이지로 데이터를 전달하려면 request 내장객체를 이용해야 함 (page 마다 생성됨)
++ 각각의 내장객체는 모두 getAttribute(), setAttribute() 메서드를 통해 속성을 저장하거나 가져올 수 있음

# request, session, application을 이용한 속성 관리
- 맵 형태의 속성 관리 기능 제공
- 속성 저장 시 setAttribute(String name, Object value) 형태를 취함
- getAttribute(String name) 메서드는 name에 해당하는 Object를 리턴 (속성을 가져올 때 적절한 형 편환 필요)
# MVC 패턴과 JSP 내장객체
- Model, View, Controller 세가지 역할로 구분해 구현하는 소프트웨어 디자인 패턴
- 뷰를 효과적으로 구성하는 방법 : <jsp:useBean>, <jsp:getProperty>, 표현식, 표현 언어 (Expression Language) 와 JSTL을 이용할 경우
[실습2] 세션을 이용한 장바구니 구현
로그인 -> 상품 선택 -> 주문 -> 주문한 상품목록 나타남
- login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch06 : login.jsp</title>
</head>
<body>
<div align="center">
<H2>로그인</H2>
<form name="form1" method="POST" action="selProduct.jsp">
<input type="text" name="username"/>
<input type="submit" value="로그인"/>
</form>
</div>
</body>
</html>
- selProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<title>ch06 : selProduct.jsp</title>
</head>
<%
request.setCharacterEncoding("UTF-8"); // euc-kr
session.setAttribute("username",request.getParameter("username"));
%>
<body>
<div align="center">
<H2>상품선택</H2>
<HR>
<%=session.getAttribute("username") %>님 환영합니다!!!!
<HR>
<form name="form1" method="POST" action="add.jsp">
<SELECT name="product">
<option>사과</option>
<option>귤</option>
<option>파인애플</option>
<option>자몽</option>
<option>레몬</option>
</SELECT>
<input type="submit" value="추가"/>
</form>
<a href="checkOut.jsp">계산</a>
</div>
</body>
</html>
- add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch05 : add.jsp</title>
</HEAD>
<body>
<%
request.setCharacterEncoding("UTF-8");
String productname = request.getParameter("product");
ArrayList<String> list = (ArrayList)session.getAttribute("productlist");
if(list == null) {
list = new ArrayList<String>();
session.setAttribute("productlist",list);
}
list.add(productname);
%>
<script>
alert("<%=productname %> 이(가)추가 되었습니다.!!");
history.go(-1);
</script>
</body>
</html>
- checkOut.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ch06 : checkOut.jsp</title>
</HEAD>
<body>
<div align="center">
<H2>계산</H2>
선택한 상품 목록
<HR>
<%
ArrayList list = (ArrayList)session.getAttribute("productlist");
if(list == null) {
out.println("선택한 상품이 없습니다.!!!");
}
else {
for(Object productname:list) {
out.println(productname+"<BR>");
}
}
%>
</div>
</body>
</html>




[실습3] 트위터 구현
- twitter_login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch06 : twitter_login.jsp</title>
</head>
<body>
<div align="center">
<H2>트위터 로그인</H2>
<form name="form1" method="POST" action="twitter_list.jsp">
<input type="text" name="username"/>
<input type="submit" value="로그인"/>
</form>
</div>
</body>
</html>
- twitter_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
// 한글 캐릭터셋 변환
request.setCharacterEncoding("UTF-8");
// HTML 폼에서 username으로 전달된 값을 가지고 옴
String username = request.getParameter("username");
// username이 null 이 아닌 경우 세션에 값을 저장
if(username != null) {
session.setAttribute("user",username);
}
%>
<html>
<head>
<title>ch06 : twitter_list.jsp</title>
</head>
<body>
<div align=center>
<H3>My Simple Twitter!!</H3>
<HR>
<form action="tweet.jsp" method="POST">
<!-- 세션에 저장된 이름 출력 -->
@<%=session.getAttribute("user") %> <input type="text" name="msg"><input type="submit" value="Tweet">
</form>
<HR>
<div align="left">
<UL>
<%
// application 내장객체를 통해 msgs 이름으로 저장된 ArrayList를 가지고 옴
ArrayList<String>msgs = (ArrayList<String>)application.getAttribute("msgs");
//msgs가 null 이 아닌 경우에만 목록 출력
if(msgs != null) {
for(String msg : msgs) {
out.println("<LI>"+msg+"</LI>");
}
}
%>
</UL>
</div>
</div>
</body>
</html>
- tweet.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*, java.text.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
// 한글 캐릭터셋 변환
request.setCharacterEncoding("UTF-8");
// HTML 폼에서 전달된 msg 값을 가지고 옴
String msg = request.getParameter("msg");
// 세션에 저장된 로그인 사용자 이름을 가지고 옴
Object username = session.getAttribute("user");
// 메시지 저장을 위해 application 에서 msgs 로 저장된 ArrayList 가지고 옴
ArrayList<String> msgs = (ArrayList<String>)application.getAttribute("msgs");
// null 인 경우 새로운 ArrayList 객체를 생성
if(msgs == null) {
msgs = new ArrayList<String>();
// application 에 ArrayList 저장
application.setAttribute("msgs",msgs);
}
// 사용자 이름, 메시지, 날짜 정보를 포함하여 ArrayList에 추가
Date date = new Date();
SimpleDateFormat f = new SimpleDateFormat("E MMM dd HH:mm", Locale.KOREA);
msgs.add(username+" :: "+msg+" , "+ f.format(date));
// 톰캣 콘솔을 통한 로깅
application.log(msg+"추가됨");
// 목록 화면으로 리다이렉팅
response.sendRedirect("twitter_list.jsp");
%>


# 핸들러 함수

# 데이터 입력 여부 검사

true 이면 입력되지 않았다 (** == 써줘야 함)


# 데이터 길이 검사





# 데이터가 숫자인지 판별






# 정규 표현식


| [웹서버프로그래밍] 2022.03.30 Assign 03 (0) | 2022.04.11 |
|---|---|
| [웹서버프로그래밍] 2022.03.23 Assign 02 (0) | 2022.04.05 |
| [웹서버프로그래밍] 2022.03.29 JAVA Applet, JSP 내장객체 (0) | 2022.03.29 |
| [웹서버프로그래밍] 2022.03.22 JSP 지시어, 액션, 스크립트릿 (0) | 2022.03.22 |
| [웹서버프로그래밍] 2022.03.17 Assign 01 (0) | 2022.03.17 |