JSP Elements Chapter 2.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
Java Script Session1 INTRODUCTION.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
The Web Warrior Guide to Web Design Technologies
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
DT228/3 Web Development JSP: Directives and Scripting elements.
Three types of scripting elements: 1.Expressions 2.Scriptlets 3.Declarations Scripting elements.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Overview of JSP Technology. The need of JSP With servlets, it is easy to – Read form data – Read HTTP request headers – Set HTTP status codes and response.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
Introduction to Java Server Pages (JSPs) Robert Thornton.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
JSP Most of the web developers deploying web applications using servlets mixes the presentation logic and business logic. Separation of business logic.
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
Introduction to JavaServer Pages. 2 JSP and Servlet Limitations of servlet  It’s inaccessible to non-programmers JSP is a complement to servlet  focuses.
Chapter 6 Server-side Programming: Java Servlets
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaServer Page.
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Java Server Pages (JSP)
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Chapter 11 Invoking Java Code with JSP Scripting Elements.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
JSP. Types of JSP Scripting Elements Expressions of the form, which are evaluated and inserted into the servlet's output. Scriptlets of the form, which.
Web Technologies Java Beans & JSP By Praveen Kumar G.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
1 Chapter 27 JavaServer Page. 2 Objectives F To know what is a JSP page is processed (§27.2). F To comprehend how a JSP page is processed (§27.3). F To.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
JSP Directive and Objects. JSP Directives As discussed before There are 3 types of elements in JSP Directive Elements Scripting Elements Standard Action.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
World Wide Web has been created to share the text document across the world. In static web pages the requesting user has no ability to interact with the.
JSP: Actions elements and JSTL
Developing JavaServer Pages
Java Server Pages.
Java Servlets.
Scripted Page Web App Development (Java Server Pages)
Chapter 3: Using Methods, Classes, and Objects
Pre-assessment Questions
Knowledge Byte In this section, you will learn about:
Invoking Java Code from JSP
Java Server Pages.
PHP.
JSP Directives 1-Jan-19.
JSP implicit objects & directive elements
Tutorial 10: Programming with javascript
Introduction to JSP Dept. of B.Voc Software Development and System Administration St. Joseph’s College(Autonomous) Trichy-02 By Dr. J. Ronald Martin Introduction.
Presentation transcript:

JSP Elements Chapter 2

A JSP page is made out of a page template, which consists of HTML code and JSP elements such as scripting elements, directive elements, and action elements Scripting elements consist of code delimited by particular sequences of characters. <% and %> Implicit objects: application, config, exception, out, pageContext, request, response, and session request.getHeader(“user-agent”)

JSTL – standardized tag library Directive elements are messages to the JSP container <%@page language="java" contentType="text/html"%> include and taglib Action elements specify activities that, like the scripting elements, need to be performed when the page is requested Action elements can use, modify, and/or create objects, and they may affect the way data is sent to the output. <jsp:include page=“another.jsp”/> JSTL – standardized tag library EL – additional JSP component that provides easy access to external objects. Action elements – you can create addition tags

Scripting Elements and Java Scripting elements let you embed Java code in an HTML page. Every Java executable—whether it’s a free-standing program running directly within a runtime environment, an applet executing inside a browser, or a servlet executing in a container such as Tomcat—boils down to instantiating classes into objects and executing their methods.

Scriptlets A scriptlet is a block of Java code enclosed between <%and %>. For example, this code includes two scriptlets that let you switch an HTML element on or off depending on a condition: <% if (condition) { %> <p>This is only shown if the condition is satisfied</p> <% } %>

Expression An expression scripting element inserts into the page the result of a Java expression enclosed in the pair <%=and %>. For example, in the following snippet of code, the expression scripting element inserts the current date into the generated HTML page: <%@page import="java.util.Date"%> Server date and time: <%=new Date()%> In practice, it means that every Java expression will do, except the execution of a method of type void.

Declarations A declaration scripting element is a Java variable declaration enclosed between <%!and %>. It results in an instance variable shared by all requests for the same page

Data Types and Variables

String aString = “abcdxyz”; int k = aString.length(); char c = aString.charAt(4); Static final NAME = “John Doe”; Declaration <% int k = 0; %> // new variable is created for each incoming HTTP client request <%! int k = 0; %> // new variable is created for each new instance of the servlet <%! static int k = 0; %> //the variable is shared among all instances of the servlet

Special characters

Objects and Arrays To create an object of a certain type (i.e., to instantiate a class), use the keyword new. Integer integerVar = new Integer(55); Arrays of any object type or primitive data type int[] intArray1; int[] intArray2 = {10, 100, 1000}; String[] stringArray = {"a", "bb"}; int[] array = new int[10]; int[][] table1 = {{11, 12, 13}, {21, 22}}; int[][] table = new int[2][3];

int[][] table = new int[2][]; //allowed declaration

Operators, Assignments, and Comparisons a += b; // same as a = a + b; a++; // same as a += 1; a--; // same as a -= 1; Comparisons !=, >, >=, <, <= Typecasting – assigning long value to an int variable

Comparison warning String s1 = "abc"; String s2 = "abc"; String s3 = "abcd".substring(0,3); boolean b1 = (s1 == "abc"); // parentheses not needed but nice! boolean b2 = (s1 == s2); boolean b3 = (s1 == s3); &&, ||, ! – can be used to form more complex conditions ((a1 == a2) && !(b1 || b2)) B1 and b2 are true, but b3 is false. Comparisons operators don’t look inside the objects. They only check whether the objects are the same instance of a class, not whether they hold the same value. Equality operators are used to compare the memory locations of the two objects. Use .equals to compare contents

