CLASS/Web Server

[웹서버프로그래밍] 2022.05.17 JSTL 태그 실습, DB 커넥션 풀과 트랜잭션, 초기화 매개변수

sseni 2022. 5. 17. 16:44
728x90

[실습1] import.jsp (** 실행 안 됨)

- 동일 서버에 있는 jsp 를 포함하거나 외부 url 자원을 포함할 수 있음

- escapeXml=“false”는 포함될 자원의 HTML 태그를 해석해서 보여줌

- import.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
  <title>ch11 : import</title>
</head>

<body bgcolor="#FFFFFF">
<h3>&lt;c:import&gt;</h3>

다음은 import 를 이용해 포함한 것입니다.<HR>

<c:import url="set.jsp" var="myurl" />
<c:out value="${myurl}" escapeXml="false"/>

<HR>

<c:import url="http://www.hanb.co.kr/book/newbooks.html" var="myurl3" />
<c:out value="${myurl3}" escapeXml="false"/>

</body>
</html>

[실습2] url.jsp

url 파라미터 추가, 수정된 url 정보를 html에서 표현언어를 이용해 활용함

- url.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
  <title>ch11 : url</title>
</head>
<body bgcolor="#FFFFFF">

<h3>&lt;c:url&gt;</h3>
<c:url value="/ch11/choose.jsp" var="target">
	<c:param name="sel">a</c:param>
</c:url>
<HR>
단순출력 : ${target}<BR>
링크연동 : <a href="${target}">choose.jsp-a선택</a>

</body>
</html>

[실습3] redirect.jsp

- 파라미터를 추가해 다른 페이지로 이동

- redirect.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
  <title>ch11 : redirect</title>
</head>
<body bgcolor="#FFFFFF">

<h3>&lt;c:redirect&gt;</h3>
<c:redirect url="/ch11/choose.jsp">
	<c:param name="sel">a</c:param>
</c:redirect>
</body>
</html>

[실습4] 스크립트릿을 JSTL로 변환

- ProductList.jsp 와 ProductSel.jsp을 JSTL 버전으로 변경

- ProductList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch11:JSTL 예제</title>
</head>
<body>
<div align="center">
<H2>ch11:상품목록-JSTL버전  </H2>
<HR>
<form name=form1 method=POST action=ProductSel.jsp>
	<jsp:useBean id="product" class="jspbook.Product" scope="session"/>
	<select name="sel">
		<c:forEach items="${product.productList}" var="item">
			<option>${item}</option>
		</c:forEach>
	</select>
	<input type="submit" value="선택"/>
</form>
</div>
</body>
</html>

- ProductSel.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch11:JSTL 예제</title>
</head>
<body>
<div align="center">
<H2>ch11:상품선택-JTL버전</H2>
<HR>
1. 선택한 상품은 : ${param.sel} <BR>
2. num1 + num2 = ${product.num1+product.num2} <BR>
</div>
</body>
</html>


[데이터베이스 커넥션 풀과 트랜잭션]

 

# 커넥션

: 애플리케이션과 데이터베이스의 연결로서, 애플리케이션에서 데이터베이스에 접속하고 접속을 종료하는 일련의 과정

 

# 트랜잭션

: 여러 작업을 하나의 단위로 처리하는 것 ( 여러 작업이지만 하나의 목적을 가짐 )

 

# 데이터베이스 커넥션 관리

 

# 톰캣에 DataSource 설정

<Resource name=“jdbc/mysql” auth=“Container” type=“javax.sql.DataSource”

driverClassName=“com.mysql.jdbc.Driver”

url=“jdbc:mysql://127.0.0.1/jspdb” 

username=“jspbook” password=“1234”

maxActive=“5” maxIdle=“3” maxWait=“-1” />

 

[실습5] DBCP 설정 및 클라이언트 구현

- DBCP 의 구현상의 차이점과 JNDI 사용법 

- jdbctest_dbcp.jsp

<%@ page contentType="text/html;charset=utf-8" import="javax.sql.*,java.sql.*, javax.naming.*" %>
<% request.setCharacterEncoding("utf-8"); %>

