Chapter-6 Java Server Page Notes

Slides:



Advertisements
Similar presentations
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
Advertisements

Java Server Pages Jeffrey Jongko. Introduction Java Server Pages (JSP) technology was created by Sun Microsystems and is built on top of Sun’s Java Servlet.
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
The JSP Directives Vijayan Sugumaran School of Business Administration Oakland University Parts of this lecture provided by Coreservlets.com.
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
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.
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.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
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.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Introduction to Java Server Pages (JSPs) Robert Thornton.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Jordan Anastasiade. All rights reserved.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
 Embeds Java code  In HTML tags  When used well  Simple way to generate dynamic web-pages  When misused (complex embedded Java)  Terribly messy.
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.
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.
Java Server Pages Introduction. Servlet Drawbacks Web page designer will need to know servlets to design the page. Servlet will have to be compiled for.
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.
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.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
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.
Chapter 14 Using JavaBeans Components in JSP Documents.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
JSP Java Server Pages. Hello, !
Developing JavaServer Pages
Java Server Pages.
Java Server Pages By: Tejashri Udavant..
COMP9321 Web Application Engineering Semester 2, 2017
Scripted Page Web App Development (Java Server Pages)
Pre-assessment Questions
Introduction to JSP Java Server Pages
Knowledge Byte In this section, you will learn about:
Invoking Java Code from JSP
Java Server Pages (JSP)
Java Server Pages JSP 11/11/2018.
Java Server Pages.
JSP Directives 1-Jan-19.
JSP implicit objects & directive elements
COSC 2956 Internet Tools Java Server Pages.
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.
Scripted Page Web Application Development (Java Server Pages)
Web Technologies Java Beans & JSP
Presentation transcript:

Chapter-6 Java Server Page Notes

JSP Overview A JavaServer page (JSP) is a template for a Web page that uses Java code to generate an HTML document dynamically. JSPs are run in a server-side component known as a JSP container, which translates them into equivalent Java servlets. For this reason, servlets and JSP pages are intimately related. What’s possible in one is, in large part, also possible in another, although each technology has its individual strengths. Because they are servlets, JSP pages have all the advantages of servlets: ■ They have better performance and scalability than CGI scripts because they are persistent in memory and multithreaded. ■ No special client setup is required. ■ They have built-in support for HTTP sessions, which makes application programming possible.

■ They have full access to Java technology–network awareness, threads, and database connectivity—without the limitations of client-side applets. But, in addition, JSP pages have advantages of their own: ■ They are automatically recompiled when necessary. ■ Because they exist in the ordinary Web server document space, addressing JSP pages is simpler than addressing servlets. ■ Because JSP pages are HTML-like, they have greater compatibility with Web development tools.

How JSP Works A JSP page exists in three forms: ■ JSP source code This is the form the developer actually writes. It exists in a text file with an extension of .jsp, and consists of a mix of HTML template code, Java language statements, and JSP directives and actions that describe how to generate a Web page to service a particular request. ■ Java source code The JSP container translates the JSP source code into the source code for an equivalent Java servlet as needed. This source code is typically saved in a work area and is often helpful for debugging. ■ Compiled Java class Like any other Java class, the generated servlet code is compiled into byte codes in a .class file, ready to be loaded and executed.

The JSP container manages each of these forms of the JSP page automatically, based on the timestamps of each file. In response to an HTTP request, the container checks to see if the .jspsource file has been modified since the .javasource was last compiled. If so, the container retranslates the JSP source into Java source and recompiles it. Figure 5-1 illustrates the process used by the JSP container. When a request for a JSP page is made, the container first determines the name of the class corresponding to the .jspfile. If the class doesn’t exist or if it’s older than the .jspfile (meaning the JSP source has changed since it was last compiled), then the container creates Java source code for an equivalent servlet and compiles it. If an instance of the servlet isn’t already running, the container loads the servlet class and creates an instance. Finally, the container dispatches a thread to handle the current HTTP request in the loaded instance.

Components of a JSP Page A .jsp file can contain JSP elements, fixed template data, or any combination of the two. JSP elements are instructions to the JSP container about what code to generate and how it should operate. These elements have specific start and end tags that identify them to the JSP compiler. Template data is everything else that is not recognized by the JSP container. Template data (usually HTML) is passed through unmodified, so the HTML that is ultimately generated contains the template data exactly as it was coded in the.jsp file.

Elements of JSP Three types of JSP elements exist Directives Scripting elements, including expressions, scriptlets, and declarations Actions

Directives Directives are instructions to the JSP container that describe what code should be generated. They have the general form <%@ directive-name [attribute="value" attribute="value" ...] %> The JSP 1.1 specification describes three standard directives available in all compliant JSP environments: page include Taglib

The page Directive The page directive is used to specify attributes for the JSP page as a whole. It has the following syntax: <%@ page [attribute="value" attribute="value" ...] %> where the attributes are any of those listed in Table

page Directive Example <%@page import ="java.util.Date"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Todays Date</title> </head><%Date date = new Date(); %> <body> <h1>Todays Date</h1> <p>Todays date :<%=date %></p> </body> </html>

