Web Programming Networking Laboratory 1/30
Sungkyunkwan University
Copyright 2000-2012 Networking LaboratoryCopyright 2000-2018 Networking Laboratory
Chapter 15
Java Server Pages (JSP)
Prepared by J. Jung and H. Choo
Web Programming Networking Laboratory 2/30
Server & Client
The client requests the server a web page
The web server finds the web page and passes it to the client
Web Programming Networking Laboratory 3/30
Dynamic Web Page
Pages whose content changes according to the user’s request
Bulletin board, Blog, and Guestbook
You can write a helper program inside the server computer,
run it whenever you need it, get the results,
and return it to the client computer.
ClientWeb Server
CGI
Program
CGI
Program
Program
Program
ClientWebServer
Web Programming Networking Laboratory 4/30
Servlet
Efficient : Servlets are more efficient because they create threads to
service each request.
Convenient : Developers who know the Java language can use it.
Powerful : With Java Servlets, you can easily handle many tasks that
were very difficult with existing programs.
ClientWeb Server
Servlet
Thread
Thread
ClientWebServer
Servlet
Thread
Thread
Web Programming Networking Laboratory 5/30
JSP
JSP (Java Server Pages) is developed to solve these problems.
A server-side script language for building dynamic web pages on Java.
It is based on a Java servlet.
Insert Java code into
an HTML document
only when needed.
Web Programming Networking Laboratory 6/30
Tomcat
A kind of JSP engine
Tomcat = Web Server + JSP Container
Client Web Server Database
Apache Tomcat
JSP Servlet Engine
Internet
JSP files are
stored here.
Web Programming Networking Laboratory 7/30
Scriptlet
<% Announces
the start of Java code.
Any code block
is possible.%> Announces
the termination of Java code.
Web Programming Networking Laboratory 8/30
JSP Expression
You can put any formula
in the Java language.
This is a tag that means that
the JSP has been terminated.
<% Represents JSP and
= means Java formula.
Web Programming Networking Laboratory 9/30
<!DOCTYPE html><HTML><BODY>
<%java.util.Date date = new java.util.Date();%>안녕하세요? 현재시각은 <%= date %>입니다.
</BODY></HTML>
Various Scriptlet Syntax Example (1/3)
Understanding the syntax of scriptlet in JSP
Web Programming Networking Laboratory 10/30
<!DOCTYPE html><HTML><BODY>
<%System.out.println( "Print Date" );java.util.Date date = new java.util.Date();
%>안녕하세요? 현재시각은<%
out.println(String.valueOf( date ));%>입니다.
</BODY></HTML>
Various Scriptlet Syntax Example (2/3)
Understanding the syntax of scriptlet in JSP
Web Programming Networking Laboratory 11/30
<!DOCTYPE html><HTML><BODY>
<%java.util.Date date = new java.util.Date();
%>안녕하세요? 현재시각은<%
out.println(date);out.println("이고 ip주소는");out.println(request.getRemoteAddr());
%>입니다.
</BODY></HTML>
Various Scriptlet Syntax Example (3/3)
Understanding the syntax of scriptlet in JSP
Web Programming Networking Laboratory 12/30
<!DOCTYPE html><html> <head><title>주석테스트</title></head> <body> <h2>주석을테스트합니다.</h2> <%-- This comment is not displayed. --%> </body> </html>
JSP Comment Example
Understanding the syntax of comment statement in JSP
Web Programming Networking Laboratory 13/30
<!DOCTYPE html><%@ page import="java.util.*" %><HTML><BODY><%
Date date = new Date();%>안녕하세요? 현재시간은 <%= date %>입니다.</BODY></HTML>
JSP Import Example
Understanding the syntax of import statement in JSP
Web Programming Networking Laboratory 14/30
JSP Declaration
<%! Announces
the start of declaration.
Contains definitions of
variables and methods.
%> Announces
the termination of declaration.
Web Programming Networking Laboratory 15/30
JSP Declaration Example
<!DOCTYPE html><HTML><BODY><%@ page import="java.util.*" %><%!
Date date = new Date();Date getDate(){
return date;}
%>안녕하세요? 현재시각은 <%= getDate() %>입니다.</BODY></HTML>
Understanding the syntax of declaration statement in JSP
Web Programming Networking Laboratory 16/30
JSP Conditional Statement Example
<%! int day = 3; %> <html> <head><title>if/else 예제</title></head> <body><% if (day == 1 | day == 7) { %>
<p>오늘은주말입니다.</p><% } else { %>
<p>오늘은주말이아닙니다.</p><% } %></body> </html>
Understanding the syntax of conditional statement in JSP
Web Programming Networking Laboratory 17/30
JSP Loop Statement Example (1/2)
<%! int fontSize; %> <html> <head><title>Loop Statement Example</title></head> <body><%for ( fontSize = 1; fontSize <= 6; fontSize++) { %>
<font color="red" size="<%= fontSize %>">안녕하세요?</font><br />
<%}%></body> </html>
Understanding the syntax of loop statement in JSP
Web Programming Networking Laboratory 18/30
JSP Loop Statement Example (2/2)
<%@ page contentType="text/html; charset=utf-8" language="java" %><%String[] array={"홍길동","김철수","김영희"};%>
<html><body>
<%int i=0;for(i=0; i < array.length; i++) {
out.print("배열요소: " + array[i] + "<br/>");}
%></body></html>
Understanding the syntax of loop statement in JSP
Web Programming Networking Laboratory 19/30
Public database server
MySQL (1/2)
Client Web Server Database
Apache Tomcat
JSP Servlet Engine
Internet
JSP files are
stored here.
Web Programming Networking Laboratory 20/30
MySQL is an open-source relational database management
system (RDBMS).
MySQL is written in C and C++, so very fast.
MySQL works on many system platforms, Linux, macOS, Microsoft
Windows, etc.
MySQL software is Open Source.
MySQL Server works in client/server or embedded systems.
SQL(Structured Query Language): It is a special purpose programming
language designed to manage the data of a relational database
management system (RDBMS).
MySQL (2/2)
Web Programming Networking Laboratory 21/30
MySQL - JSP Example (1/9)eBookShop (1/9)
Understanding the syntax of combining JSP and MySQL
Web Programming Networking Laboratory 22/30
Install MySQL Community Installer
Install MySQL Server and Connector/J
Copy MySQL database library for fixing error
Copy mysql-connector-java-x.x.xx.jar to (Tomcat installation directory)/lib.
Create Database
Uses the utf-8 version of the command line client
Create Web Application
Create a directory called ebookshop to (TomcatDirectory)/webapps.
Run with a web browser using http://localhost:8080/ebookshop/order.jsp
MySQL - JSP Example (2/9)eBookShop (2/9)
Web Programming Networking Laboratory 23/30
MySQL - JSP Example (3/9)eBookShop (3/9) – order.jsp
<%@ page import="java.sql.*" %> <%--자바라이브러리 import --%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%-- JSP 선언 --%>
<% request.setCharacterEncoding("utf-8"); %>
<html>
<head>
<title>온라인서점예제</title>
</head>
<body>
<h1>인터넷프로그래머문고</h1>
<h3>제목을입력하세요:</h3>
<form method="post">
책제목:
<input type="text" name="title">
<br />
<input type="submit" value="검색">
</form>
Web Programming Networking Laboratory 24/30
MySQL - JSP Example (4/9)eBookShop (4/9) – order.jsp
<%String title = request.getParameter("title"); // title 키에저장된 value 수신if (title != null) {Class.forName("com.mysql.jdbc.Driver"); // MySQL 연결 (JDBC_URL, ID, PW)Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/book_db", "root", "1234");Statement stmt = conn.createStatement();String sqlStr = "SELECT * FROM book_table WHERE title LIKE '%" + title + "%' ORDER BY title ASC";ResultSet rset = stmt.executeQuery(sqlStr); // SQL 구문실행 %>
<hr /><form method="post" action="order_result.jsp"> <!-- submit 할경우 order_result.jsp로 id 값전송 -->
<table border="2"><tr>
<th>주문</th><th>저자</th><th>제목</th><th>가격</th><th>수량</th>
</tr>
Web Programming Networking Laboratory 25/30
MySQL - JSP Example (5/9)eBookShop (5/9) – order.jsp
<%
while (rset.next()) { // 다음 SQL 실행결과가있는경우
int id = rset.getInt("id");
%>
<tr>
<td><input type="checkbox" name="id" value="<%= id %>"></td>
<td><%= rset.getString("author") %></td>
<td><%= rset.getString("title") %></td>
<td><%= rset.getInt("price") %>won</td>
<td><%= rset.getInt("qty") %></td>
</tr>
<%
}
%>
</table>
<br />
Web Programming Networking Laboratory 26/30
MySQL - JSP Example (6/9)eBookShop (6/9) – order.jsp
<input type="submit" value="주문">
<input type="reset" value="초기화">
</form>
<a href="<%= request.getRequestURI() %>">
<h3>재주문</h3>
</a>
<%
// 연결종료
rset.close();
stmt.close();
conn.close();
}
%>
</body>
</html>
Web Programming Networking Laboratory 27/30
MySQL - JSP Example (7/9)eBookShop (7/9) – order_result.jsp
<%@ page import="java.sql.*" %> <%--자바라이브러리 import --%><html><head><title>Order Screen</title>
</head><body><h2>주문해주셔서감사합니다.</h2><%
String[] ids = request.getParameterValues("id"); // id 키에저장된 value 배열수신if (ids != null) {Class.forName("com.mysql.jdbc.Driver"); // MySQL 연결 (JDBC_URL, ID, PW)Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/book_db", "root", "1234");Statement stmt = conn.createStatement();
%><table border="2">
<tr><th>저자</th><th>제목</th><th>가격</th><th>수량</th>
</tr>
Web Programming Networking Laboratory 28/30
MySQL - JSP Example (8/9)eBookShop (8/9) – order_result.jsp
<%
for (int i = 0; i < ids.length; i++) {
String sqlStr1 = "UPDATE book_table SET qty = qty - 1 WHERE id = " + ids[i]; // 재고수량변경
stmt.executeUpdate(sqlStr1);
String sqlStr2 = "SELECT * FROM book_table WHERE id = " + ids[i]; // 재고수량변경후다시조회
ResultSet rset = stmt.executeQuery(sqlStr2);
while (rset.next()) { // 다음 SQL 실행결과가있는경우
%>
<tr>
<td><%= rset.getString("author") %></td>
<td><%= rset.getString("title") %></td>
<td><%= rset.getInt("price") %>won</td>
<td><%= rset.getInt("qty") %></td>
</tr>
Web Programming Networking Laboratory 29/30
MySQL - JSP Example (9/9)eBookShop (9/9) – order_result.jsp
<%
}
rset.close();
}
// 연결종료
stmt.close();
conn.close();
}
%>
</table>
<a href="order.jsp">
<h3>주문화면으로돌아가기</h3>
</a>
</body>
</html>
Web Programming Networking Laboratory 30/30
Q & A
Top Related