Apr 3, 2013 JSP Java Server Pages. 2 A “Hello World” servlet (from the Tomcat installation documentation) public class HelloServlet extends HttpServlet.

Slides:



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

CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
Java Server Pages (JSP)
 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.
Java Servlet & JSP © copyright 2005 SNU OOPSLA Lab.
Using JavaServer Pages Harry R. Erwin, PhD CIT304/CSE301.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
DT228/3 Web Development JSP: Directives and Scripting elements.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems JavaServer Pages (JSP)
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 Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
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,
JSP Java Server Pages Softsmith Infotech.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
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.
Jordan Anastasiade. All rights reserved.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
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:
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
JSP Presented by K.Venkata Ratnam HOD MCA (Dept) Newton’s Institute of Engineering.
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.
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.
JSP Java Server Pages Apr 3, 2013.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
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.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
Java Servlets and Java Server Pages Norman White Stern School of Business.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
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.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
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.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
Java Servlets and Java Server Pages
CSI 3125, Preliminaries, page 1 JSP (Java Server Pages)
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.
 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 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.
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.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
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.
Developing JavaServer Pages
Servlet Fudamentals.
JSP Java Server Pages Reference:
Java Server Pages.
Scripted Page Web App Development (Java Server Pages)
Java Server Pages.
JSP Directives 1-Jan-19.
Presentation transcript:

Apr 3, 2013 JSP Java Server Pages

2 A “Hello World” servlet (from the Tomcat installation documentation) public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + " \n" + " Hello \n" + " \n" + " Hello World \n" + " "); } This is mostly Java with a little HTML mixed in

HelloWorld import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" Hello CS764! "); out.println(" "); out.println(" Hello CS764! "); out.println(" "); out.close(); }

4 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 HTML mixed in The HTML is enclosed in out.println( ) statements JSP (Java Server Pages) is an alternate way of creating servlets JSP is written as ordinary HTML, with a little Java mixed in The Java is enclosed in special tags, such as The HTML is known as the template text JSP files must have the extension.jsp JSP is translated into a Java servlet, which is then compiled Servlets are run in the usual way The browser or other client sees only the resultant HTML, as usual Tomcat knows how to handle servlets and JSP pages

JSP Introduction JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. JavaServer Pages (JSP) is 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.

Why Use JSP? 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 Servlets API, so like Servlets, 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

JSP - Architecture

JSP Processing

JSP life cycle

