[JSP] useBean 쓰는 법

JSP 2009. 1. 21. 21:17

처리 부분을 모듈화 하기 위해 자바빈을 작성한다.

JSP에서 자바빈을 사용하기 위한 액션 태그가 있다.

<jsp:useBean id="Bean_Name" class="JavaBean class_name" scope="자바빈객체가 저장될 영역"/>
<jsp:setProperty name="Bean_Name" property="property_name" value="프로퍼티에 저장할 값"/>
<jsp:getProperty name="Bean_Name" property="property_name"/>

<jsp:useBean> 액션 태그에서 id속성값에 지정한 이름이 이미 존재하는 경우, 자바빈 객체를 새로 생성하지 않고 기존에 생성된 객체를 그대로 사용한다. 이때 id속성값, class속성값, scope속성값이 모두 동일해야 같은 객체가 된다. scope는 page, request, session, application 값을 가지며 기본값은 page이다.

<jsp:setProperty> 액션 태그는 자바빈 객체의 프로퍼티 값을 저장하기 위해 사용된다. 프로퍼티가 많을 경우에는 property속성값을 *로 주면 모든 프로퍼티 값이 세팅된다. 주의할 점은 폼으로부터 넘어오는 파라미터의 이름이 프로퍼티의 이름과 일치해야 한다는 것이다. 만일 폼으로부터 넘어온 파라미터 명과 자바빈의 프로퍼티가 일치하지 않는 경우에는 <jsp:setProperty> 액션 태그에 param속성을 기술해야 한다, param속성값에는 폼으로부터 넘어온 파라미터 명을 기술한다.

<jsp:getProperty> 액션 태그는 자바빈 객체에서 저장된 프로퍼티 값을 사용하기 위해 사용된다.

Posted by zeide
,

-_- 우편번호...떡밥인가효?

DB에 우편번호테이블을 먼저 생성해야 한다. 디비는 오라클을 사용했다.

1. 찾기 첫페이지

<?xml version="1.0" encoding="EUC-KR" ?>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR" />
<title>Address</title>
<link  href="style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="zipfind.js"></script>
</head>

<body>
<div>
Find Address<br/>
<form name="ad" method="get" action="dataHandle.jsp" onsubmit="return searchDb()">
<input type="text" name="address" id="dong" class="txtbox"/>
<input type="submit" value="find" class="bt" />
</form>
</div>
</body>
</html>

2. 디비 검색 결과 페이지

<?xml version="1.0" encoding="EUC-KR" ?>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@page import="java.sql.Connection"%>
<
%@page import="java.sql.PreparedStatement"%>
<
%@page import="java.sql.ResultSet"%>
<
%@page import="java.sql.DriverManager"%>
<
%@page import="java.sql.SQLException"%>
<
%@page import="zip.data.DTO.ZipVO"%>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR" />
<title>Address</title>
<link  href="style2.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="zipfind.js"></script>
</head>
<body>

<div id="result">
<form action="myAddress.jsp" method="post">
<table border="0" cellpadding="0"cellspacing="0" >
<tr  class="title">
<td>우편번호</td>
<td>시, 도</td>
<td>구, 군</td>
<td>동</td>
<td>번지</td>
<td>선택</td>
</tr>
<tr class="line">
<td colspan="5"></td>
</tr>
<%
request.setCharacterEncoding("euc-kr");
String address = request.getParameter("address");
//sql에서 읽을 수 있게 넘어오는 값을 타입 변형
address = new String(address.getBytes("8859_1"),"euc-kr");

//1.드라이버 로딩
  try{
   Class.forName("oracle.jdbc.OracleDriver");
  }catch(ClassNotFoundException e){
   System.err.print("ClassNotFoundException");
  }

