사용자에게 여러 행을 보여줘야 할 때 for문을 씀
--html파일
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>if-else example</h1>
<form method="post" action="05.2.if.jsp">
이름: <input name="name"></p> <!-- <br>대신에 </p> 써도 됨 -->
좋아하는 색상:
<select name="color">
<option value="blue">파란색</option>
<option value="red">빨간색</option>
<option value="yellow">노란색</option>
<option value="etc">기타</option>
</select></p>
<input type="submit" value="보내기">
</form>
</body>
</html>
--jsp파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!
String msg;
%>
<%
request.setCharacterEncoding("utf-8"); //한글설정
String name = request.getParameter("name");//value값을 name이란 변수 공간에 저장
String color = request.getParameter("color");
switch(color) {
case "blue" :
msg = "파란색";
break;
case "red" :
msg = "빨간색";
break;
case "yellow" :
msg = "노란색";
break;
default :
msg = "기타";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body bgcolor="<%=color %>"> <!-- 배경색 지정인 bgcolor는 예전식 -->
<b><%=name %></b>님이 좋아하는 색상은 <b><%=msg %></b>입니다
</body>
</html>
<%--
if(color.equals("blue")) { (color=="blue"이렇게 쓰면 String이라 주소값이 같은지 보기 때문에 equals)
msg = "파란색";
} else if(color.equals("red")) {
msg = "빨간색";
} else if(color.equals("yellow")) {
msg = "노란색";
} else {
msg = "기타";
}
--%>
프로그램을 하면서 브라우저로 출력하려면
방법1) out.print(출력할 구문); ★방법2) 중간을 끊어 html로 넣어줌: html구문이 많을 경우 <% 프로그램 하다가 %> html 구문 작성 <% 프로그램 이어서 작성 %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>for Ex</h1>
<!-- 1~10까지의 합 -->
<%
int sum = 0;
for(int i=1; i<=10; i++) {
sum += i;
}
%>
1부터 10까지의 합: <%=sum %></p>
<!-- 방법1) 1+2+3+4+..+10 = 55 처럼 출력되게 하기 -->
<%
int sum2 = 0;
for(int i=1; i<=10; i++) {
if(i <= 9)
out.print(i + " + ");
else
out.print(i + " = ");
sum2 += i;
}
%>
<%=sum2 %></p>
<!-- 방법2) 끊었다가 작성할 경우 if,for 등에 한 줄이어도 반드시 중괄호{}삽입 -->
<%
int sum3 = 0;
for(int i=1; i<=10; i++) {
if(i<=9) {
%>
<%=(i + " + ") %>
<%
} else {
%>
<%=(i + " = ") %>
<%
}
sum3 += i;
}
%>
<%=sum3 %></p>
<!-- 배열로 표현 -->
<%
int[] arr = new int[10];
int sum4 = 0;
for(int i=0; i<arr.length; i++) {
arr[i] = i+1;
%>
<%=arr[i] + " " %>
<%
sum4 += arr[i];
}
%>
= <%=sum4 %></p>
</body>
</html>
--html파일
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="07.2.while.jsp">
반복하고 싶은 문구: <input name="msg" size="50"><br>
반복하고 싶은 횟수: <input name="count"><br>
<input type="submit" value="전송">
</form>
</body>
</html>
-jsp파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String msg = request.getParameter("msg");
int count = Integer.parseInt(request.getParameter("count"));
int i = 1;
while(count >= i) {
%>
<%=i + "." + msg %><br>
<%
i++;
}
%>
</body>
</html>
1) page 지시자: JSP 페이지에 지원되는 속성을 정의
2) include 지시자: 별도의 파일을 JSP파일에 삽입
3) taglib 지시자: JSP에서 지원하지 않는 부분들을 사용자가 직접 작성하여 그 태그를 호출해 사용
- language: 현재 페이지에서 사용할 언어
- contentType: jsp페이지의 내용을 어떤 형태로 출력할 것인지 MIME형식으로 브라우저에 알려주는 역할
MIME 형식: text/gif, text/xml, text/plain ...
- pageEncoding: 페이지의 문자 인코딩 값
- info: 현재 페이지를 설명해주는 문자열
- session(기본값 true): HTTPSession을 사용할지 여부
true이면 세션 유지, false이면 세션 연결되지 않음
기본값이 true이기 때문에 특수하게 false를 쓰려는 것 아닌 이상 명시 안 함
ex) 쇼핑몰 페이지에서 내가 골라둔 물건들을 기억하여 다른 때에 홈페이지에 들어가도 그대로 설정되어 있는 것
- buffer(기본값 8kb): 출력크기를 kb단위로 지정, 내용들을 모아둠
- autoFlush(기본값 true): 버퍼가 다 찼을 때 저장된 내용들을 어떻게 처리할 것인지
true는 가득차면 자동으로 비움, false는 작업중지(예외발생)
- ★import: 다른 class API를 사용하려할 때 import후 사용
- extends: 다른 class를 상속받아 사용할 때
- trimDirective Whitespaces: 글자의 맨 앞과 맨 뒤의 공백 제거
- ★errorPage: 사용자 정의로 error페이지를 별도로 만들어 사용할 때
ㄴ isErrorPage: errorPage를 사용할 경우 반드시 isErrorPage로 에러 페이지임을 표시
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page info = "JSP 현재 페이지 정보" session = "false" buffer="16kb"
autoFlush = "true" import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Page 지시자 info</h1>
<%=this.getServletInfo() %>
<h1>Page 지시자 import</h1>
<%
Date date = new Date();
%>
현재 시간과 날짜 ? <%= date.toLocaleString() %>
</body>
</html>
페이지 소스를 보면 사용자가 넣은 page지시자 때문에 행의 여백이 생겨버림
이럴 때 trimDirective Whitespaces 지시자 사용
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page info = "JSP 현재 페이지 정보" %>
<%@ page session = "false"%>
<%@ page buffer="16kb"%>
<%@ page autoFlush = "true"%>
<%@ page import="java.util.*" %>
<%@ page trimDirectiveWhitespaces = "true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Page 지시자 info</h1>
<%=this.getServletInfo() %>
<h1>Page 지시자 import</h1>
<%
Date date = new Date();
%>
현재 시간과 날짜 ? <%= date.toLocaleString() %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" errorPage="userErrorPage.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int zero = 0, one = 2;
%>
<h1>Page ErrorPage</h1>
zero와 one의 사칙연산<p/> <!-- 열면서 동시에 닫을 땐 슬래시 오른쪽에 -->
one+zero=<%=one+zero %><p/>
one-zero=<%=one-zero %><p/>
one*zero=<%=one*zero %><p/>
one/zero=<%=one/zero %><p/>
</body>
</html>
--isErrorPage를 사용하여 에러 페이지임을 보이기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Error Page</h1>
다음과 같은 예외가 발생하였습니다<p/>
<%-- 직접 0으로 나눠서 오류났다고 써도 됨
에러메시지: 연산은 0으로 나눌 수 없습니다.
--%>
에러타입: <%=exception.getClass().getName() %><p/>
에러메시지: <%=exception.getMessage() %>
</body>
</html>
다른 파일(jsp, html)을 포함시켜 모든 페이지를 하나로 합쳐서 컴파일하여 보여줌
[표현법]
<%@ include file = "포함시킬 파일명" %>
--include body파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ include file="04.2.page_include_Top.jsp" %><br>
<hr>
include 지시자의 body부분입니다<br>
<hr>
<%@ include file="04.3.page_include_Bottom.jsp" %>
</body>
</html>
--include Top파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
include지시자의 Top부분입니다
</body>
</html>
--include Bottom파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
include지시자의 Bottom부분입니다
</body>
</html>
여러 개의 페이지가 하나로 컴파일 됨
action태그에도 include가 존재
그러나 동작이 include 지시자와는 조금 차이가 있음
include 지시자는 body+Top+Bottom이 하나로 합쳐진다면
Action Tag의 include는 합쳐지는 것이 아닌 그저 거쳐가서 페이지가 응답되는 것임
--html파일(첫번째)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="05.2.action_includeTag.jsp">
이름: <input name = "name"><p/>
<input type="submit" value="보내기">
</form>
</body>
</html>
--두번째jsp파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name = "집에가고싶어요 간절히";
%>
include ActionTag의 Body입니다<br>
<%=name %>
<hr>
<jsp:include page = "05.3.action_includeTag.jsp"></jsp:include><br>
<!-- <jsp:include page = "05.3.action_includeTag.jsp"/><br> 중간에 쓸 것이 없다면 그냥 닫아줘도 됨-->
</body>
</html>
--세번째jsp파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("name");
%>
include ActionTag의 3번째 파일 입니다<br>
<%=name %> Fighting!!!
</body>
</html>
Action Tag의 include는 page_include와 달리 하나로 합쳐지는 것이 아닌, 페이지에 지정한 경로 순서대로 끼워넣어지는 식
파라미터 구문으로 안 받고 바로 변수로 넘겨줬기 때문에 변수 값들이 다음 페이지 파일로 넘어갈 수 있음(jsp:include 태그로 page 경로설정)
--html파일(첫번째)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="06.2.action_includeTagParam2.jsp">
siteName : <input name="siteName"><br>
siteTel : <input name="siteTel"><br>
<input type="submit" value="보내기">
</form>
</body>
</html>
--두번째 jsp파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String siteName = request.getParameter("siteName");
String siteTel = request.getParameter("siteTel");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Include ActionTag Parameter</h1>
<jsp:include page="06.3.action_includeTagParam.jsp">
<jsp:param value="JSP 수업" name="siteName"/>
<jsp:param value="010-1234-5678" name="siteTel"/>
</jsp:include>
<hr>
include ActionTag의 body입니다<br>
사이트 이름: <%=siteName %><br>
사이트 전환: <%=siteTel %><br>
</body>
</html>
--세번째 jsp파일
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String siteName = request.getParameter("siteName");
String siteTel = request.getParameter("siteTel");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
include ActionTag의 3번째 페이지<br>
사이트명: <%=siteName %><br>
사이트 Tel: <%=siteTel %>
</body>
</html>
3번째 페이지의 출력 내용은 파라미터 태그로 넘겨준 값들(page의 경로를 3번째로 해놓음),
body부분의 출력 내용은 두번째 jsp파일에서 html문단 위에 스크립트릿 태그의 리퀘스트로 사용자에게 값을 받아서 넘겨준 값들
중간에서 파라미터에서 새롭게 정의한 값을 받았기 때문에 3번째 페이지의 파일로 리퀘스트로 받은 변수 값이 안 넘어옴
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
//리퀘스트로 받은 값, 파라미터값 없는 것으로 복사수정함!!
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Include ActionTag Parameter</h1>
<jsp:include page="06.3.action_includeTagParam.jsp"/>
<hr>
include ActionTag의 body입니다<br>
</body>
</html>
파라미터로 값을 안 받는 경우는 바로 사용자로부터 받은 변수 값이 넘어오게 됨
그래서 3번째 페이지의 출력내용이 파라미터 태그가 있는 경우와 달라짐
윗문단의 action_includeTag 코드들과 같음
파라미터를 써서 중간에서 변수 값들(이 코드에선 String으로 선언된 siteName, siteTel)을 받으면 원래는 변수값들이 넘어가지 않고 jsp:param 구문에 내가 직접 넣은 값들만 들어가게 되는데,
jsp:param 구문에 <%= 으로 변수를 직접 넣어주게되면 결국 변수의 값들이 넘어갈 수 있게 됨
포워드는 중간 파일 페이지 값들 안 보여주고(include는 중간 페이지 값도 보여줌) 곧바로 원하는 페이지만 보여줌
--html파일
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="07.2.action_forward.jsp">
ID: <input name ="id"><p/>
PW: <input type="password" name="pwd"><p/>
<input type="submit" value="전송">
</form>
</body>
</html>
--페이지1
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
//여기서 값을 받지 않아도 거쳐가기 때문에 한글이 깨질 수 있어 인코딩 해줘야함
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>ForwardTag</h1>
ForwardTag의 포워딩 되기전의 페이지 입니다<br>
<!-- include같은 경우 위의 두 줄이 보이게 됨 -->
<jsp:forward page="07.3.action_forward.jsp"></jsp:forward>
</body>
</html>
--페이지2
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>ForwardTag 마지막 페이지</h1>
당신의 아이디는 <b><%=id %></b>이고<br>
비밀번호는 <b><%=pwd %></b>입니다.
</body>
</html>
forwarding 전의 중간 페이지(페이지1)는 건너뛰므로 출력되지 않음
<h1>ForwardTag</h1>
ForwardTag의 포워딩 되기전의 페이지 입니다<br>
이 출력문들이 나왔어야했는데 안 나옴!
아이디와 비밀번호가 맞지 않으면 나올 페이지와
맞게 입력했을 때 보여줘야할 페이지 2개가 구성되어있기 때문에
forward 기능을 사용하여 어느 페이지를 보여줄 건지 지정하면 됨