Selections The following statement assigns to the string variable sa different string depending on a condition: if (a == 1) { s = "yes"; } else { s = "no"; You can omit the else part. String s = (a== 1) ? "yes" : "no";

Or switch(a) { case 1: s = "yes"; break; default: s = "no"; }

Iterations for (initial-assignment; end-condition; iteration-expression) { statements; } while (end-condition) { statements; } for (;end-condition;) { statements; } do { statements; } while (end-condition);

Java variation of for loop String concatenate(Set<String> ss) { String conc = ""; Iterator<String> iter = ss.iterator(); while (iter.hasNext()) { conc += iter.next(); } return conc; } String concatenate(Set<String> ss) { String conc = ""; for (String s : ss) { conc += s; } return conc;

Implicit Objects Most commonly used implicit objects defined by Tomcat are out and request, followed by application and session. In general, <%=the_mysterious_object.getClass().getName()%>

The application Object Provides access to the resource shared within the web application if (application.getAttribute("do_it") != null) { /* ...place your "switchable" functionality here... */ }

Example to enable and disable conditional code

continuations

Example using an attribute to control logging

The config Object The exception Object The config object is an instance of the org.apache.catalina.core.StandardWrapperFacadeclass, which Tomcat defines to implement the interface javax.servlet.ServletConfig. Tomcat uses this object to pass information to the servlets. config.getServletName() The exception Object The exception object is an instance of a subclass of Throwable(e.g., java.lang.NullPointerException) and is only available in error pages.

Listing 2-7 shows you two methods to send the stack trace to the output. <%@page isErrorPage=“true”%>

<%@page errorPage=“stack_trace.jsp”%>

The out Object Use out like System.out <% out.print("abc"); %> out.print("a string" + intVar + obj.methodReturningString() + ".");

<%@page trimDirectiveWhitespaces="true"%> Ways to remove new lines <%@page trimDirectiveWhitespaces="true"%> - removes unnecessary spaces from the output, including the newlines.

The pageContext Object A class to access all objects and attributes of a JSP page The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four possible scopes. pageContext.removeAttribute("attrName", PAGE_SCOPE)

The request Object The request variable gives you access within your JSP page to the HTTP request sent to it by the client. Note: You cannot mix methods that handle parameters with methods that handle the request content, or methods that access the request content in different ways.

Listing the Headers

Example: User Authentication Tomcat-users.xml file is shared by all applications Read the other two examples

To password-protect all the pages inside a particular folder of an application, you have to edit the WEB-INF/web.xml file in the application’s root directory. Listing 2-11 shows you the code you need to insert inside the <web- app> element to limit the access of the pages in the folder /tests/auth/this/to users with the role canDoThis, and of the pages in the folder /tests/auth/that/to users with the role canDoThat.

The response Object The response variable gives you access within your JSP page to the HTTP response to be sent back to the client. The HttpServletResponse interface includes the definition of 41 status codes (of type public static final int) to be returned to the client as part of the response. The HTTP status codes are all between 100 and 599. The range 100–199 is reserved to provide information, 200–299to report successful completion of the requested operation, 300–399to report warnings, 400–499to report client errors, and 500–599 to report server errors. You will find the full list of errors at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. The normal status code is SC_OK (200), and the most common error is SC_NOT_FOUND (404), Working with Tomcat, the most common server error is SC_INTERNAL_SERVER_ERROR (500). You get it when there is an error in a JSP. You can use these constants as arguments of the sendErrorand setStatusmethods.

The session Object The term session refers to all the interactions a client has with a server from the moment the user views the first page of an application to the moment they quit the browser (or the session expires because too much time has elapsed since the last request). When Tomcat receives an HTTP request from a client, it checks whether the request contains a cookie that by default is named JSESSIONID. session.setAttribute("MyAppOperator", ""); boolean isOperator = (session.getAttribute("MyAppOperator") != null); if (isOperator) { ...

session.setAttribute("upref", preferences); In all the pages of your application, you can then retrieve that information with something like this: UserPrefs preferences = (UserPrefs)session.getAttribute("upref");

Directive Elements <%@directive-name attr1="value1" [attr2="value2"...] %> The page Directive Tell Tomcat that the scripting language is Java and that the output is to be HTML: <%@page language="java" contentType="text/html"%> Tell Tomcat which external class definitions your code needs <%@page import="java.util.ArrayList"%> <%@page import="java.util.Iterator"%> <%@page import="myBeans.OneOfMyBeans"%> <%@page import="java.util.ArrayList, java.util.Iterator"%> // for multiple class <%@page import="java.util.*"%> not good

In addition to language, contentType, and import, the page directive also supports autoFlush, buffer, errorPage, extends, info, isELIgnored, isErrorPage, isScriptingEnabled, isThreadSafe, pageEncoding, session, and trimDirectiveWhitespaces.

Simple program that utilizes the isThreadSafe attribute to test concurrency. Slows down execution.

alternative

Remaining page directives extends tells Tomcat which class the servlet should extend. info defines a string that the servlet can access with its getServletInfo()method. isELIgnored tells Tomcat whether to ignore EL expressions. isScriptingEnabled tells Tomcat whether to ignore scripting elements. pageEncoding specifies the character set used in the JSP page itself. session tells Tomcat to include or exclude the page from HTTP sessions.

The include Directive The taglib Directive The includedirective lets you insert into a JSP page the unprocessed content of another text file. <%@include file="some_jsp_code.jspf"%> The taglib Directive You can extend the number of available JSP tags by directing Tomcat to use external self- contained tag libraries. The taglib directory identifies a tag library and specifies what prefix you use to identify its tags. <%@taglib uri="http://mysite.com/mytags" prefix=”my”%> <my:oneOfMyTags> ... </my:oneOfMyTags> The following code includes the core JSP Standard Tag Library: <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>