Connection con=null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try{
 String zipcode, sido, gugun, dong, bunji;
 String dburl="jdbc:oracle:thin:@localhost:1521:ORCL";
 String dbUser = "scott";
 String dbPass = "tiger";
 
 StringBuffer query = new StringBuffer();
 query.append("select zipcode, sido, gugun, dong, bunji from zipcode where dong like '%");
 query.append(address);
 query.append("%'");

//2.데이터베이스 커넥션 생성
 con = DriverManager.getConnection(dburl,dbUser,dbPass);
 
//3.statement 생성
 pstmt = con.prepareStatement(query.toString());

//4.쿼리 실행
 rs = pstmt.executeQuery();

//5.쿼리 실행 결과 출력
 while(rs.next()){
 
%>
<tr class="line">
<td colspan="5"></td>
</tr>
<tr class="value">

<td><%= rs.getString("zipcode") %></td>
<td><%= rs.getString("sido") %></td>
<td><%= rs.getString("gugun") %></td>
<td><%= rs.getString("dong") %></td>
<td><%= rs.getString("bunji") %></td>
<td>
<input type="button" value="선택" class="bt"
onclick="btnSelectClick('<%= rs.getString("zipcode") %>', '<%= rs.getString("sido") %>','<%= rs.getString("gugun") %>','<%= rs.getString("dong") %>','<%= rs.getString("bunji") %>')"/>
</td>
</tr>
<tr class="line">
<td colspan="5"></td>
</tr>

<%
}

}catch(SQLException e){

 e.printStackTrace();
}finally{
//6.사용한 statement 종료
 if(rs!=null){
  rs.close();
 }
 if(pstmt!=null){
  pstmt.close();
 }
//7.커넥션 종료
 if(con!=null){
  try{
   con.close();
 }catch(SQLException e){
 
  e.printStackTrace();
 }
  
 }
}

%>
<input type="hidden" name="zipcode"  id="zipcode"/>
<input type="hidden" name="sido" id="sido"/>
<input type="hidden" name="gugun" id="gugun"/>
<input type="hidden" name="dong" id="dong"/>
<input type="hidden" name="bunji" id="bunji"/>

</table>
</form>
</div>
</body>
</html> 

3. 상세 주소로 이동

<%@ page contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR" %>
<% request.setCharacterEncoding("euc-kr"); %>

<jsp:useBean id="myaddress" class="zip.data.DTO.ZipVO"></jsp:useBean>
<jsp:setProperty name="myaddress" property="*"/>
<html>
<head>
<style type="text/css">
body {margin: 0;padding: 0;height: 100%;width: 100%;}
div {font-size: 12px;font-family: 돋움;}

#table {position: absolute;top: 30%;left: 25%;height:80px;width:400px;border: 2px solid #0046AD;}
#txtaddress {position: absolute;top: 1%;left: 5%;padding: 3px}
#btarea {position: absolute;top:65%;left: 5%;padding: 3px;}

.txtarea {font:normal 14px Dotum,"돋움"; }
.txtbunji {font-size: 12px;width: 354px;}
.bt{float:right; border:1px solid #0046AD;font:normal 12px Dotum,"돋움";color:#444444;width:60px;}
</style>
<title>Insert title here</title>
</head>
<body>

<div id="table">
<form action="">

<div id="txtaddress">
<textarea rows="1" cols="50" style="overflow: hidden;" readonly="readonly" class="txtarea" >
<jsp:getProperty name="myaddress" property="zipcode"/> <jsp:getProperty name="myaddress" property="sido"/>시 <jsp:getProperty name="myaddress" property="gugun"/> <jsp:getProperty name="myaddress" property="dong"/>
</textarea>
<br/>
<input type="text" name="juso" id="realbunji" class="txtbunji"/>
</div>

<div id="btarea">
<input type="submit" name="confirm" id="confirmbt" value="확인" class="bt"/>
</div>

</form>
</div>

</body>
</html>


Posted by zeide
,
데스크탑에 오라클10g를 설치했지만 테스트를 위해(과연!?) 랩탑에 MySQL5.1을 그냥 설치했다.

나의 설치 과정

1. MySQL 설치
http://dev.mysql.com/downloads/
MySQL Community Server → windows → Windows ZIP/Setup.EXE (x86) →Pick a mirror → 다운로드

1) mysql-5.1.30-win32.zip 파일의 압축을 풀어준다.
2) Setup.exe 파일이 생성된다.
3) 실행
Setup Type : custom
Custom Setup : Developer Components → install, Install path → change
Configuration Type : Detailed Configuration
Server Type : Developer Machine
Database Usage : Multifunctional Database
InnoDB Tablespace Settings : 알아서 경로 설정
Decision Support(DSS)/OLAP 체크
Enable TCP/IP Networking 체크, Add firewall exception for this port 체크, Enable Strict Mode 체크
Best Support For Multilingualism 체크 - 'UTF-8', euc-kr은 아래 메뉴에서 선택 가능
Install As Windows Service 체크(service name확인), Include Bin Directory in Windows PATH 체크
Modify Security Settings 비번 체크
Execute
4) MySQL 실행
도스 창에서 명령 실행, 설정할 때 체크한 server name으로 실행한다.
실행
>net start mysql
중지
>net stop mysql
5)MySQL 접속
관리자 접속 - 비번은 setting에 넣은 비번
>mysql -u root -p
접속 끊기
>quit