Attributes of the Page Directive Value Attribute The language used in scriptlets, expressions, and declarations. In JSP 1.1, the only valid value for this attribute is java. language The fully qualified name of the superclass of this JSP page. This must be a class that implements the HttpJspPage interface. The JSP specification warns against the use of this attribute without fully understanding its implications. extends A comma-separated list of one or more package.* names and/or fully qualified class names. This list is used to create corresponding import statements in the generated Java servlet. The following packages are automatically included and need not be specified:java.lang.* java.servlet.* java.servlet.jsp.* java.servlet.http.* Import true or false, indicating whether the JSP page requires an HTTP session. If the value is true, then the generated servlet will contain code that causes an HTTP session to be created (or accessed, if it already exists). The default value is true. session Specifies the size of the output buffer. Valid entries are nnnkb or none, where nnn is the number of kilobytes allocated for the buffer. The default value is 8kb. buffer true if the buffer should be automatically flushed when it is full, or false if a buffer overflow exception should be thrown. The default value is true. autoflush true if the page can handle simultaneous requestsfrom multiple threads, or false if it cannot. If false,the generated servlet declares that it implements the SingleThreadModelinterface. isThreadSafe A string that will be returned by the page’s getServletInfo()method. Info true if this page is intended to be used as another JSP’s error page. In that case, this page can be specified as the value of the errorPageattribute in the other page’s pagedirective. Specifying true for this attribute makes the exception implicit variable available to this page. The default value is false. isErrorPage Specifies the URL of another JSP page that will be invoked to handle any uncaught exceptions. The other JSP page must specify isErrorPage="true" in its pagedirective. errorPage Specifies the MIME type and, optionally, the character encoding to be used in the generated servlet. contentType Note: More than one page directive can be in a file and the attributes specified collectively apply to the whole file, but no attribute can be specified more than once, with the exception of the importattribute.

The include Directive The include directive merges the contents of another file at translation time into the .jsp source input stream, much like a #includeC preprocessor directive. The syntax is <%@ include file="filename" %> where filename is an absolute or relative pathname interpreted according to the current servlet context. Examples would be <%@ include file="/header.html" %> <%@ include file="/doc/legal/disclaimer.html" %> <%@ include file="sortmethod" %> The include directive contrasts with the <jsp:include>action ,which merges the output of another file at request time into the response output stream. Either element can be used to include standard headers and footers or other common text in JSP pages.

The taglib Directive The taglib directive makes custom actions available in the current page through the use of a tag library. The syntax of the directive is <%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %> where the attributes are those listed here:

tagLibraryURI tagPrefix The URL of a Tag Library Descriptor. A unique prefix used to identify custom tags used later in the page

Expressions JSP provides a simple means for accessing the value of a Java variable or other expression and merging that value with the HTML in the page. The syntax is <%= exp %> where exp is any valid Java expression. The expression can have any data value, as long as it can be converted to a string. This conversion is usually done simply by generating an out.print()statement. For example, the JSP code The current time is <%= new java.util.Date() %>

Scriptlets A scriptlet is a set of one or more Java language statements intended to be used to process an HTTP request. The syntax of a scriptlet is <% statement; [statement; ...] %>

Scriptlet Example <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IP Address</title> </head> <body> <%out.println("Your IP Address:"+request.getRemoteAddr()); %> </body> </html>

Declarations Like scriptlets, declarations contain Java language statements, but with one big difference: scriptlet code becomes part of the _jspService()method, whereas declaration code is incorporated into the generated source file outside the _jspService()method. The syntax of a declaration section is <%! statement; [statement; ...] %>

