1
Middleware (2)
Nclab M.S.
Jinwon Lee
2
Contents
CGI, Servlet, JSP
→
Client Session Management
JDBC (Java Database Connectivity)
Connection pooling
3
Overview
ClientBrowser
Engine SupportingJSPs and Servlets Database
JDBC
ServletJSP,
Session
Connection Pooling
4
Client Session Management
5
Stateless HTTP Protocol
HTTP transaction is independent to each request.
Problems at Data Tracking, User Identification. Ex) website login, shopping cart.
Need to mange state information between transaction requests and Web Application
→ Session Tracking
6
Session Tracking
Session TrackingManage states informationClient-side : CookieServer-side: HttpSession (Servlet API)
7
CookiesA cookie is a piece of information that a site hands to your browser
The browser hands the site the cookie on each subsequent requestUnless the cookie is deleted, expired, modified..
8
Servlet/JSP support CookiesJavax.serlvet.http package support Cookie class
Send to Client (HttpServletResponse class) Cookie myCookie = new Cookie(“key”, “value”)
// Create cookie and Set attribute response.addCookie(myCookie); // Send Cookie to Client(Cookie is part of the HTTP response header.)
Receive from Client(HttpServletRequest class) Cookie [] allCookie = request.getCookies(); // Receive allCookie from Client String value = myCookie[i].getValue(); // Find the specific one you are interested in
9
Cookies don’t always taste good
Cookies can only contain small amounts
of data (all cookie data are strings)
Cookies might not be accepted by the browser
Cookies can get stale
→ Use Object in Server-side
(HttpSession)
10
HttpSession
A session is a continuous connection from the same browser over a fixed period of time. Default is 30 minutes for Servlet Container To maintain session information, Use session
with browser cookies or encodeURL
Javax.servlet.http package support
HttpSession interface
11
HttpSessionHow to obtain HttpSession objectHttpSession session = request.getSession(true); // read session id from cookie or encodeURL,and // if there are valid session object, return object. // else create new session with cookie
You can maintain a set of (key, value) paired information in the HttpSession object.
To store session-specific information, use the putValue(key, value) & getValue(key).
12
encodeURL If the browser doesn’t accept cookies, session id
is appended to each URL in the HTML responseWhen the rewritten URL is accessed, the server extracts the appended session idString URL encodeURL(String URL); session id is append to URL and return URL [URL] http://local/servlet/MyServlet?id=nannom [After encodeURL] http://local/servlet/MyServlet?id=nannom&JSevID= xxxxxxx
13
Session Implemention
Informations of HTTP transaction are managed by using HttpSession
→ Security, efficiency
To track the HttpSession, it is the best way that user accept cookie
14
JDBC
15
JDBC
Application 개발시 Database system 과의 연동이 필수적 → JDBC (Java Database Connectivity)
JDBC API Java 로 작성된 Program 을 일반 Database 에 연결하기 위한 API 제공
16
JDBC OverviewJDBC Overview
DB 와 User 사이에 Abstract Layer 제공 .
한가지 API 만을 이용하여 서로 상이한 DB 사용 가능 .
대부분의 DB Vendor 가 JDBC Spec. 에 따라 JDBC Driver 를 구현하여 제공 .
17
Java Application
JDBC Driver Manager
(java.sql.*)
JDBC Driver
JDBC API
JDBC Driver API
DB
18
JDBC DriverType I : JDBC-ODBC bridge plus ODBC driver
DataBase
JAVA 어플리케이션JAVA 어플리케이션
JDBC-ODBC BridgeJDBC-ODBC Bridge
기존의 ODBC 드라이버기존의 ODBC 드라이버
Native API( C/C++)Native API( C/C++)
DataBaseprotocol
19
Type II : Native-API partly-Java driver
( JDBC 의 호출을 각 DB Client API 로 변환하여 호출 )
20
Type III: JDBC-Net pure Java driver
21
Type IV: Native-protocol pure Java driver
22
장점JDBC 호출을 DBMS 의 고유한 Protocol 로
직접 변환해 처리하기 때문에 처리 속도가 가장 빠르다 .
Internet/Intranet 에 가장 적합한 방식
단점DB 고유의 Protocol 을 알고 있어야만 하므로
JDBC Driver Vendor 가 만들기에는 어렵고 주로 DBMS Vendor 에 의해 제공된다 .
23
java.sql package JDBC 2.0 core API
Major interface Making a connection with a data source
DriverManager class Connection interface
Sending SQL statements to a database Statement interface
Retrieving and updating the results of a query ResultSet interface
Throwing exceptions SQLException
24
Programming with JDBC API
1. DriverManager 에 해당 DBMS driver 등록Class.forName(String className );
“com.jk.jdbc.Driver”
2. 해당 Driver 로부터 Connection 객체 획득String jdbcURL="jdbc:jk:[email protected]:1433"; String user=“scott”; String passwd=“tiger”;
Connection conn=DriverManager.getConnection(jdbcURL, user, passwd);
25
3. Connection 객체로부터 Statement 객체 획득
Statement stmt=conn.createStatement();
4. Statement method 를 이용하여 SQL 실행ResultSet rset=stmt.executeQuery(“SELECT id, name FRO
M emp”);
5. 결과를 ResultSet 으로 받아서 처리while(rset.next()) {
System.out.println(“ 사번 :” + rset.getInt(“id”));System.out.println(“ 이름 :” + rset.getString(“name”)); }
6. 종료rset.close(); stmt.close(); conn.close();
26
Problems
Accessing the database can be slow
Lots of years and tears are spent optimizing database access
An obvious optimization is to reuse the JDBC connections
27
References
BooksProfessional Java server programming
Websitehttp://java.sun.com/servlethttp://www.javanuri.net (servlet/jsp lecture 7 ~ 9)