JSP Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests. public void jspInit(){ // Initialization code... } JSP Execution: This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } JSP Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. public void jspDestroy() { // Your cleanup code goes here. }

The Scriptlet A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Syntax of Scriptlet: code fragment Example: Hello World Hello World!

JSP Declarations: A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Syntax of JSP Declarations: code fragment

JSP Expression: A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. expression Example: A Comment Test Today's date: Result: Today's date: 11-Sep :24:25

JSP Comments: JSP comment marks text or statements that the JSP container should ignore. Syntax: Example: A Comment Test A Test of Comments

15 JSP scripting elements The expression is evaluated and the result is inserted into the HTML page The code is inserted into the servlet's service method This construction is called a scriptlet The declarations are inserted into the servlet class, not into a method

JSP Tags Examples Comments Declaration Expression Scriptlets include file …...

17 Example JSP Hello! The time is now Notes: The tag is used, because we are computing a value and inserting it into the HTML The fully qualified name ( java.util.Date ) is used, instead of the short name ( Date ), because we haven’t yet talked about how to do import declarations

18 Variables You can declare your own variables, as usual JSP provides several predefined variables request : The HttpServletRequest parameter response : The HttpServletResponse parameter session : The HttpSession associated with the request, or null if there is none out : A JspWriter (like a PrintWriter ) used to send output to the client Example: Your hostname:

A First JSP Enter two numbers and click the ‘calculate’ button. Calculator.html

A simple calculator: results 1+1 = The sum of your two numbers is: <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %> Calculator.jsp

21 Scriptlets Scriptlets are enclosed in tags Scriptlets do not produce a value that is inserted directly into the HTML (as is done with ) Scriptlets are Java code that may write into the HTML Example: Scriptlets are inserted into the servlet exactly as written, and are not compiled until the entire servlet is compiled Example: Have a nice day! Have a lousy day!

22 Declarations Use for declarations to be added to your servlet class, not to any particular method Caution: Servlets are multithreaded, so nonlocal variables must be handled with extreme care If declared with, variables are local and OK Data can also safely be put in the request or session objects Example: Accesses to page since server reboot: You can use to declare methods as easily as to declare variables

Exception handling in JSP These are nothing but the abnormal conditions which interrupts the normal flow of execution. Mostly they occur because of the wrong data entered by user. It is must to handle exceptions in order to give meaningful message to the user So that user would be able to understand the issue and take appropriate action.

Exception handling using exception implicit object Index.jsp JSP exception handling example <% //Declared and initialized two integers int num1 = 122; int num2 = 0; //It should throw Arithmetic Exception int div = num1/num2; %>

Errorpage.jsp Display the Exception Message here errorpage.jsp An exception has occurred in the index.jsp Page. Please fix the errors. Below is the error message:

Exception handling using try catch blocks within scriptlets Error.jsp Exception handling using try catch blocks <% try { //I have defined an array of length 5 int arr[]={1,2,3,4,5}; int num=arr[6]; out.println("7th element of arr"+num); } catch (Exception exp){ out.println("There is something wrong: " + exp); } %>

JSP Directives JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form:

Directive Types DirectiveDescription Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. Includes a file during the translation phase. Declares a tag library, containing custom actions, used in the page

29 Directives Directives affect the servlet class itself A directive has the form: or The most useful directive is page, which lets you import packages Example:

The page Directive The page directive is used to provide instructions to the container that pertain to the current JSP page. Code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Syntax of page directive:

Page Directive Attribute import session isErrorPage errorPage ContentType isThreadSafe extends info language autoflush buffer

Page Directive Example <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now

The taglib Directive The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags A tag library is a set of user-defined tags that implement custom behavior. The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page. Syntax:

JSP Taglib Example The custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be Code:

35 The include directive The include directive inserts another file into the file being parsed The included file is treated as just more JSP, hence it can include static HTML, scripting elements, actions, and directives Syntax: The URL is treated as relative to the JSP page If the URL begins with a slash, it is treated as relative to the home directory of the Web server The include directive is especially useful for inserting things like navigation bars

JSP Include Directive Example Index.jsp Passing Parameters to Include directive <%! String country="India"; String state="UP"; String city="Agra"; %>

Output File1.jsp Output: India UP Agra

38 Actions Actions are XML-syntax tags used to control the servlet engine Inserts the indicated relative URL at execution time (not at compile time, like the include directive does) This is great for rapidly changing data " /> Jump to the (static) URL or the (dynamically computed) JavaExpression resulting in a URL

Directives vs Actions Directives are used during translation phase while actions are used during request processing phase. Unlike Directives Actions are re-evaluated each time the page is accessed.

JSP Forward Example 1 – without passing parameters Index.jsp Contains JSP forward action tag example My main JSP page display.jsp Display Page Hello this is a display.jsp Page

JSP Forward Example 2 – with parameters Index.jsp JSP forward example with parameters

Display.jsp Display Page Hello this is a display.jsp Page My name is: Website: Topic: Forward Request came from the page:

Action include page directive this action is also used to insert a JSP file in another file. Syntax of : Example: Demo of JSP include Action Tag JSP page: Demo Include

Action is used for redirecting the request. When this action is encountered on a JSP page the control gets transferred to the page mentioned in this action. Syntax of :

Example Demo of JSP Forward Action Tag JSP page: Demo forward

Action This action is useful for passing the parameters to Other JSP action tags such as JSP include & JSP forward tag. This way new JSP pages can have access to those parameters using request object itself. Syntax of :

First.jsp Demo of JSP Param Action Tag JSP page: Demo Param along with forward Second File: Date: Time: My Data:

Action This action is useful when you want to use Beans in a JSP page, through this tag you can easily invoke a bean. Syntax of :

EmployeeTest.jsp JSP Page to show use of useBean action Demo: Action name: empno:

StudentBean.java package javabeansample; public class StuBean { public StuBean() { } private String name; private int rollno; public void setName(String name) { this.name=name; } public String getName() { return name; } public void setRollno(int rollno) { this.rollno=rollno; } public int getRollno() { return rollno; } }

Action This tag is used when there is a need of a plugin to run a Bean class or an Applet.

JSP - Database Access Understanding on how JDBC application works. Before starting with database access through a JSP, make sure that you have proper JDBC environment setup along with a database.

Create Table mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> Create Data Records mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec)

Connecting JSP To Mysql Database

Login.html User name : password :

Reg.html First name : Last name : User name : password :

Login.jsp

Reg.jsp

Index.html Database Lookup Database Lookup Please enter the ID of the publisher you want to find:

Basic.jsp Fetching Data From a Database <% Connection connection = DriverManager.getConnection( "jdbc:odbc:data", "YourName", "password"); Statement statement = connection.createStatement(); String id = request.getParameter("id"); ResultSet resultset = statement.executeQuery("select * from Publishers where pub_id = '" + id + "'") ; if(!resultset.next()) { out.println("Sorry, could not find that publisher. "); } else { %>

Basic.jsp ID Name City State Country

62 JSP in XML JSP can be embedded in XML as well as in HTML Due to XML’s syntax rules, the tags must be different (but they do the same things) HTML: XML: expression HTML: XML: code HTML: XML: declarations HTML: XML:

63 The End