Implicit Objects Although scriptlets, expressions, and HTML template data are all incorporated into the _jspService()method, the JSP container writes the skeleton of the method itself, initializing the page context and several useful variables. These variables are implicitly available inside scriptlets and expressions (but not declarations). They can be accessed like any other variable, but do not have to be declared first. For example, the HttpServletRequestobject passed to _jspService()is available under the name request, as shown in the following scriptlet: <% String accountNumber = request.getParameter("acct"); if (accountNumber == null) { // ... handle the missing account number problem }%>

Implicit Variables Value Variable Name The ServletRequestor HttpServletRequest being serviced. request The ServletResponseor HttpServletResponse that will receive the generated HTML output. response The PageContextobject for this page. This object is a central repository for attribute data for the page, request, session, and application. pageContext If the JSP page uses an HttpSession, it is available here under the name session. session The servlet context object. application

Implicit Variables Value Variable Name The character output stream used to generate the output HTML. out The ServletConfigobject for this servlet context. config A reference to the JSP page itself. page An uncaught exception that causes the error page to be invoked. This variable is available only to pages with isErrorPage="true". exception

Standard Actions Actions are high-level JSP elements that create, modify, or use other objects. Unlike directives and scripting elements, actions are coded using strict XML syntax <tagname [attr="value" attr="value" ...] > ... </tag-name> or, if the action has no body, an abbreviated form: <tagname [attr="value" attr="value" ...] /> XML syntax requires the following: Every tag must have matching end tag or use the short form /> previously shown Attribute values must be placed in quotes Tags must nest properly: <A><B> ... </B></A> is legal, but <A><B> ...</A></B> is not.

Standard Actions Description Tag Name Declares a Java Bean instance and associates it with a variable name. Syntax is<jsp:useBean id="name"[ type="type" ][ class="class" ][ beanName="beanName" ][scope="page|request|session|application"]> ...</jsp:useBean> <jsp:useBean> Sets the values of one or more properties of a bean previously declared with <jsp:useBean>. Syntax is <jsp:setProperty name="id"prop-expression/>where prop-expression is one of the following: property="*"property="propName"property="propName" param="parameterName" property="propName" value="value"property="propName" value=<%= expression %> <jsp:setProperty>

<jsp:getProperty> Standard Actions Description Tag Name Returns the value of the specified property of a bean. Syntax is<jsp:getProperty name="id" property="name" /> <jsp:getProperty> Invokes another resource and merges its output stream with the JSP page output stream. Syntax is <jsp:include page="URL" flush="true" /> or, if parameters need to be passed:<jsp:include page="URL" flush="true"><jsp:param … /><jsp:param … />...<jsp:param ... /></jsp:include> <jsp:include>

Standard Actions Description Tag Name Forwards this HTTP request to another JSP page or servlet for processing. Syntax is<jsp:forward page="URL" />or, if parameters need to be passed:<jsp:forward page="URL"><jsp:param ... /><jsp:param ... />...<jsp:param ... /></jsp:forward> <jsp:forward> Binds a value to a name and passes the binding to another resource invoked with <jsp:include>or <jsp:forward>. Syntax is<jsp:param name="name" value="value" /> <jsp:param>

Standard Actions Description Tag Name Used to generate the appropriate HTML linkage for downloading the Java plugin:<jsp:plugintype="bean|applet"code="objectCode"codebase="objectCodebase"{ align="alignment" }{ archive="archiveList" }{ height="height" }{ hspace="hspace" }{ jreversion="jreversion" }{ name="componentName" }{ vspace="vspace" }{ width="width"}{ nspluginurl="url" }{ iepluginurl="url" } > { <jsp:params>{ <jsp:param name="name" value="value" />}+</jsp:params> }}</jsp:plugin> <jsp:plugin>

JSP Example Login Verification (index.jsp) <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>UserName Password verification </h1> <form action="verify.jsp" method ="get"> Enter UserName:<input type="text" name="uname" value="" /><br> Enter Password:<input type="text" name="pass" value="" /><br> <input type="submit" value="submit" /> </form> </body> </html> Program using scriptlet, expression, declaration, directive , implicit object, and actions

verify.jsp <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String uname, pass;%> <% uname= request.getParameter("uname"); pass=request.getParameter("pass"); if (uname.equals("jazan")&& pass.equals("university")) {%> <jsp:forward page="welcome.jsp"/> <%} else Wrong UserName/Password, Try again!!! <jsp:include page ="index.jsp"/> <%}%> </body> </html>

welcome.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String uname, pass;%> <% uname= request.getParameter("uname"); pass=request.getParameter("pass"); %> Welcome, <%=uname%> <br> Your password is : <%=pass </body> </html>

Jsp and javabeans What Is a JavaBean? The definition of a bean is purposely broad. A bean is simply a Java class that meets two requirements: It has a zero-argument constructor. It implements Serializable or Externalizable to make it persistent. Bean Properties In addition, most beans have properties. Properties are attributes of the bean for which the bean provides read and/or write methods. All access to the bean’s properties must be done through these methods; the underlying data field (if there is one) is private. Part of the JavaBeans programming model is the naming convention used for these methods. Unless you make special provision through a BeanInfoclass, the read method for a property is a public method named get<PropertyName>(), where <PropertyName> is the name of the property with the first letter converted to uppercase. Similarly, the write method, if there is one, is named set<PropertyName>().

Example Using jsp & javabeans //index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form action="first.jsp" method ="get"> Enter Usn:<input type="text" name="usn" value="" /><br> Enter Name:<input type="text" name="name" value="" /><br> Enter Course:<input type="text" name="course" value="" /><br> <input type="submit" value="submit" /> </form> </body> </html>

StudentBean.java package bean; public class StudentBean { private String usn; public String getUsn() { return usn; } public void setUsn(String usn) { this.usn = usn; private String name; public String getName() { return name;

public void setName(String name) { this public void setName(String name) { this.name = name; } private String course; public String getCourse() { return course; public void setCourse(String course) { this.course = course;

first.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <jsp:useBean id="stud" scope="request" class="bean.StudentBean"/> <jsp:setProperty name="stud" property="*"/> <jsp:forward page="display.jsp"/> </body> </html>

welcome.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <jsp:useBean id="stud" scope="request" class="bean.StudentBean"/> Usn:<jsp:setProperty name="stud" property="usn"/> Name:<jsp:setProperty name="stud" property="name"/> Couse:<jsp:setProperty name="stud" property="course"/> </body> </html>