Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 12 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
12
Dung lượng
1,4 MB
Nội dung
21/07/2009 1 JavaServerPages http://www.vovanhai.wordpress.com 1 JSP Basics 2 JSP JavaServer Page (JSP) is a server side script language Saved with .jsp extension A simple, yet powerful Java technology for creating and maintaining dynamic-content webs pages JSP page are converted by the web container into a Servlet instance It focus on the presentation logic of the web application 3 Architecture of JSP 4 JSP Expression Includes expression in a scripting language page 5 Scriptlet Refers to code blocks executed for every request. 6 21/07/2009 2 Declarations Defines the variables and methods for a JSP page 7 Comments Explains the functioning of the code Comments are ignored by the servlet during compilation Syntax <!–- HTML comments > <% JSP comments %> <% /*Scripting languages comments*/ %> 8 Directives Controls the structure of the servlet by sending messages from the JSP page to the JSP container. Specify the scripting language to used. Denote the use of custom tag library in a JSP page. Be used to include the content of another JSP page. … Syntax <%directivename attribute = “value”%> Specifies the JSP directive Refers to the directive attribute 9 Directives – Contd… The types of JSP directives are: page - Associates the attributes that affect the entire JSP page include - Sends message to the JSP container to include the contents of one file into another taglib - Enables the use of custom tags in the JSP page 10 page Directive 11 include Directive 12 21/07/2009 3 taglib Directive 13 Standard Actions Tags affecting the behavior of JSP at runtime and the response sent back to web browser Syntax: <jsp: standard action> Standard Action Description <jsp: useBean> Accesses the functions of custom tags <jsp: param> Provides name and value to the parameters used by the JSP page <jsp: include> Includes the output from one file into the other files <jsp: forward> Transfers control from a JSP page to another <jsp: plugin> Uses a plugin to execute an applet or bean 14 JSP Implicit Object 15 Implicit Objects Are loaded by the Web Container automatically and maintains them in a JSP page The names of the implicit objects are reserved words of JSP Access dynamic content using JavaBeans Types of implicit objects 16 Implicit Objects (cont) Object Class / Interface page javax.servlet.jsp.HttpJspPage config javax.servlet.ServletConfig request javax.servlet.http.HttpServletRequest response javax.servlet.http.HttpServletResponse out javax.servlet.jsp.JspWriter session javax.servlet.http.HttpSession application javax.servlet.ServletContext pageContext javax.servlet.jsp.PageContext exception java.lang.Throwable 17 The request Object 18 Represents the request from the client for a Web page Controls information associated with a request from client Includes the source, URL, headers, cookies and parameters 21/07/2009 4 The response Object 19 Manages the response generated by JSP container and sends response to the client Is passed as a parameter to JSP _jspService() method The out Object 20 Represents the output stream, then it will be sent to the client as a response for the request Is has page scope The session Object 21 Provides all the objects available in the JSP pages within the session The application Object 22 Is used to share the data between all application pages Can be accessed by any JSPpresent in the application The pageContext Obbject (1) 23 Provides methods to access all attributes defined by implicit objects in the page. Provides methods to transfer control from one web page to another osetAttribute() ogetAttribute() ogetAttributeNamesInScope() oremoveAttribute() The pageContext Obbject (2) 24 Find the scope or specify the scope 21/07/2009 5 Servlet Object (1) 25 The page object: is an instance of the servlet processing the current request in a JSP page. Servlet Object (2) 26 The “config” Object: oStores the information of the servlet oRepresents the configuration of the servlet data where a JSP page is compiled oIt has page scope The exception Object 27 Is used to handle errors in a JSPpage Is used to trace the exception thrown during the execution It has page scope Error handling <%@page errorpage=“error.jsp”%> < some of code,… > index.jsp error.jsp <%@page isErrorPage=“true”%> <% if(exception!=null){ out.println(exception.getMessage()); } %> 28 Standard Actions 29 Standard Actions 30 Are XML like tags which take the form of an XML tag with a name prefixedjsp Are used for Forwarding requests and performing includes in page Embedding the appropriate HTML on pages Interacting between pages and JavaBeans Providing additional functionality to tag libraries Syntax: <jsp:actionName attribute=“value”> </jsp:actionName> Someproperties Using <jsp> prefix The attributes are case sensitive Value in the attributes must be enclosed in double quotes Standard actions can be either an empty or a container tag 30 21/07/2009 6 <jsp:include> 31 Include either static or dynamic file in jsp file at the time of page request. Static case: The content is included in the calling jsp file. Dynamic case: it acts on the request and send back a result that is include in the JSP page. Syntax: <jsp:include: page=“webURL”|<%=exp%> flush=“true”/> <jsp:forward> 32 It’s used to forward the request and response to another jsp page or servlet Syntax: <jsp:forward page=“{webURL|<%=exp%>}”> <jsp:param name=“{paramName|<%=exp%>”}/> <jsp:forward> Allow to pass one or more name/value pairs as parameters to an included or forwarded resource like a jsp page. Syntax: <jsp:param name=“thename” value=“{thevalue|<%=exp%>}” <jsp:param> <jsp:plugin> 33 Used in the execution of an applet or bean. Syntax: <jsp:plugin type=“bean|applet” code=“ClassFileName” codebase=“classFileDirectoryName” <jsp:params> <jsp:param name=“thename” value=“thevalue”> </jsp:params> [<jsp:fallback> display message to user</jsp:fallback> </jsp:plugin> <jsp:fallback> 34 Display a text message to user if the plug- in could not start. Syntax: <jsp:fallback> html message </jsp:fallback> JavaBeans 35 Concept 36 JavaBeans are reusable components that can be deployed in java. Define the interactivity of Java object Allow creation of graphical components that can be reused in GUI application. Can be embedded in multiple applications, servlet and jsp. Requirements: o Be a public class o Have a public constructor with no arguments o Have get/set methods to read/write bean properties Components of JavaBeans: ◦ Properties Getters and setters ◦ Methods ◦ Events 21/07/2009 7 <jsp:useBean> Is used to create a reference and include an existing bean component in JSP The <jsp:useBean> follows to locate or instantiate the Bean Attemps to locate a Bean within the scope Defines an object reference variable with the name Stores a reference to it in the variable, if it retrieves the Bean Instantiates it from the specified class, it is cannot retrieve the Bean Syntax: <jsp:useBean id=“name” class=“class” scope=“page/session/request/application” /> 37 <jsp:getProperty> 38 Using for retrieve properties value of the Bean. Retrieves a bean property value using the getter methods and displaysthe output in a JSP page The <jsp:getProperty> and expression convert the value into a string and insert it into an implicit out object Some drawbacks Fails toretrieve the values of indexes property Fails todirectlyaccess enterprise bean components Syntax: <jsp:getProperty name=“Bean_Alias” property=“PropertyName”/> <jsp:setProperty> 39 Retrieves a bean property value using the getter methods and displays the output in a JSP page The <jsp:getProperty> and expression convert the value into a string and insert it into an implicit out object Some drawbacks: ◦ Fails to retrieve the values of indexes property ◦ Fails to directly access enterprise bean components Syntax: <jsp:setProperty name=“Bean_Alias” property=“Property_Name” value=“TheValue” param=“Parameter”/> JavaBeans & Scriptlets 40 JavaBeans can be accessed from scripting element in differentways.Do it likes in J2SE. The JSP container converts the string values into non string values by the attribute values that evaluate the correct data type to set the propertyvalue Expression Language 41 Expression Language (EL) 42 New feature of JSP 2.0 Allows JSP developers to access java objects via a compact, easy-to-use shorthand style (similar to JavaScript) It can handle both expressions and literals Developed by two groups JSP Standard Tag Library expert group JSP 2.0 expert group Syntax: ${EL Expression} 21/07/2009 8 EL Implicit Objects 43 Implicit Objects pageContext cookie initParam paramValuesparam header headerValues application servletContext request session response Request Headers and Parameters 44 param: return a value that maps a request parameter name to a single string value ex: "${param.Name}“ paramValues: return an array of values is mapped to the request parameters from client ex: “${paramValues.Name[0]}” header: return a request header name and maps the value to single string value. ex: ${header[“host”]} headerValues: return an array of values is mapped to the request header ex: ${headerValues.Name} cookie: returns the cookies name mapped to the single cookie object ex: ${cookie.name.value} initParam: returns a context initialization parameter name, which is mapped to a single value. Scope variables (1) 45 Variables are used to store and access values in JSP program Variable refers as a attributes that are stored in standard scope such as page, request, session and application Dot operator . or square brackets [ ] can be used to access value of variable Example ${pageScope.color} ${pageScope[“color”]} Scope Variables (2) 46 EL Operators 47 * / or div + - % or mod < or lt > or gt < = or le > = or ge = = or eq != or ne && or and || or or ! or not empty Operators Empty LogicalRelational Arithmetic Example 48 21/07/2009 9 JSP Standard Tag Library (JSTL) 49 Concept JSTL provides a set of reusable standard tag that work for create jsp pages. JSTL allows programming using tags rather than scriptlet code. JSTL has tags, such as: ◦ Iterators and conditional tags ◦ Internationalization tags ◦ SQL tags 50 Types Of Tags Libraries 51 JSP Standard Tag Library (JSTL) Core Tag Library I18N & Formatting Tag Library SQL Tag Library XML Tag Library Core Tag Library 52 General Purpose Tags Decision Making Tags Iteration Tags set remove out forEach forTokensif choose Core Tag Library General Purpose Tags 53 <c:set>: assigns a value to a variable in scope <c:remove>: remove a scope variable <c:out>: evaluate an expression and store a result in the current JspWriter object. <c:catch>: provides an exception handling functionality, such as try-catch inside jsp pages without using scriptlet Syntax: <c:set var=“varName” value=“value” scope=“page|request|session|application” /> <c:remove var=“varName” scope=“page|request|session|application” /> <c:out value=“value|expression” escapeXml=“true|false” default=“defaultValue” /> <c:catch /> Example 54 21/07/2009 10 Decision-Making Tags 55 <c:if>: used for conditional execution of the code <c:choose>: similar switch statement in java Iteration Tags 56 <c:forEach>: used to repate the body content over a collection of objects. <c:forTokens>: used to iterate over a collection of tokens separated by user-specified delimiters. SQL Tag Library 57 SQL Tag Library setDataSource query update paramtransaction The sql:setDataSource Tag 58 The sql:query Tag The sql:update Tag 59 The sql:param Tag 60 [...]... product or service language, cultural and local “look and feel” specific A Locale is a simple object identifying a specific language and geographic region (java. lang.Locale) Is denoted by xx_YY (language code_letter country) Unicode in Java, is a 16 bit character encoding Resource Bundles contain locale-specific objects Internationalization(I18N) 63 Internationalizing (1) Internationalizing . Syntax: < ;jsp: plugin type=“bean|applet” code=“ClassFileName” codebase=“classFileDirectoryName” < ;jsp: params> < ;jsp: param name=“thename” value=“thevalue”> < /jsp: params> [< ;jsp: fallback> display message to user< /jsp: fallback> < /jsp: plugin> < ;jsp: fallback> 34 . like a jsp page. Syntax: < ;jsp: param name=“thename” value=“{thevalue|<%=exp%>}” < ;jsp: param> < ;jsp: plugin> 33 Used in the execution of an applet or bean. Syntax: < ;jsp: plugin type=“bean|applet” code=“ClassFileName” codebase=“classFileDirectoryName” < ;jsp: params> < ;jsp: param. custom tags < ;jsp: param> Provides name and value to the parameters used by the JSP page < ;jsp: include> Includes the output from one file into the other files < ;jsp: forward> Transfers