1 JSP – Java Server Pages Representation and Management of Data on the Internet.

Slides:



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

Java Server Pages (JSP)
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.
JSP – Java Server Pages Part 1 Representation and Management of Data on the Internet.
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:
Introduction to JavaServer Pages Vijayan Sugumaran Dept. of DIS Oakland University Parts of this presentation was provided by
Java Server Pages Russell Beale. What are Java Server Pages? Separates content from presentation Good to use when lots of HTML to be presented to user,
JSP – Java Server Pages Representation and Management of Data on the Internet.
1 CS6320 – JSP L. Grewe 2 Java Server Pages Servlets require you to write out entire page delivered with print statements Servlets require you to write.
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 Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
© Yaron Kanza Server-Side Programming using Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Introduction to JSP Based on: Marty Hall, Larry Brown, Core Servlets and JavaServer Pages.
JSP Java Server Pages Softsmith Infotech.
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.
 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.
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.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
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.
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.
1 (Server-Side Programming using Java Server Pages) cs
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.
1 JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
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.
Java Server Pages (JSP)
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.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
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.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
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.
JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
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.
SKT-SSU IT Training Center Servlet and JSP. Chapter Eleven: Invoking Java Code with JSP Scripting Elements.
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
JAVA SERVER PAGES -by Rubeena Memon Deepti Jain Jaya Thakar Jisha Vettuventra.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
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
Scripted Page Web App Development (Java Server Pages)
Invoking Java Code from JSP
JSP Syntax.
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.
Web Technologies Java Beans & JSP
Presentation transcript:

1 JSP – Java Server Pages Representation and Management of Data on the Internet

2 What is JSP Good For? Servlets allow us to easily: –read data from user –read HTTP request –create cookies –etc. It is not convenient to write long static HTML using Servlets –out.println(" Bla Bla " + "bla bla bla bla bla " + " lots more here...")

3 JSP Idea Use HTML for most of the page Write Java code directly in the HTML page (similar to Javascript) Automatically translate JSP to Servlet that actually runs

4 Relationships In servlets: HTML code is printed from java code In JSP pages: Java code is embedded in HTML code Java HTML Java HTML

5 Example Hello World Example Hello World Example Hello !

6 Page is in the proj web application: tomcat_home/webapps/proj/HelloWorld.jsp Invoked with URL: : /proj/HelloWorld.jsp?name=snoopy

7 Invoked with URL (no parameter): : /proj/HelloWorld.jsp

8 JSP Limitations and Advantages JSP can only do what a Servlet can do Easier to write and maintain HTML Easier to separate HTML from code Can use a "reverse engineering technique": create static HTML and then replace static data with Java code

9 What does a JSP-Enabled Server do? receives a request for a.jsp page parses it converts it to a Servlet (JspPage) with your code inside the _jspService() method runs it

10 Translation of JSP to Servlet Two phases: –Page translation: JSP is translated to a Servlet. Happens the first time the JSP is accessed –Request time: When page is requested, Servlet runs No interpretation of JSP at request time!

11 Design Stategy Do not put lengthy code in JSP page Do put lengthy code in a Java class and call it from the JSP page Why? Easier for –Development (written separately) –Debugging (find errors when compiling) –Testing –Code Reuse

12 The Source Code In Tomcat 3.2.1, you can find the generated Java and the class files in a subdirectory under tomcat_home/work.

13 JSP Scripting Elements Scripting elements let you insert code into the servlet that will be generated from the JSP Three forms: –Expressions of the form that are evaluated and inserted into the output, –Scriptlets of the form that are inserted into the servlet's _jspService method, and –Declarations of the form that are inserted into the servlet class, outside of any methods

14 JSP Expressions A JSP expression is used to insert Java values directly into the output It has the following form: Example: –

15 JSP Expressions A JSP Expression is evaluated The result is converted to a string The string is inserted into the page This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request

16 Expression Translation A Random Number public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(" A Random Number "); out.println(Math.random());... }

17 Predefined Variables The following predefined variables can be used: –request, the HttpServletRequest –response, the HttpServletResponse –session, the HttpSession associated with the request –out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client

18 JSP Expressions JSP Expressions Current time: Your hostname: Your session ID: The testParam form parameter:

19 Encoded Unencoded

20 JSP Scriplets JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page ( _jspService ) Scriptlets have the following form: Scriptlets have access to the same automatically defined variables as expressions. Why?

21 public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(foo()); bar();... } Scriptlet Translation

22 Producing Code Scriptlets can produce output by printing into the out variable Example: <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> Would we want to use a scriptlet in this case?

23 HTML Code in Scriptlets Scriptlets don't have to be entire Java Staments: You won the game! You lost the game! if (Math.random() < 0.5) { out.println("You won the game!"); } else { out.println("You lost the game!"); }

24 JSP Declaration A JSP declaration lets you define methods or fields that get inserted into the servlet class (outside of all methods) It has the following form: Declarations do not produce output They are used to define variables and methods Should you define a method in a JSP declaration?

25 Declaration Example Print the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded): <%! private synchronized int incAccess() { return ++access; } %> Accesses to page since server reboot: Should accessCount be static?

26 public class xxxx implements HttpJspPage { private int accessCount = 0; private synchronized int incAccess() { return ++access;} public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(" Accesses to page since server reboot: "); out.println(incAccess());... }... }

27 Predefined Variables As we have seen before, there are variables that can be used in the code There are eight automatically defined variables, sometimes called implicit objects We saw 4 variables: request, response, out, session Other 4 variables: application, config, pageContext, page