2. MySQL 드라이버 설치
http://dev.mysql.com/downloads/
Connectors → Connector/J → 5.1 Source and Binaries (zip) → 다운로드

1) mysql-connector-java-5.1.7.zip 파일의 압축을 풀어준다.
2) mysql-connector-java-5.1.7 폴더가 생성된다.

3. 이클립스에 MySQL 연동
1) Build Path로 드라이버(mysql-connector-java-5.1.7-bin.jar)를 잡아준다.

DB 플러그인(DBedit)은 설치했다가 삭제했다.
설치는 완벽했으나...
SQL문 작성을 위해 파일을 생성하려면 에러 발생이 무한으로 반복되어 이클립스가 날아가는 증상도 반복-_-
대체 무엇이 문제였을까?
Posted by zeide
,

[DataBase] Connection Pool

DB 2009. 1. 16. 15:19

jdbc 방식의 연결시에는 초기 지연시간 발생하기 때문에 서비스 시간이 지연 → 서비스 시간 개선 → connection을 DB에 미리 연동해두고 필요한 클라이언트에게 연결된 connection을 제공 → 메모리 부하

JNDI(Java Naming & Directory Interface) : JVM → CP
DBCP를 찾아 가기 위한 객체
Context ct = new InitialContext();
DataSource ds = (DataSorce)ct.lookup("java:comp/env/jdbc/등록한 이름");
Connection con = ds.getConnection();

이후는 JDBC와 동일하다.

* DBCP설정
http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html

0. Drivers for older Oracle versions may be distributed as *.zip files rather than *.jar files. Tomcat will only use *.jar files installed in $CATALINA_HOME/common/lib. Therefore classes111.zip or classes12.zip will need to be renamed with a .jar extension. Since jarfiles are zipfiles, there is no need to unzip and jar these files - a simple rename will suffice

1.context configuration
server.xml의 context부분에 추가해준다.

<Resource name="jdbc/myoracle" -- context의 lookup에서 찾아갈 이름, myoracle만 변경가능, 대소문자 주의
              auth="Container"
              type="javax.sql.DataSource"
              driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" 
              password="tiger"
              maxActive="50" -- 확장 커넥션의 생성 갯수, 기본과 동일하거나 기본+10
              maxIdle="40" -- 기본 커넥션의 생성 갯수
              maxWait="-1" -- 대기시간
/>

2. web.xml configuration
일반 클래스(DAO)에서 connection pool을 쓰려면 servlet이나 JSP에서 클래스를 인스턴스화 해서 쓴다.
안되면 web.xml설정, DTD의 설정에 따라 파일에 넣는다.
webcontent → WEB-INF → lib → web.xml
위에서 설정한 resource name으로 변경해준다

<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/myoracle</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

Posted by zeide
,

[DataBase] JDBC 작성 순서

DB 2009. 1. 15. 11:59
1. JDBC드라이버 로딩
오라클 - oracle.jdbc.driver.OracleDriver

  try{
  Class.forName("oracle.jdbc.driver.OracleDriver");//대소문자 주의
  }catch(ClassNotFoundException cnfe){
   cnfe.printStackTrace();
  }

2. 데이터베이스 커넥션 구함

 public Connection getConnection(){
  Connection con=null;
  String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";//127.0.0.1루프백, 도메인, 로컬호스트
  String dboid = "scott";
  String dbopass = "tiger";
    
  try{
  con = DriverManager.getConnection(dburl,dboid,dbopass);
  }
  catch(SQLException e){
   e.printStackTrace();
  }//end catch
  
  return con;
 }
//singletonpattern이용

3. 쿼리 실행을 위한 statement 객체 생성

Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

   con = SingletonConnection.getInstance().getConnection();
   StringBuffer selectQuery = new StringBuffer();
   selectQuery.append("select num, name, address, phone, age from classinfo");
   pstmt = con.prepareStatement(selectQuery.toString());
  
4. 쿼리 실행

 rs = pstmt.executeQuery();

5. 쿼리 실행 결과 사용

 while(rs.next()){
    //조회된 결과를 자바빈즈로 생성
    xmlDateDTO xdd = new xmlDateDTO(
            rs.getInt("num"),
            rs.getInt("age"),
            rs.getString("name"),
            rs.getString("address"),
            rs.getString("phone"));//빈즈를 list로 관리
    classList.add(xdd);
   }

6. statement 종료

if(rs!=null){rs.close();}
if(pstmt!=null){pstmt.close();}

7. 데이터베이스 커넥션 종료

if(con!=null){con.close();}

Posted by zeide
,