Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
데이타베이스시스템연구실Database Systems Lab.
충남대학교컴퓨터공학과
데이타베이스시스템연구실
11. JSP I
http://www.tutorialspoint.com/jsp/index.htm
What is JavaServer Pages?JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications.
A technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
Overview
2
Advantages of JSPOffer several advantages in comparison with the CGI
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files
JSP are always compiled before it’s processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servelts API, so like Servelts, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc
JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines
Overview (cont’d)
3
CGI(Common Gateway Interface)
4
최초의웹애플리케이션기술
웹애플리케이션을독립적인프로그램형태로작성
문제점각프로그램이하나의프로세스로수행됨
독립적인프로그램실행을하기위해시스템자원이많이필요
그결과웹서버로많은요청이한꺼번에들어오면너무많은 CGI프로그램의프로세스가동시에실행되어컴퓨터전체가다운되는일이빈번히발생
서블릿(Servlet)
5
자바를기반으로하는웹애플리케이션프로그래밍기술
처음에 Sun Microsystems의해개발되었지만, 그후에자바표준개발을전담하는기관인 JCP(Java community Process)로이관되어서발전
자바클래스형태로웹애플리케이션작성이클래스를서블릿클래스라함
서블릿클래스의예
6
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;Public class HundredServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
printWriter out = response.getWriter();out.printIn(“<HTML>”);out.printIn(“<HEAD><TITLE>Sum of 1 to 100</TITLE></HEAD>”);out.printIn(“<BODY>”);int total = 0;for(int cnt =1;cnt <=100; cnt++)
total += cnt ;out.printIn(“1+2+3+ …+100 = “+total);out.printIn(“</BODY>”);out.printIn(“</HTML>”);
}}
HttpServlet클래스를상속
doGet또는 doPost매서드안에서블릿클래스가해야할일을써넣음
HttpServletResponse파라미터를이용해서HTML 코드를출력함
서블릿장점과단점
7
장점자바의플랫폼독립성:서블릿실행코드를다양한운영체제에서수행가능
네트워크환경에서보안이용이
시스템부하가적은멀티스레드기능이지원됨
단점프로그래밍작업의효율성이떨어짐
HTML 코드가자바코드안으로들어가는구조로인함
이러한구조는서블릿클래스가출력하는동적 HTML 문서의구조를이해하기어렵게함
또한, 웹페이지의디자인작업을위해서도소스코드에손을대게만드는비효율성을낳음
자바의유용한장점을살리면서서블릿기술의단점을보완하는새로운기술 JSP가개발됨
JSP (JavaServer Pages)
8
자바를기반으로한웹애플리케이션
JSP는웹애플리케이션서버의서블릿컨테이너에서서블릿원시코드로변환된후에서블릿원시코드는바로컴파일된후실행
JSP페이지는HTML 문서에자바코드가삽입되는구조
<%@ page contentType=“text/html; charset=UTF-8”%><HTML><HEAD><TITLE>1부터 100까지의합</TITLE></HEAD><BODY><% int total = 0;
for (int cnt=1; cnt <= 100; cnt++)total += cnt;
%>1부터 100까지의합은? <%=total %></BODY></HTML>
자바코드
JSP (JavaServer Pages) (cont’d)
9
<% …. %>, <%= … %>
JSP 문법
이태그안에자바프로그래밍언어로작성된코드가있음
이코드는웹서버에서실행됨
<%..%> : 1부터 100까지의수를더해서 total변수에대입
<%= …%> : total 변수의값을웹브라우저로전송
웹디자이너가그대로가져다가디자인작업을할수있고, 디자인작업이끝나면프로그래머가다시가져다가자바부분을수정할수있음
The web server needs a JSP engine ie. container to process JSP pages. JSP container is responsible for intercepting requests for JSP pages.
Apache has built-in JSP container(Tomcat) to support JSP pages development
Architecture
10
JSP Processing
Architecture (cont’d)
11
As with a normal page, your browser sends an HTTP request to the web server
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
This is done by using the URL or JSP page which ends with .jsp instead of .html
The JSP engine loads the JSP page from disk and converts it into a servlet content.
All template text is converted to println( ) statements
All JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response.
Architecture (cont’d)
12
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.
Architecture (cont’d)
13
JSP 기초문법
14
JSP 문법의형태1. <%...... %>
2. ${……...}
3. XML 태그형태 : <jsp:forward>나 <c:if>
<%....%>로끝나는문법지시자(directive)
스크립팅요소(scripting elements) : scriptlet과 expression
${…}로끝나는문법익스프레션언어(expression language)
XML 태그형태로기술액션(Action)
JSP의문법 -지시자와스크립트요소예
15
<%@ page contentType=“text/html; charset=UTF-8”%><HTML>
<HEAD><TITLE>1부터 100까지의합</TITLE></HEAD><BODY>
<%int total = 0;for (int cnt=1; cnt <= 100; cnt++)
total += cnt;%>
1부터 100까지의합은? <%=total %></BODY></HTML>
지시자(directive)
스크립틀릿(scriptlet)
익스프레션(expression)
The ScriptletContain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
The syntax of Scriptlet
Example Try it!
Syntax :Scriptlet
16
<% code fragment %>
<html><head><title>Hello World</title><head><body>Hello World!<br><% out.println("Your IP address is " + request.getRemoteAddr()); %></body></head>
JSP DeclarationsDeclares one or more variables or methods that you can use in Java code later in the JSP files.
The syntax of JSP Declarations
Example
Syntax : JSP Declaration
17
<%! declaration; [declaration; ] + …. %>
<%! int i=0; %><%! int a, b, c; %><%! Circle a= new Circle(2.0) ; %>
JSP ExpressionJSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The syntax of JSP Expression
Example Try it
Syntax : JSP Expression
18
<%= expression %>
<html><head><title>A Comment Test</title><head><body><p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> </body></head>
JSP CommentsThe syntax of JSP Comments
Example Try it!
Syntax : JSP Comments
19
<%-- This is JSP comment -- %>
<html><head><title>A Comment Test</title><head><body><h2> A Test of Comments </h2> <%-- This comment will not be visible in the page source --%></h2> </body></head>
A small numbers of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially
Syntax : JSP Comments (cont’d)
20
Control-Flow StatementsYou can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc
Decision-Making StatementsIf…else block. Try it!
Syntax : Control-Flow Statement
21
<%! int day = 3; %><html><head><title>IF...ELSE Example</title></head><body><% if (day == 1 | day ==7) { %>
<p> Today is weekend</p><% } else {%>
<p> Today is not weekend</p><% } %></body></html>
switch…case block Try it!
Syntax : Control-Flow Statement (cont’d)
22
<%! int day = 3; %><html><head><title>SWITCH...CASE Example</title></head><body><% switch(day) {case 0:
out.println("It\'s Sunday.");break;
case 1:out.println("It\'s Monday.");break;
case 2:out.println("It\'s Tuesday.");break;
case 3:out.println("It\'s Wednesday.");break;
case 4:out.println("It\'s Thursday.");break;
case 5:out.println("It\'s Friday.");break;
default:out.println("It\'s Saturday.");
}%></body></html>
Loop StatementsYou can also use three basic types of looping blocks in Java : for, while, and do…while blocks in your JSP programming.
for loop Try it!
Syntax : Control-Flow Statement (cont’d)
23
<%! int fontSize; %><html><head><title>FOR LOOP Example</title></head><body><%for (fontSize =1;fontSize <=3;fontSize++) { %>
<font color="green" size="<%=fontSize %>">JSP Tutorial</font><br>
<% } %></body></html>
while loop
Syntax : Control-Flow Statement (cont’d)
24
<%! int fontSize; %><html><head><title>FOR LOOP Example</title></head><body><%while (fontSize <=3) { %>
<font color="green" size="<%=fontSize %>">JSP Tutorial</font><br>
<%fontSize++; %><%}%></body></html>
JSP OperatorsFollowing table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom
Syntax : Operators
25
JSP LiteralsBoolean : true and false
Integer : as in Java
Floating point : as in Java
String : with single and double quotes; “ is escaped as \”, ‘is escaped as \’, and \ is escaped as \\
Null : null
Syntax : Literals
26
지시자의문법
27
목적웹컨테이너가 JSP 페이지를서블릿클래스로변환할때필요한여러가지정보들을기술하기위해사용하는문법
구성page 지시자
JSP 페이지전체에적용되는정보를기술
include 지시자
JSP 페이지에포함시킬파일
taglib지시자
해당페이지가 taglib library를사용할것인지의여부
Tag library의URI
지시자이름
<%@ page 애트리뷰트_목록%>
<%@ include 애트리뷰트_목록%>
<%@ taglib 애트리뷰트_목록%>
JSP DirectivesJSP directive affects the overall structure of the servlet class
Usually has the following form
Three types of directive tag
Syntax : JSP Directives
28
<%@ directive attribute =“value” %>
JSP ActionsUse constructs in XML syntax to control the behavior of the servlet engine.
You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin
Syntax
Syntax : JSP Actions
29
<jsp:action_name attribute=“value”>
Basically predefined functions
Syntax : JSP Actions (cont’d)
30
JSP Implicit Objects
Syntax : Implicit Object
31