28 More Details: request, response request: the HttpServletRequest response: the HttpServletResponse The output stream is buffered It is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client Use request to save page specific values

29 More Details: out This is the PrintWriter used to send output to the client Actually a buffered version of PrintWriter called JspWriter You can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive

30 More Details: session This is the HttpSession object associated with the request Sessions are created automatically, so this variable is bound even if there was no incoming session reference (unless session was turned off using the session attribute of the page directive) Use session to store client specific values

31 Another Variable: application This is the ServletContext as obtained via getServletConfig().getContext() Remember: –Servlets and JSP pages can hold constant data in the ServletContext object –Getting and setting attributes is with getAttribute and setAttribute –The ServletContext is shared by all the servlets in the server Use application to store web application specific values

32 Another Variable: config This is the ServletConfig of the page, as received in init method Remember: Contains Servlet specific initialization parameters

33 Another Variable: pageContext pageContext encapsulates use of server- specific features like higher performance JspWriters Access server-specific features through this class rather than directly, your code will still run on "regular" servlet/JSP engines

34 Another Variable: page Simply a synonym for this page is not very useful in JSP pages It was created as a placeholder for the time when the scripting language could be something other than Java

35 Note about Predefined Variables Predefined variables are local to the _jspService method. How can we use them in methods that we define? When using out in a method, note that it might throw a IOException

36 JSP Directives A JSP directive affects the structure of the servlet class that is created from the JSP page It usually has the following form: Multiple attribute settings for a single directive can be combined: directive attribute1="value1"... attributeN="valueN" %>

37 Three Types of Directives page, which lets you do things like –import classes –customize the servlet superclass include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet taglib, which indicates a library of custom tags that the page can include

38 page Directive Attributes import attribute: A comma seperated list of classes/packages to import contentType attribute: Sets the MIME-Type of the resulting document (default is text/html) Note that instead of using the contentType attribute, you can write

39 More page Directive Attributes isThreadSafe=“true|false” –false indicates that the Servlet should implement the SingleThreadModel session=“true|false” –false indicates that a session should not be created –Saves memory –All related pages must do this!!! buffer=“sizekb|none” – specifies the buffer size for the JspWriter out Default is Server Dependant

40 More page Directive Attributes autoflush=“true|false” –Flush buffer when full or throws an exception when buffer isfull extends=“package.class” –Makes Servlet created a subclass of class supplied –Don't use this! Why? info=“message” –A message for the getServletInfo method

41 More page Directive Attributes errorPage=“url” –Define a JSP page that handles uncaught exceptions –available to next page by exception variable –example isErrorPage=“true|false” –allows the page to be an error page

42 Reading From Database <% Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:" + Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from a"); ResultSetMetaData md = rs.getMetaData(); int col = md.getColumnCount(); %>

43 Note: Is this a convenient way to print out a table? What would be a better way?

44 Reading From Database Oops. There was an error when you accessed the database. Here is the stack trace:

45 Accessing ReadingDatabase when there is a table "a" Accessing ReadingDatabase when there is no table "a"

46 The include Directive This directive lets you include files at the time the JSP page is translated into a servlet The directive looks like this: JSP content can affect main page servers don't notice changes in included files

47 Reading From Database Here is an interesting page. Bla, Bla, Bla, Bla. BlaBla.jsp Page Created for Dbi Course. us here. Accesses to page since server reboot: AccessCount.jsp

48

49 Writing JSP in XML We can replace the JSP tags with XML tags that represent – Expressions –Scriptlets –Declarations –Directives

50 Java Expression Code Java Java Declaration <jsp:directive.type Attribute = value/>

51 Actions JSP actions use 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

52 Available Actions jsp:include - Include a file at the time the page is requested jsp:useBean, jsp:setProperty, jsp:getProperty – manipulate a JavaBean (not discussed today) jsp:forward - Forward the requester to a new page jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin (not discussed today)

53 The jsp:include Action This action lets you insert files into the page being generated The file inserted when page is requested The syntax looks like this:

54 The jsp:forward Action Forwards request to another page Page could be a static value, or could be computed at request time Examples: " />

55 Comments –A JSP comment, ignored by JSP-to-scriptlet translator –An HTML comment, Passed through to resultant HTML –Any embedded JSP scripting elements, directives, or actions are executed normally /* comment */ or // comment –Java comment, Part of the Java code

56 Quoting Conventions <\% - used in template text (static HTML) and in attributes where you really want <% %\> - used in scripting elements and in attributes where you really want %> \‘ \” - for using quotes in attributes \\ for having \ in an attribute

57 Init and Destroy In JSP pages, like regular servlets, sometimes want to use init and destroy It is illegal to use JSP declarations to override init or destroy, since they are already implemented (usually) by Servlet created Instead use jspInit and jspDestroy –The auto-generated servlet is guaranteed to call these methods from init and destroy –The standard versions of jspInit and jspDestroy are empty (placeholders for you to override)

58 Material Not Covered Java beans: Using Java beans you can simplify the process of sharing information between JSP pages and Servlets. (How can you share information now?) Custom Tags: You may define new tags and Java classes that define what should be done when the tag appears in a JSP page

59 JSP versus JavaScript Q: Can/Should you have JSP and Javascript in the same page? Q: Can you validate a form using JavaScript? Where should the code go? Q: Can you validate a form using JSP? Where should the code go?