Employee.java
package web.jdbc.test;

public class Employee {

	private int empno;
	private String ename;
	private int deptno;
	private String hiredate;
	private int sal;
	private int mgr;
	
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public int getSal() {
		return sal;
	}
	public void setSal(int sal) {
		this.sal = sal;
	}
	public int getMgr() {
		return mgr;
	}
	public void setMgr(int mgr) {
		this.mgr = mgr;
	}
	
	
}

EmpDAO.java
package web.jdbc.test;

import java.sql.*;
import java.util.*;

public class EmpDAO {
	// 데이터베이스 연결관련정보를 문자열로 선언
	private String jdbc_driver = "oracle.jdbc.OracleDriver";
	private String db_url = "jdbc:oracle:thin:@211.183.3.5:1521:ORCL";

	private Connection getConn() throws Exception{
		// JDBC 드라이버 로드하여 DriverManager에 등록함
		Class.forName(jdbc_driver);

		// 로드된 드라이버를 이용하여 DB와 연결하고 Connection 인스턴스 구함
		Connection conn = DriverManager.getConnection(db_url,"user05","user05");
		return conn;
	}

	private void closeAll(ResultSet rs, Statement stmt, Connection conn){
		try {
			if(rs!=null)rs.close();
			if(stmt!=null)stmt.close();
			if(conn!=null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public ArrayList<Employee> getAllEmps(){
		String sql ="select * from employee";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			Employee emp = null;
			ArrayList<Employee> list = new ArrayList<Employee>();
			while(rs.next()){
				emp = new Employee();
				emp.setEmpno(rs.getInt("EMPNO"));
				emp.setEname(rs.getString("ENAME"));
				emp.setDeptno(rs.getInt("DEPTNO"));
				list.add(emp);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			closeAll(rs, stmt, conn);
		}
		return null;
	}

	// 사번을 전달받고 데이터베이스를 검색하여 해당 사원의 상세정보를 리턴한다
	// @param empno 검색할 사원의 사번
	// @return Employee 사원의 상세정보를 저장하고 있는 DTO
	public Employee getEmp(int empno){
		String sql = "select * from employee where empno="+empno;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if (rs.next()){
				Employee emp = new Employee();
				emp.setEmpno(rs.getInt("EMPNO"));
				emp.setEname(rs.getString("ENAME"));
				emp.setDeptno(rs.getInt("DEPTNO"));
				emp.setHiredate(rs.getString("HIREDATE"));
				emp.setSal(rs.getInt("SAL"));
				emp.setMgr(rs.getInt("MGR"));
				return emp;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeAll(rs, stmt, conn);
		}
		return null;
	}
}

empDesc.jsp
<%@page import="web.jdbc.test.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="dao" class="web.jdbc.test.EmpDAO"/>
<% 
	int empno = Integer.valueOf(request.getParameter("empno")); 
	Employee emp = dao.getEmp(empno);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
	table {border: 1px solid black;}
	td {text-align: center;}
	th {border: 1px solid black; background-color: green; }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>사원의 상세정보 보기</title>
</head>
<body>
<table>
<tr>
	<td colspan="4"><h1>사번이 <%=empno %>인 사원의 상세정보</h1></td>
</tr>
<tr>
	<td>사번</td><td><%=empno %></td>
	<td>이름</td><td><%=emp.getEname() %></td>
</tr>
<tr>
	<td>부서</td><td><%=emp.getDeptno()%></td>
	<td>입사일</td><td><%=emp.getHiredate()%></td>
</tr>
<tr>
	<td>급여</td><td><%=emp.getSal()%></td>
	<td>매니져</td><td><%=emp.getMgr()%></td>
</tr>
</table>
</body>
</html>
empList.jsp
<%@page import="web.jdbc.test.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="dao" class="web.jdbc.test.EmpDAO"/>
<%
	ArrayList<Employee> list = dao.getAllEmps();
%>

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
	table {border: 1px solid black;}
	td {text-align: center;}
	th {border: 1px solid black; background-color: green; }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>오라클 접속 테스트</title>
</head>
<body>
<table rules="rows">
<tr>
	<th>Empno</th>
	<th>Ename</th>
	<th>Deptno</th>
</tr>
<%
	for(int i=0;i<list.size();i++){
		Employee emp = list.get(i);
		int empno = emp.getEmpno();
		%>
		<tr>
		<td><%=empno %></td> 
		<td><a href="empDesc.jsp?empno=<%=empno%>"><%=emp.getEname() %></a></td> 
		<td><%=emp.getDeptno() %></td>
		</tr>
	<%}
%>
</table>
</body>
</html>






http://dl.dropbox.com/u/92046264/303jsp/


JDBC Test in Oracle


Java 프로그램과 연결할 때 사용할 JDBC Driver는 설치된 Oracle 디렉토리에서 검색해보면 해당 오라클 버전의 JDBC Driver를 찾을 수가 있다. 만약 찾지 못하면 아래에서 다운로드할 수 있다.

ojdbc14.jar


package web.jdbc.test;
import java.sql.*;

public class OracleTest {
	public static void main(String[] args)  {
		// 데이터베이스 연결관련 변수 선언
		Connection conn = null;
		Statement stmt = null;

		// 데이터베이스 연결관련정보를 문자열로 선언
		String jdbc_driver = "oracle.jdbc.OracleDriver";
		String db_url = "jdbc:oracle:thin:@211.183.3.5:1521:ORCL";

		try{
			// JDBC 드라이버 로드하여 DriverManager에 등록함
			Class.forName(jdbc_driver);

			// 로드된 드라이버를 이용하여 DB와 연결하고 Connection 인스턴스 구함
			conn = DriverManager.getConnection(db_url,"user09","user09");

			// Connection 객체로 부터 SQL문 작성을 위한 Statement 준비
			stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery("select * from emp");
			while(rs.next()) {
				System.out.println(rs.getString(1)+" " +rs.getString(2)+" " +rs.getString(3)+" " +rs.getString(4)+" " +rs.getString(5));
			}
			rs.close();
			stmt.close();
			conn.close();
		}
		catch(Exception e) {
			System.out.println(e);
		}
		System.out.println("테스트 끝");
	}
}



오라클 디비랑 잘 연결 되어서 요렇게 출력된다~~







DAO - data access object

DTO - data transfer object

ORM - (Object-relational mapping)








oracleTest.jsp
<%@page import="web.jdbc.test.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="dao" class="web.jdbc.test.EmpDAO"/>
<%
	ArrayList<Employee> list = dao.getAllEmps();
%>
<!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>오라클 접속 테스트</title>
</head>
<body>
<ol>
<%
	for(int i=0;i<list.size();i++){
		Employee emp = list.get(i);%>
		<li><%=emp.getEmpno() %> / <%=emp.getEname() %> / <%=emp.getDeptno() %>
	<%}
%>
</ol>
</body>
</html>
Employee.java
package web.jdbc.test;

public class Employee {
	
	private int empno; //사원번호
	private String ename;//사원이름
	private int deptno;//부서번호
	private String hiredate;//고용날짜
	private int sal;//봉급
	private int mgr;//매니져
	
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String eanme) {
		this.ename = eanme;
	}
	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public int getSal() {
		return sal;
	}
	public void setSal(int sal) {
		this.sal = sal;
	}
	public int getMgr() {
		return mgr;
	}
	public void setMgr(int mgr) {
		this.mgr = mgr;
	}	
}

EmpDAO.java
package web.jdbc.test;

import java.sql.*;
import java.util.ArrayList;

public class EmpDAO {
	// 데이터베이스 연결관련 변수 선언
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;

	// 데이터베이스 연결관련정보를 문자열로 선언
	String jdbc_driver = "oracle.jdbc.OracleDriver";//ojdbc14.jar에 있다.
	String db_url = "jdbc:oracle:thin:@211.183.3.5:1521:ORCL";

	private Connection getConn() throws Exception{

		// JDBC 드라이버 로드하여 DriverManager에 등록함
		Class.forName(jdbc_driver);

		// 로드된 드라이버를 이용하여 DB와 연결하고 Connection 인스턴스 구함
		Connection conn = DriverManager.getConnection(db_url,"user09","user09");
		return conn;
	}

	private void closeAll(ResultSet rs,Statement stmt,Connection conn){
		try{
			if(rs!=null)rs.close();
			if(stmt!=null)stmt.close();
			if(conn!=null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public ArrayList<Employee> getAllEmps(){
		String sql="select * from emp";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs =null;
		try {
			conn = getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			Employee emp = null;
			ArrayList<Employee> list = new ArrayList<Employee>();
			while(rs.next()){
				emp = new Employee();
				emp.setEmpno(rs.getInt("EMPNO"));
				emp.setEname(rs.getString("ENAME"));
				emp.setDeptno(rs.getInt("DEPTNO"));
				list.add(emp);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{//오류와 관련없이 항상 실행
			closeAll(rs,stmt,conn);
		}
		return null;
	}
}



'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습10  (0) 2012.07.17
복습8  (0) 2012.07.13
복습7 회원 정보 저장 폼  (0) 2012.07.12
복습6 Cookie,Session을 이용한 login 처리,자바빈(JavaBeans)  (0) 2012.07.11
복습5 페이지 모듈화,error page,Cookie  (0) 2012.07.10

표현 언어


Expression Language

JSP에서 사용가능한 새로운 스크립트 언어

EL의 주요 기능

JSP의 네 가지 기본 객체가 제공하는 영역의 속성 사용

Collection 객체, 배열에 대한 접근 방법 제공

수치 연산, 관계 연산, 논리 연산자 제공

자바 클래스 메서드 호출 기능 제공

표현언어만의 기본 객체 제공

간단한 구문 때문에 표현식 대신 사용

기본 문법

${expr}, #{expr}

사용예

<jsp:include page="/module/${skin.id}/header.jsp" />

<b>${sessionScope.member.id}</b>님 환영합니다.

${expr}은 표현식이 실행되는 시점에 바로 값 계산

#{expr}은 값이 실제로 필요한 시점에 값 계산

JSP 템플릿 텍스트에서는 사용 불가

스크립트 요소(스크립트릿, 표현식, 선언부)를 제외한 나머지 부분에서 사용




${expr}#{expr}의 동작 방식 예

<% 
    Member m = new Member();
    m.setName("이름1");
%>
<c:set var="m" value="<%= m %>" /><%--선언시의 값을 가짐--%> 

<%-- 이 시점에는 값 생성하지 않음 --%>
<c:set var="name" value="#{m.name}" /><%--현재 값을 가지지 않음--%>

<% m.setName("이름2"); %>

${name} <%-- 사용될 때 값 계산, "이름2" 출력 --%>

<% m.setName("이름3"); %>

${name} <%-- 사용될 때 값 계산, "이름3" 출력 --%>




EL에서 기본 객체





예제
EL은 영역 개체에 있어야 인식한다.
package test.bean;

public class Member {
	
	private String name;
	private String id;
	private String pwd;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	
}

<%@ page import="test.bean.Member" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Member m = new Member();
	m.setId("myID");
	m.setPwd("myPWD");
	m.setName("김연아");
	pageContext.setAttribute("m", m);
%>
<!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></title>
</head>
<body>
회원 이름:[${m.name }]
</body>
</html>
<%@ page import="test.bean.Member" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="m" class="test.bean.Member">
	<jsp:setProperty name="m" property="name" value="김연아"/>
	<jsp:setProperty name="m" property="id" value="myID"/>
	<jsp:setProperty name="m" property="pwd" value="myPWD"/>
</jsp:useBean>    
<%-- <%
	Member m = new Member();
	m.setId("myID");
	m.setPwd("myPWD");
	m.setName("김연아");
	pageContext.setAttribute("m", m);
%> --%>
<!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></title>
</head>
<body>
회원 이름:[${m.name }]
<%=m.getName() %>
</body>
</html>




<%@ page import="test.bean.Member" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String[] name={"강호동","이수근","김종민"};
	pageContext.setAttribute("arr", name);
%>
<!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></title>
</head>
<body>
<%=name[0] %><p/>
${arr[0]}
</body>
</html>


<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("1", "강호동");
	map.put("2", "이수근");
	map.put("three", "김종민");
	pageContext.setAttribute("map", map);
%>
<!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></title>
</head>
<body>
<%=map.get("1") %><p/>
${ map["1"]}<p/>
${ map.three }<!-- map에 영문이 아니면 오류가 난다. -->
</body>
</html>
<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("강호동", "123-12321");
	map.put("이수근", "123-1232-2323");
	map.put("김종민", "234-2343-3242");
	pageContext.setAttribute("map", map);
%>
<!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></title>
</head>
<body>
<%=map.get("김종민") %><p/>
${ map["김종민"]}<p/>
</body>
</html>



session 영역에서 값을 가져와서 nextPage에 출력

<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("강호동", "123-12321");
	map.put("이수근", "123-1232-2323");
	map.put("김종민", "234-2343-3242");
	session.setAttribute("map", map);
%>
<!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></title>
</head>
<body>
<a href="nextPage.jsp">다음페이지로 이동</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>Insert title here</title>
</head>
<body>
&lt연락처&gt <p/>
강호동:${ map["강호동"]}<p/>
이수근:${ map["이수근"]}<p/>
김종민:${ map["김종민"]}<p/>
</body>
</html>


01


<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("강호동", "123-12321");
	map.put("이수근", "123-1232-2323");
	map.put("김종민", "234-2343-3242");
	request.setAttribute("map", map);
%>
<jsp:forward page="nextPage.jsp"/>
<!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></title>
</head>
<body>
<a href="nextPage.jsp">다음페이지로 이동</a>
</body>
</html>




<%@ page import="test.bean.*, java.util.*" %>
<%@ page contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<jsp:useBean id="m" class="test.bean.Member" scope="request">
	<jsp:setProperty name="m" property="name" value="김종민"/>
	<jsp:setProperty name="m" property="id" value="myID"/>
	<jsp:setProperty name="m" property="pwd" value="myPWD"/>
</jsp:useBean>
<jsp:forward page="nextPage.jsp"/>
<!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></title>
</head>
<body>
<a href="nextPage.jsp">다음페이지로 이동</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="m" class="test.bean.Member"/>
<!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>Insert title here</title>
</head>
<body>
${m.name}<p/>
${m.id}<p/>
${m.pwd}<p/>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>브라우저에서 전달된 파라미터</title>
</head>
<body>
아이디 : ${param.id }<br/>
암호 : ${param.pwd }<br/>
</body>
</html>



<jsp:setProperty> 액션 태그

자바빈 객체의 프로퍼티 값 설정

구문

<jsp:setProperty name="id" property="이름" value=""  />

name - 자바빈 객체의 이름

property - 값을 설정할 프로퍼티

value - 프로퍼티의

<jsp:setProperty name="id" property="이름"
   
param="파라미터이름"  />

param - 프로퍼티의 값으로 사용할 파라미터 이름.

<jsp:setProperty name="id" property="*" />

프로퍼티와 동일한 이름의 파라미터를 이용해서 값을 설정

폼에 입력한 값을 자바 객체에 저장할 때 유용하게 사용




예제)



회원 정보 저장 폼



























Cookie 를 이용한 login 처리

cookie01.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Cookie[] cookies = request.getCookies();
	boolean found = false;
	if(cookies==null){
		found=false;
	}else{
	for(int i=0;i<cookies.length;i++){
		if(cookies[i].getName().equals("sampleCookie")){
			found = true;
			}
		}
	}
	String msg = null;
	if( ! found){
		Cookie cookie = new Cookie("sampleCookie","This is Sample Cookie");
		response.addCookie(cookie);
		msg = "발견된 쿠키가 없었기 때문에 새로 설정했습니다.";
	}
%>
<!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>쿠키 테스트</title>
</head>
<body>
<script type="text/javascript">
	var found = <%=found%>;
	if(!found){
		alert("<%=msg%>");
	}
</script>
</body>
</html>
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>로그인 폼</title>
</head>
<body>
<form action="loginProc.jsp" method="post">
<table>
<tr><th>아이디</th><td><input type="text" name="id"></td></tr>
<tr><th>비	번</th><td><input type="password" name="pwd"></td></tr>
<tr><td colspan="2"><input type="submit" value="로그인"></td></tr>
</table>
</form>
</body>
</html>
loginProc.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String id= request.getParameter("id");
	String pwd= request.getParameter("pwd");
	if(id.length()> 0&& pwd.length()>0){
		request.setAttribute("login", "pass");
	%>
		<jsp:forward page="loginSuccess.jsp"/>		
 <%}else{%>
		<jsp:forward page="loginFail.jsp"/>
<%}
%>

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(request.getAttribute("login")!=null){
		Cookie cookie = new Cookie("login","pass");
		response.addCookie(cookie);
	}else{
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>
<!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>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/><p/>
<a href="service.jsp">서비스 이용하기</a>
</body>
</html>
service.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ include file="loginCheck.jsp" %>
<!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>회원 이용가능 페이지</title>
</head>
<body><p/><p/><p/>
<h1>회원이므로 이 기능을 이용할 수 있습니다.</h1>
</body>
</html>
loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
Cookie[] cookies = request.getCookies();
	boolean pass = false;
	if(cookies!=null){
		for(int i=0;i<cookies.length;i++){
			if(cookies[i].getName().equals("login")){
				pass = true;
				break;
			}
		}
	}
	if(!pass){
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>






세션(session)이란

웹 컨테이너에서 클라이언트의 정보를 보관할 때 사용

오직 서버에서만 생성

클라이언트마다 세션이 생성





세션과 session 기본 객체

page 디렉티브의 session 속성 값을 true로 지정

-세션이 존재하지 않을 경우 세션이 생성되고, 세션이 존재할 경우 이미 생성된 세션을 사용

session 기본 객체를 이용해서 세션에 접근

-session의 기본 값은 true이므로 false로 하지 않는 이상 항상 세션 사용

<%@ page contentType = ... %>

<%@ page session = "true" %>

<%

    ...

    session.setAttribute("userInfo", userInfo);

    ...

%>

속성 이용해서 클라이언트 관련 정보 저장



Session을 이용한 login 처리

※위 cookie를 이용한 login 처리 예제와 소스 같고 아래만 소스바꿈

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(request.getAttribute("login")!=null){
		/*상태 정보가 session으로 감  */
		session.setAttribute("login","pass");
	}else{
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>
<!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>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/><p/>
<a href="service.jsp">서비스 이용하기</a>
</body>
</html>
loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String login = (String)session.getAttribute("login");
	if(login==null){
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>


모든 페이지에서 로그인체크 해서 세션정보(아이디 비번)값이 없으면 경고 창 띄우고 loginForm으로 이동

loginCheck.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String login = (String)session.getAttribute("login");
	boolean pass = false;
	if(login!=null){
		pass = true;
	}
	
%>	
<script type="text/javascript">
	var pass = <%=pass%>;
	if(!pass){
		alert("회원으로 로그인한 경우에만 사용할 수 있습니다.");
		location.href="loginForm.jsp";
	}
</script>




자바빈

Bean

-1.기본 생성자

-2.변수

-3.set,get

-4.public



자바빈(JavaBeans)


-자바빈 - 웹 프로그래밍에서 데이터의 표현을 목적으로 사용

-일반적인 구성

값을 저장하기 위한 필드

값을 수정하기 위한 setter

값을 읽기 위한 getter


public class BeanClassName {
    /* 값을 저장하는 필드 */
    private String value;
    
    /* BeanClassName의 기본 생성자 */
    public BeanClassName() {
    }
    
    /* 필드의 값을 읽어오는 값 */
    public String getValue() {
        return value;
    }

    /* 필드의 값을 변경하는 값 */
    public void setValue(String value) {
        this.value = value;
    }
}

<jsp:useBean> 태그

JSP에서 자바빈 객체를 생성할 때 사용

구문

-<jsp:useBean id="[빈이름]" class="[자바빈클래스이름]"    scope="[범위]" />

id - JSP 페이지에서 자바빈 객체에 접근할 때 사용할 이름

class - 패키지 이름을 포함한 자바빈 클래스의 완전한 이름

scope - 자바빈 객체가 저장될 영역을 지정한다. page, request, session, application 중 

하나를 값으로 갖는다. 기본값은 page.

-예

<jsp:useBean id="info" class="chap11.member.MemberInfo" scope="request" />
<%= info.getName() %>







페이지 모듈화



※JSP 주석(TomCat에 의해서 컨버젼 할때 문장 무시) : <%--  문장  --%>


<jsp:include> 액션 태그

-다른 JSP 페이지의 '실행' 결과를 현재 위치에 삽입

-동작 방식


<jsp:include> 액션 태그

구문
<jsp:include page="포함할페이지" flush="true" />
-page 속성 : 포함할 JSP 페이지
-flush 속성 : 지정한 JSP 페이지를 실행하기 전에 출력 버퍼를 플러시 할 지의 여부를 지정한다.
 true이면 출력 버퍼를 플러시하고, false이면 하지 않는다.

중복 영역을 모듈화 하는 데 유용



<jsp:param> 액션 태그
신규 파라미터를 추가하는 데 사용
<jsp:param name="파라미터이름" value="값" />

<jsp:include page="/module/top.jsp" flush="false">
    <jsp:param name="param1" value="value1" />
    <jsp:param name="param2" value="value2" />
</jsp:include>



<jsp:param> 액션 태그의 동작 방식

기존 파라미터는 유지하고 파라미터를 새로 추가
  <jsp:include>로 포함되는 페이지에서만 유효


main.jsp(위와 동일한 결과값 출력)

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>메인 페이지</title>
</head>
<body>
<jsp:include page="top.jsp"/>
</body>
</html>

top.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<div style="border:1px solid red; background-color:#999999; height:100px;">
여기는 Top.jsp
</div>

보고있나






include 디렉티브

코드 차원에서 포함
구문 : <%@ include file="포함할파일" %>
활용
-모든 JSP 페이지에서 사용되는 변수 지정
-저작권 표시와 같은 간단하면서도 모든 페이지에서 중복되는 문장

main.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>메인 페이지</title>
</head>
<body>
<%-- <jsp:include page="top.jsp"/> --%>
<%@include file="top.jsp" %>
</body>
</html>


※설정파일은 점차 사라지고 있다~~



<jsp:include> 액션 태그와 include 디렉티브




<jsp:forward> 액션 태그
하나의 JSP 페이지에서 다른 JSP 페이지로 요청 처리를 전달할 때 사용
동작 방식





<jsp:forward> 액션 태그의 전형적 사용법
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    String forwardPage = null;
    
    // 조건에 따라 이동할 페이지를 지정
    if (조건판단1) {
        forwardPage = "페이지URI1";
    } else if (조건판단2) {
        forwardPage = "페이지URI2";
    } else if (조건판단3) {
        forwardPage = "페이지URI3";
    }
%>
<jsp:forward page="<%= forwardPage %>" />


기본 객체의 속성을 이용한 값 전달
속성을 이용해서 JSP 페이지 간 값 전달
 - <jsp:include>나 <jsp:forward>에서 사용



include와 forword의 차이
gugu.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String sDan = request.getParameter("dan");
	int dan = 0;
	if(sDan==null || sDan.equals("")){
		dan =2;
	}else{
	dan = Integer.valueOf(sDan);
	}
	String str = "";
	for(int i=1;i<=9;i++){
		str += dan + "*" + i+ "="+dan*i +"<br/>";
	}
	request.setAttribute("data", str);
%>
<jsp:forward page="guguView.jsp"/>
guguView.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String str = (String)request.getAttribute("data");
%>
<!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>구구단 보기(guguView.jsp)</title>
</head>
<body style="text-align:center;">
<%=str %>
</body>
</html>




01




에러 페이지 지정 & 에러 페이지 작성

에러 페이지 지정

- <%@ page errorPage = "예외발생시보여질JSP지정" %>


에러 페이지 작성

- <%@ page isErrorPage = "true" %>

isErrorPage 속성이 true인 경우 에러 페이지로 지정

- exception 기본 객체 : 발생한 예외 객체

exception.getMessage() : 예외 메시지

exception.printStackTrace() : 예외 추적 메시지 출력

- IE에서 예외가 올바르게 보여지려면 에러 페이지가 출력한 응답 데이터 크기가 513 바이트보다 커야 함

- <% response.setStatus(HttpServletResponse.SC_OK);%>


※요즘은 web.xml이용하지 않는게 추세




gugu.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page errorPage="error.jsp" %>    
<%
	String sDan = request.getParameter("dan");
	int dan =  Integer.valueOf(sDan);	
	String str = "";
	for(int i=1;i<=9;i++){
		str += dan + "*" + i+ "="+dan*i +"<br/>";
	}
	request.setAttribute("data", str);
%>
<jsp:forward page="guguView.jsp"/>

error.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page isErrorPage="true" %>
<!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>오류발생!!</title>
</head>
<body style="text-align:center;">
<h1>요청을 처리하는 중에 요류가 발생했습니다.</h1>
발생한 예외의 내용<p/><%=exception %>
</body>
</html>






Cookie

이용자의 상태정보를 클라이언트에 저장 할려고 하는 수단, 화면 출력용이 아님


JSP에서 쿠키 생성 / 읽기




쿠키 값의 인코딩/디코딩 처리

쿠키는 값으로 한글과 같은 문자를 가질 수 없음

-쿠키의 값을 인코딩해서 지정할 필요 있음


쿠키 값의 처리

 -값 설정시 : URLEncoder.encode("값", "euc-kr")

예, new Cookie("name", URLEncoder.encode("값", "euc-kr"));



     -값 조회시 : URLDecoder.decode("값", "euc-kr")

Cookie cookie = …; String value = URLDecoder.decode(cookie.getValue(), "euc-kr");



쿠키 값 변경
기존에 존재하는 지 확인 후, 쿠키 값 새로 설정
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
    for (int i = 0 ; i < cookies.length ; i++) {
        if (cookies[i].getName().equals(name)) {
        	Cookie cookie = new Cookie(name, value);
        	response.addCookie(cookie);
        }
    }
}


cookie01.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Cookie[] cookies = request.getCookies();
	boolean found = false;
	if(cookies==null){
		found=false;
	}else{
	for(int i=0;i<cookies.length;i++){
		if(cookies[i].getName().equals("sampleCookie")){
			found = true;
			}
		}
	}
	String msg = null;
	if( ! found){
		Cookie cookie = new Cookie("sampleCookie","This is Sample Cookie");
		response.addCookie(cookie);
		msg = "발견된 쿠키가 없었기 때문에 새로 설정했습니다.";
	}
%>
<!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>쿠키 테스트</title>
</head>
<body>
<script type="text/javascript">
	var found = <%=found%>;
	if(!found){
		alert("<%=msg%>");
	}
</script>
</body>
</html>




주요 기본 객체




※println()쓰는 이유
HTML소스코드 줄바꿈 되서 브라우져 소스보기에 출력되기 때문에



영역객체(Scope Object


PAGE 영역 - 하나의 JSP 페이지를 처리할 때 사용되는 영역

REQUEST 영역 - 하나의 HTTP 요청을 처리할 때 사용되는 영역

SESSION 영역 - 하나의 웹 브라우저와 관련된 영역(한 사람의 아이디 비번 ,구매한 물건의 갯수,가격 공유안됨)

APPLICATION 영역 - 하나의 웹 어플리케이션과 관련된 영역




속성(Attribute)





속성의 활용











<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	pageContext.setAttribute("myData", "페이지영역에 저장된 데이타");
%>
<!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>Page Scope Test</title>
</head>
<body>
<%=pageContext.getAttribute("myData") %>
</body>
</html>






loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>로그인 폼</title>
</head>
<body>
<form action="loginProc.jsp" method="post">
<table>
<tr><th>아이디</th><td><input type="text" name="id"></td></tr>
<tr><th>비	번</th><td><input type="password" name="pwd"></td></tr>
<tr><td colspan="2"><input type="submit" value="로그인"></td></tr>
</table>
</form>
</body>
</html>
loginProc.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String id= request.getParameter("id");
	String pwd= request.getParameter("pwd");
	if(id.length()> 0&& pwd.length()>0){%>
		<jsp:forward page="loginSuccess.jsp"/>		
 <%}else{%>
		<jsp:forward page="loginFail.jsp"/>
<%}
%>

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/>
</body>
</html>
loginFail.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>로그인 실패</title>
</head>
<body>
<h1>로그인에 실패하셨습니다.</h1>
</body>
</html>



012



camera.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")== null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("Camera,Canon DSLR 450,1000000");
%>
<!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>카메라 구입 페이지</title>
</head>
<body>
<h1>카메라를 장바구니에 담았습니다.</h1>
<a href="notebook.jsp">노트북 매장 가기</a>
</body>
</html>
notebook.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")==null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("Notebook,Apple MacBook Pro,1200000");
%>
<!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>노트북 구입 페이지</title>
</head>
<body>
<h1>노트북을 장바구니에 담았습니다.</h1>
<a href="car.jsp">자동차 매장 가기</a>
</body>
</html>
car.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")==null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("자동차,현대 소나타,8200000");
%>
<!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>자동차 구입 페이지</title>
</head>
<body>
<h1>자동차를 장바구니에 담았습니다.</h1>
<a href="showCart.jsp">장바구니 내용보기</a>
</body>
</html>
showCart.jsp
<%@ page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
%>
<!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>장바구니 보기</title>
</head>
<body>
<h1>장바구니 내용</h1>
<ol>
<%
	for(int i=0;i<cart.size();i++){
		String item = cart.get(i);%>
		<li><%=item %>
 <%}
%>

</ol>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(application.getAttribute("count")==null){
		application.setAttribute("count",0);
	}
	int cnt =(Integer)application.getAttribute("count");
	cnt++;
	application.setAttribute("count",cnt);
%>
<!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>방문자 수</title>
</head>
<body>
<h1>현재까지의 클릭한 수</h1>
<%=application.getAttribute("count") %>
</body>
</html>


reflash 할때 마다 클릭수가 바뀐다~

선언부(Declaration)


스크립트릿이나 표현식에서 사용할 수 있는 함수를 작성할 때 사용

선언부 형식


<%!
    public 리턴타입 메서드이름(파라미터목록) {
        자바코드1;                                              메소드, 변수, 클래스 선언 가능
        자바코드2;
        ...
        자바코드n;
        return 값;
    }
%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private String createGugu(int dan){
		String str ="";
		for(int i=1;i<=9;i++){
			str +=dan + " * " + i + " = " + dan*i + "<br/>"; 
		}
		return str;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!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>Declaration Test</title>
</head>
<body>

	<%=createGugu(dan)%>
</body>
</html>





<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!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>Declaration Test</title>
</head>
<body>

	<%=createGugu(dan)%>
</body>
</html>



↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓



<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!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>Declaration Test</title>
</head>
<body>
<%
	ArrayList<String> list = createGugu(dan);
	for(int i=0;i<list.size();i++){
		String line = list.get(i);%>
		<%=line %><br/>

<%}%>
</body>
</html>





jsp 모델1 방식(JSP, JAVA) 


Gugudan.java

package web.business;

import java.util.ArrayList;

public class Gugudan {
	private int num;

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}
	public ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}
}

gugudan.jsp
<%@page import="web.business.Gugudan"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<% 
	int dan= Integer.valueOf(request.getParameter("dan")); 
	Gugudan gugu = new Gugudan();
	ArrayList<String> list = gugu.createGugu(dan);
%>
<!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>Declaration Test</title>
</head>
<body>
<%
	for(int i=0;i<list.size();i++){
		String line = list.get(i);%>
		<%=line %><br/>

<%}%>
</body>
</html>






request 기본 객체


form 처리예

form.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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>Servlet POST 방식으로 요청하기</title>
</head>
<body>
<form  action="formProc.jsp" method="post">
	취미를 선택해주세요(다수개 가능)<p/>
	여행<input type="checkbox" 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="놀기"/>
	<input type="submit" value="저장"/>
</form>

</body>
</html>


formProc.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("euc-kr");
	String[] hobby = request.getParameterValues("hobby");
%>    
<!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>이용자가 선택한 취미</title>
</head>
<body>
<h2>이용자가 선택한 취미</h2>
<ol>
<%
	for(int i=0;i<hobby.length;i++){%>
		<li><%=hobby[i] %><br/>
<%}
%>
</ol>
</body>
</html>







리다이렉트(Redirect)
특정 페이지로 이동하라고 웹 브라우저에 응답

response.sendRedirect(String location)로 구현















Model 2 ---->MVC


C   servlet  ----HTML (x)

                       veiw (x)

                       controller(o)


V    JSP -------view(0)

                       HTML


M    JAVA







스크립트 요소

표현식(Expression) - 값을 출력                      <%=  %>     안(메소드를 선언 할 수 없다.)

스크립트릿(Scriptlet) - 자바 코드를 실행           <%   %>      


선언부(Declaration) - 자바 메서드(함수)를 정의 <%!  %>     → service 메소드 으로 나간다.


Directive                                                       <%@ %>   




<%@ page contentType = "text/html; charset=euc-kr" %>        → Directive
   include                                                                                 → 개발자가 TomCat한테 

   taglib  - JSTL                                                                                                

         Struts                                                                                              JSP → Servlet으로 바꿀때  

         Spring                                                                                                   └(Conversion Time)

<html>

<head>

  <title>HTML 문서의 제목</title>

</head>

<body>

<%                                                                                    →Scriptlet(service메소드 안쪽으로 들어가는 소스; 지역변수)

    String bookTitle = "JSP 프로그래밍";         

    String author = "최범균";

%>

<b><%= bookTitle %></b>(<%= author %>)입니다.                →Expression("bookTilte"은 service메소드 안쪽으로 간다)

</body>

</html>



<%out.print("bookTiltle");%> == <%= bookTitle %> 위 표현식을 scriptlet에 이렇게 표현 할 수 있지만 소스를 줄이기 위해 표현식으로 쓴다.

java 설치 확인

 

cmd창 열고

 

java -version     그러면 자바 설치 가 되어 있다면 설치 버젼이 나옴

 

java

 

javac

 

echo %classpath%

이렇게 나오면 오류나니

 

환경 변수에 새로 만들기

CLASSPATH

.;

 

이렇게 해줌~~

 

 

<IDE :통합 개발 환경 [integrated development environment, 統合開發環境] >

1.에디터

2.JSK 툴

3.webbrowser(client)

4.web server를 편리하게

 


JSP(잘할려면)---->servlet



Servlet - 서버(Serv)에 들어가는 작은(let) 프로그램이다..



HTTP Server   -----servlet(요청과 응답을 다룰수 있는 기능이 있음)


       ↑           

(request ) (response)

                      ↓

Webbrowser   ------http client










package test.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.Out;


public class TestServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=euc-kr");//http header부분
		
		int num = Integer.valueOf(request.getParameter("num"));//request로 부터 num이라는 파라미터를 받겠다.(숫자여도 문자열로 받기 때문에 Integer)
		
		PrintWriter out = response.getWriter();
		for(int i=1;i<=9;i++){
			out.println(num + " * " + i + " = " +num*i+"</br>");
		}
		
		//server client 연결...stream
		out.println("Hello World");
		out.flush();//buffer안에 있는 데이터를 브라우져로 전송
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}


http://localhost:8080/WebApp/TestServlet  이러면 오류가 남


http://localhost:8080/WebApp/TestServlet?num=7

이렇게 뒤에다  num 값을 주면 7단 구구단이 출력된다.



'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습3 선언부(Declaration),request 기본 객체,리다이렉트(Redirect)  (0) 2012.07.06
복습2 스크립트 요소  (0) 2012.07.05
예비  (0) 2012.05.30
예비  (0) 2012.05.30
예비  (0) 2012.05.30


'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습2 스크립트 요소  (0) 2012.07.05
복습1 설치 및 세팅  (0) 2012.07.04
예비  (0) 2012.05.30
예비  (0) 2012.05.30
8일차 MVC  (0) 2012.05.30


'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습1 설치 및 세팅  (0) 2012.07.04
예비  (0) 2012.05.30
예비  (0) 2012.05.30
8일차 MVC  (0) 2012.05.30
7일차 filter,로그인  (0) 2012.05.30


'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

예비  (0) 2012.05.30
예비  (0) 2012.05.30
8일차 MVC  (0) 2012.05.30
7일차 filter,로그인  (0) 2012.05.30
7일차 Tiles  (0) 2012.05.30
SimpleController.java
package kame.chap24;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleController extends HttpServlet {

	public void doGet(HttpServletRequest request, 	HttpServletResponse response)
												throws ServletException, IOException {
		processRequest(request, response);
	}

	public void doPost(HttpServletRequest request, 
			HttpServletResponse response)
	throws ServletException, IOException {
		processRequest(request, response);
	}
	
	private void processRequest(HttpServletRequest request,		HttpServletResponse response)
													throws IOException, ServletException {
		// 2단계, 요청 파악
		// request 객체로부터 사용자의 요청을 파악하는 코드
		String type = request.getParameter("type");
		
		// 3단계, 요청한 기능을 수행한다.
		// 사용자에 요청에 따라 알맞은 코드
		Object resultObject = null;
		
		String outcomePage="";
		if (type == null || type.equals("greeting")) {
			resultObject = "안녕하세요.";
			outcomePage="/simpleView.jsp";
		} else if (type.equals("date")) {
			outcomePage="/home_body.jsp";
			request.setAttribute("hello", "안녕 난 컨트롤러");
			resultObject = new java.util.Date();
		} else {
			resultObject = "Invalid Type";
		}
		
		// 4단계, request나 session에 처리 결과를 저장
		request.setAttribute("result", resultObject);
		
		// 5단계, RequestDispatcher를 사용하여 알맞은 뷰로 포워딩
		RequestDispatcher dispatcher =
				   request.getRequestDispatcher(outcomePage);
		dispatcher.forward(request, response);
	}
}





원본 소스.zip


11.MVC.zip


'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

예비  (0) 2012.05.30
예비  (0) 2012.05.30
7일차 filter,로그인  (0) 2012.05.30
7일차 Tiles  (0) 2012.05.30
7일차 파일 업로드  (0) 2012.05.30
XSLTFilter.java
package kame.chap21.filter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XSLTFilter implements Filter {

	private String xslPath = null;

	public void init(FilterConfig config) throws ServletException {
		xslPath = config.getServletContext().getRealPath(
				"/WEB-INF/xsl/book.xsl");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html; charset=euc-kr");
		//응답에 어던 데이터를 보내기 위한 통로를 준비
		PrintWriter writer = response.getWriter();
		XSLTResponseWrapper responseWrapper = new XSLTResponseWrapper(
				(HttpServletResponse) response);
		chain.doFilter(request, responseWrapper);

		// XSL/T 변환
		try {
			TransformerFactory factory = TransformerFactory.newInstance();
			Reader xslReader = new BufferedReader(new FileReader(xslPath));

			StreamSource xslSource = new StreamSource(xslReader);

			Transformer transformer = factory.newTransformer(xslSource);

			String xmlDocument = responseWrapper.getBufferedString();
			Reader xmlReader = new StringReader(xmlDocument);
			StreamSource xmlSource = new StreamSource(xmlReader);

			StringWriter buffer = new StringWriter(4096);

			transformer.transform(xmlSource, new StreamResult(buffer));

			writer.print(buffer.toString());
		} catch (Exception ex) {
			throw new ServletException(ex);
		}

		writer.flush();
		writer.close();
	}

	public void destroy() {
	}
}






원본 소스.zip

10.Filter.zip


'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

예비  (0) 2012.05.30
8일차 MVC  (0) 2012.05.30
7일차 Tiles  (0) 2012.05.30
7일차 파일 업로드  (0) 2012.05.30
6일차 답변형 게시판  (0) 2012.05.30

+ Recent posts