<%
	// 데이터베이스 연결관련 변수 선언
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	try{
        Context initContext = new InitialContext();
        Context envContext = (Context)initContext.lookup("java:/comp/env");
        DataSource ds = (DataSource)envContext.lookup("jdbc/mysql");
        
        // 커넥션 얻기
         conn = ds.getConnection();

		// username 값을 입력한 경우 sql 문장을 수행.
		if(request.getParameter("username") != null) {
			// Connection 클래스의 인스턴스로 부터 SQL  문 작성을 위한 Statement 준비
			String sql = "insert into jdbc_test values(?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,request.getParameter("username"));
			pstmt.setString(2,request.getParameter("email"));
			pstmt.executeUpdate();
		}
	}
	catch(Exception e) {
		e.printStackTrace();
	}
%>
<HTML>
<HEAD><TITLE>ch12 : JDBC 테스트 </TITLE></HEAD>
<BODY>
<center>
<H2>ch12:jdbctest_dbcp.jsp</H2>
<HR>

<form name=form1 method=post action=jdbctest_dbcp.jsp>
등록이름 : <input type=text name=username>
email주소 : <input type=text name=email size=20>
<input type=submit value="등록">
</form>
<HR>
</center>
# 등록 목록<P>
<%
	try{
		// select 문장을 문자열 형태로 구성한다.
		String sql = "select username, email from jdbc_test";

		pstmt = conn.prepareStatement(sql);

		// select 를 수행하면 데이터정보가 ResultSet 클래스의 인스턴스로 리턴됨.
		ResultSet rs = pstmt.executeQuery();
		int i=1;

		// 마지막 데이터까지 반복함.
		while(rs.next()) {
			out.println(i+" : "+rs.getString(1)+" , "+rs.getString("email")+"<BR>");
			i++;
		}

		// 사용한 자원의 반납.
		rs.close();
		pstmt.close();
		conn.close();
	}
	catch(Exception e) {
		System.out.println(e);
	}
%>
</BODY>
</HTML>

 

[실습6] 트랜잭션 관리 - 계좌이체 구현

- transaction_test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<jsp:useBean scope="page" id="bb" class="jspbook.Bank1Bean" />
<jsp:useBean scope="page" id="bb2" class="jspbook.Bank2Bean" />

<%
	if(request.getMethod().equals("POST")){
		if(bb.transfer(Integer.parseInt(request.getParameter("bal"))))
				out.println("<script>alert('정상처리 되었습니다.')</script>");
		else
				out.println("<script>alert('수용한도를 초과했습니다.')</script>");
	}

	bb.getData();
	bb2.getData();
%>

<HTML>
<HEAD>
<TITLE>ch12 :트랜잭션 테스트 </TITLE> 
</HEAD>

<BODY>
<div align="CENTER">
<H3>계좌현황</H3>
<HR>

<table border=1 cellpadding=5 cellspacing=0>
<tr>
<td>Bank1</td>
<td>이름 : <%=bb.getAname() %></td>
<td>잔액 : <%=bb.getBalance() %></td>
</tr>

<tr>
<td>Bank2</td>
<td>이름 : <%=bb2.getAname() %></td>
<td>잔액 : <%=bb2.getBalance() %></td>
</tr>

</table>
<HR>

<form name=form1 method=post>
이체금액 : <INPUT TYPE="text" NAME="bal" width=200 size="5">
<input type="submit" value="이체실행" name="B1"> <input type="reset" value="다시입력" name="B2">
</form>
</div>
</BODY>
</HTML>

- Bank1Bean.java

package jspbook;

//클래스 import
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

public class Bank1Bean {
	
	// 멤버 선언
	private int aid;
	private String aname;
	private int balance;

	// 데이터베이스 관련 객체 선언
	Connection conn = null;
	Statement stmt = null;
	PreparedStatement pstmt = null;

	// JNDI를 통한 연결
	public void connect() {
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup("jdbc/mysql");
			conn = ds.getConnection();
		}

		catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}

	// connection  반환
	public void disconnect() {
		try {
			if (conn != null)
				conn.close();
		}
		catch (SQLException e) {
			System.out.println(e);
		}
		System.out.println("close");
	}

	// bank1 테이블 데이터 가져오는 메서드
	public void getData() {
		connect();
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select * from bank1");
			rs.next();
			aid = rs.getInt("aid");
			aname = rs.getString("aname");
			balance = rs.getInt("balance");
		}
		catch (Exception e) {
			System.out.println(aid + aname + balance);
			System.out.println(e);
		}
		finally {
			disconnect();
		}
	}

	// 이체 처리 메서드
	public boolean transfer(int bal) {
		connect();
		try {
			conn.setAutoCommit(false);
			pstmt = conn
			.prepareStatement("update bank1 set balance = balance-? where aid=101");
			pstmt.setInt(1, bal);
			pstmt.executeUpdate();
			pstmt = conn
			.prepareStatement("update bank2 set balance = balance+? where aid=201");

			pstmt.setInt(1, bal);
			pstmt.executeUpdate();
			stmt = conn.createStatement();

			ResultSet rs = stmt
			.executeQuery("select balance from bank2 where aid=201");

			rs.next();

			if (rs.getInt(1) > 80) {
				conn.rollback();
				return false;
			}
			else
				conn.commit();
		}
		catch (Exception e) {
				System.out.println(e);
		}
		finally {
			disconnect();
		}
		return true;
	}

	public int getAid() {
		return aid;
	}

	public String getAname() {
		return aname;
	}

	public int getBalance() {
		return balance;
	}
}

- bank2Bean.java

package jspbook;

//클래스 import
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

public class Bank2Bean {
	
	// 멤버 선언
	private int aid;
	private String aname;
	private int balance;

	// 데이터베이스 관련 객체 선언
	Connection conn = null;
	Statement stmt = null;
	PreparedStatement pstmt = null;

	// JNDI를 통한 연결
	public void connect() {

		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup("jdbc/mysql");
			conn = ds.getConnection();
		}

		catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}

	// connection 연결종료
	public void disconnect() {
		try {
			if (conn != null)
				conn.close();
		}
		catch (SQLException e) {
			System.out.println(e);
		}
		System.out.println("close");
	}

	// bank1 테이블 데이터 가져오는 메서드
	public void getData() {
		connect();
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select * from bank2");
			rs.next();
			aid = rs.getInt("aid");
			aname = rs.getString("aname");
			balance = rs.getInt("balance");
		}
		catch (Exception e) {
			System.out.println(aid + aname + balance);
			System.out.println(e);
		}
		finally {
			disconnect();
		}
	}

	// getXxx 메서드
	public int getAid() {
		return aid;
	}

	public String getAname() {
		return aname;
	}

	public int getBalance() {
		return balance;
	}
}

- transaction_table.sql

create table bank1 (
	aid int NOT NULL primary Key,
	aname varchar(10),
	balance int
);

create table bank2 (
	aid int NOT NULL primary Key,
	aname varchar(10),
	balance int
);

insert into bank1 values(101,'user1',100);
insert into bank2 values(201,'user2',50);


[리스너와 필터]

 

# 초기화 매개변수의 개요

- 웹 애플리케이션 초기화 매개변수는 웹 애플리케이션이 컨테이너에 의해 구동될 때 로딩되는 정보로서, 웹 애플리케이션 전반에 걸쳐 공통적으로 참조하는 값을 설정하는 용도로 사용함

- ex 데이터베이스 접속 주소나 환경설정 파일의 위치 

- 공통적으로 참조하는 값을 설정하는 용도

- ServletConfig, ServletContext

 

# ServletConfig 사용하는 경우

getInitParameter(“param-name에서의 설정 이름”)

web.xml 에서 <context-param> 태그를 이용해 설정할 수 있음

<web-app>
<context-param>
<param-name> </param-name>
<param-value> </param-value>
</context-param>
</web-app>

[실습7] 초기화 매개변수 관리

- PropTest.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>ch13 : Properties 연계</title>
</head>
<body>
<div align="center">
<H2>Properties 연계</H2>
<HR>
 버전 :  ${prop.get('version')} <BR>
 url :  ${prop.get('url')} <BR>
 user :  ${prop.get('user')} <BR>
 password :  ${prop.get('passwd')}
 <HR>
 <H2>Admin Properties</H2>
 관리자 ID : ${prop.get("adminId")} <BR>
 관리자 전화번호 : ${tel}
</div>
</body>
</html>

 

 

 

 

*** 13장 하고 Django 셋업

 

 

728x90