Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 Apr 3, 2013 JSP Java Server Pages

2 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

3 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 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

5 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.

6 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

7 JSP - Architecture

8 JSP Processing

9 JSP life cycle

10 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. }

11 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!

12 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

13 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-2010 21:24:25

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

15 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

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

17 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 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:

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

20 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 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 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

23 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.

24 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; %>

25 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:

26 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); } %>

27 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:

28 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 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:

30 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:

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

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

33 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:

34 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 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

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

37 Output File1.jsp Output: India UP Agra

38 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

39 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.

40 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

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

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

43 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

44 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 :

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

46 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 :

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

48 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 :

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

50 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; } }

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

52 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.

53 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)

54 Connecting JSP To Mysql Database

55 Login.html User name : password :

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

57 Login.jsp

58 Reg.jsp

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

60 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 { %>

61 Basic.jsp ID Name City State Country

62 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 63 The End


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

Similar presentations


Ads by Google