공통객체: request, session, application, pageContext
제일 많이 사용되는 객체 : session
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Request Example1</h1>
<FORM METHOD="get" ACTION="request1.jsp">
성명 : <INPUT NAME="name" value="홍길동"><br/>
학번 : <INPUT NAME="studentNum" value="20173053"><br/>
성별 : 남자 <INPUT TYPE="radio" NAME="gender" VALUE="man" checked>
여자 <INPUT TYPE="radio" NAME="gender" VALUE="woman"><br/>
전공 : <SELECT NAME="major">
<OPTION SELECTED VALUE="국문학과">국문학과</OPTION>
<OPTION VALUE="영문학과">영문학과</OPTION>
<OPTION VALUE="수학과">수학과</OPTION>
<OPTION VALUE="정치학과">정치학과</OPTION>
<OPTION VALUE="체육학과">체육학과</OPTION>
</SELECT><br/>
취미 : 인터넷<input type="checkbox" checked name="hobby" value="인터넷">
여행<input type="checkbox" name="hobby" value="여행">
게임<input type="checkbox" name="hobby" value="게임">
영화<input type="checkbox" name="hobby" value="영화">
운동<input type="checkbox" name="hobby" value="운동"><br/>
<INPUT TYPE="submit" value="보내기">
</FORM>
</body>
</html>
<!-- ch07/request1.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
// name, studentNum, gender, major
// hobby
String name = request.getParameter("name");
String studentNum = request.getParameter("studentNum");
String gender = request.getParameter("gender");
String major = request.getParameter("major");
//String test = request.getParameter("test");
String []hobby = request.getParameterValues("hobby");
%>
name: <%=name%><br>
studentNum: <%=studentNum%><br>
gender: <%=gender%><br>
major: <%=major%><br>
hobby: <%
for(int i=0;i<hobby.length;i++){
out.println(hobby[i]+" ");
}
%>
<%--=name.length()%><br>
<%--=test.length()--%>
<!-- ch07/request2.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
String protocol = request.getProtocol();
int port = request.getServerPort();
// ip값
String remoteAddr = request.getRemoteAddr();
String uri = request.getRequestURI();
StringBuffer url = request.getRequestURL();
// ? 이후에 요청 조건값
String query = request.getQueryString();
%>
protocol: <%=protocol%><br>
port: <%=port%><br>
remoteAddr: <%=remoteAddr%><br>
uri: <%=uri%><br>
url: <%=url%><br>
query: <%=query%><br>
-Djava.net.preferIPv4Stack=true 추가하기
실행시 다음과 같이 addr 정보가 나옴.
<!-- 07/response1.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
response.sendRedirect("response2.jsp");
%>
<!-- ch07/response2.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
if (request.getProtocol().equals("HTTP/1.1"))
response.setHeader("Cache-Control", "no-cache");
%>
reponse2.jsp입니다.
실행시 로그인정보같은 중요한 정보가 캐시 메모리에 저장이 되지 않는다.
<!-- ch07/location1.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<script>
alert("반갑습니다.");
location.href = "location2.jsp";
</script>
<!-- ch07/location2.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
location2.jsp입니다.
<!-- ch07/out1.jsp -->
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@page contentType="text/html; charset=UTF-8"
buffer="5kb"
%>
<%
int totalBuffer = out.getBufferSize();
int remainBuffer = out.getRemaining();
int useBuffer = totalBuffer - remainBuffer;
out.print("출력 버퍼의 전체크기 : " + totalBuffer + "bytes<br>");
out.println("남은 버퍼의 전체크기 : " + remainBuffer + "bytes<br>");
out.println("사용 버퍼의 전체크기 : " + useBuffer + "bytes<br>");
String arr[] = {"Java","JSP","Android","Spring"};
for(int i=0;i<arr.length;i++){
out.println(arr[i] +"<br>");
}
%>
<%for(int i=0;i<arr.length;i++){%>
<%=arr[i]%><br>
<%}%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>Session Example1</h1>
<form method="post" action="session1.jsp">
아이디 : <input name="id"><p>
비밀번호 : <input type="password" name="pwd"><p/>
<input type="submit" value="로그인">
</form>
</body>
</html>
<%@page contentType="text/html; charset=UTF-8"%>
<%
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
// 세션에 idkey라는 이름으로 id를 저장
session.setAttribute("idKey", id);
session.setMaxInactiveInterval(60*3); // 3분
%>
<h1>Session Example1</h1>
<form method="post" action="session1_1.jsp">
1.가장 좋아하는 계절은?<br/>
<input type="radio" name="season" value="봄">봄
<input type="radio" name="season" value="여름">여름
<input type="radio" name="season" value="가을">가을
<input type="radio" name="season" value="겨울">겨울<p/>
2.가장 좋아하는 과일은?<br/>
<input type="radio" name="fruit" value="watermelon">수박
<input type="radio" name="fruit" value="melon">멜론
<input type="radio" name="fruit" value="apple">사과
<input type="radio" name="fruit" value="orange">오렌지<p/>
<input type="submit" value="결과보기">
</form>
<!-- ch07/session1_1.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
String season = request.getParameter("season");
String fruit = request.getParameter("fruit");
String id = (String)session.getAttribute("idKey");
int intervalTime = session.getMaxInactiveInterval();
if(id!=null){
%>
<b><%=id%></b>님이 좋아하는 계절과 과일은<p>
<b><%=season%></b>과 <b><%=fruit%></b>입니다.<p>
세션ID : <%=session.getId()%><br>
세션 유지 시간 : <%=intervalTime%>초
<%
}else{
out.println("세션의 시간이 경과를 하였거나 다른 이유로 연결을 할 수가 없습니다.");
}
%>
공유의 목적으로 사용하는 것이 session
빈관련 태그
<jsp:useBean id="..."class="..."scope="..."/> -> 빈 생성
<jsp:setProperty name="..."property="..."value="..."/> -> 빈 값을 저장
<jsp:getProperty name="..."property="..."/> -> 빈 값을 가져옴
getter setter 생성
package ch09;
public class SimpleBean {
private String msg;
private int cnt;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
}
<simpleBean.html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function send() {
//alert(1);
f = document.frm;
//f = document.forms[0];
f.action = "simpleBean2.jsp";
f.submit();
}
</script>
</head>
<body>
<h1>빈즈 액션 태그 Example</h1>
<form name="frm" action="simpleBean1.jsp">
msg : <input name="msg" value="빈을 만들자."><br/>
cnt : <input name="cnt" value="10"><br/>
<input type="submit" value="Send1">
<!-- button type은 반드시 onclick 실행 -->
<input type="button" value="Send2" onclick="send()">
</form>
</body>
</html>
<simpleBean1.jsp>
<!-- ch09/SimpleBean.jsp -->
<%@page import="ch09.SimpleBean"%>
<%@page contentType="text/html; charset=UTF-8"%>
<%
SimpleBean bean = new SimpleBean();
String msg = request.getParameter("msg");
int cnt = Integer.parseInt(request.getParameter("cnt"));
// 넘겨받은 값들을 Beans에 저장 why -> DB연동을 위해서
bean.setMsg(msg);
bean.setCnt(cnt);
%>
msg:<%=bean.getMsg()%><br>
cnt:<%=bean.getCnt()%><br>
<simpleBean2.jsp>
<!-- ch09/simpleBean2.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="bean" class="ch09.SimpleBean"/>
<!--jsp:setProperty property="msg" name="bean"/-->
<!--jsp:setProperty property="cnt" name="bean"/-->
<!-- property="*" 는 모든 변수를 선언하다와 같은 뜻 -->
<jsp:setProperty property="*" name="bean"/>
<h3>SimplBean2</h3>
msg : <%=bean.getMsg()%><br>
cnt : <%=bean.getCnt()%><br>
msg : <jsp:getProperty property="msg" name="bean"/><br>
cnt : <jsp:getProperty property="cnt" name="bean"/><br>
<결과>
Send1 일 경우
Send2 일 경우
<TeamBean.java>
package ch09;
public class TeamBean {
private int num;
private String name;
private String city;
private int age;
private String team;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
}
<team.html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function send(){
f = document.frm;
f.action = "team.jsp";
f.submit();
}
</script>
</head>
<body>
<h1> team 액션 태그 Example</h1>
<form name="frm">
num : <input name="num" value=10><br/>
name : <input name="name" value="홍길동"><br/>
city : <input name="city" value="부산"><br/>
age : <input name="age" value=26><br/>
team : <input name="team" value="A팀"><br/>
<input type="button" value="Send1" onclick="send()">
</form>
</body>
</html>
<team.jsp>
<!-- ch09/team.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="bean" class="ch09.TeamBean"/>
<jsp:setProperty property="*" name="bean"/>
<h3>TeamBean</h3>
num : <%=bean.getNum()%><br>
name : <%=bean.getName()%><br>
city : <%=bean.getCity()%><br>
age : <%=bean.getAge()%><br>
team : <%=bean.getTeam()%><br>
num : <jsp:getProperty property="num" name="bean"/><br>
name : <jsp:getProperty property="name" name="bean"/><br>
city : <jsp:getProperty property="city" name="bean"/><br>
age : <jsp:getProperty property="age" name="bean"/><br>
team : <jsp:getProperty property="team" name="bean"/><br>
일반적으로 getProperty 방식보다 bean.get..() 방식으로 많이씀.
<결과>
mydb2 생성
create table tblTeam(
num int primary key auto_increment,
name char(10) not null,
city char(10) not null,
age int default 0,
team char(10) not null
);
mydb2 에 위 테이블 생성
다음과 같이 테이블 데이터 넣기
ch09 에 DBConnectioonMgr.java 파일 넣기
TeamMgr.java 생성
<TeamMgr.java>
package ch09;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
public class TeamMgr {
private DBConnectionMgr pool;
public TeamMgr() {
pool = DBConnectionMgr.getInstance();
}
// 리스트
public Vector<TeamBean> listTeam(){
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
Vector<TeamBean> vlist = new Vector<TeamBean>();
try {
con = pool.getConnection();
sql = "select * from tblTeam";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
TeamBean bean = new TeamBean();
bean.setNum(rs.getInt("num"));
bean.setName(rs.getString("name"));
bean.setCity(rs.getString("city"));
bean.setAge(rs.getInt("age"));
bean.setTeam(rs.getString("team"));
vlist.addElement(bean);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return vlist;
}
}
코드 삽입
jar 파일 넣기
teamList.jsp 생성
<teamList.jsp>
<!-- ch09/teamList.jsp -->
<%@page import="ch09.TeamBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="mgr" class="ch09.TeamMgr"/>
<%
Vector<TeamBean> vlist = mgr.listTeam();
//out.println(vlist.size());
%>
<div align="center">
<h1>Team List</h1>
<table border="1">
<tr>
<th>번호</th>
<th>이름</th>
<th>사는곳</th>
<th>나이</th>
<th>팀명</th>
</tr>
<%
for(int i=0;i<vlist.size();i++){
TeamBean bean = vlist.get(i);
%>
<tr align="center">
<td><%=bean.getNum()%></td>
<td><%=bean.getName()%></td>
<td><%=bean.getCity()%></td>
<td><%=bean.getAge()%></td>
<td><%=bean.getTeam()%></td>
</tr>
<%
} //-for
%>
</table>
</div>
코드 삽입후 실행
<결과>