JSP Tutorial PDF
Document Details
Uploaded by CoolestOnyx679
M. Elarbi Badidi
Tags
Summary
This document provides an introduction to JSP (Java Server Pages) technology, including objectives, basic concepts, examples and benefits.
Full Transcript
CSBP 461 Internet Computing: Java Server Pages (JSP) M. Elarbi Badidi Objectives Introduce JSP Web components Compare JSP with Servlets Present the JSP life cycle ▪ Introduce JSP scripting elements Discuss JSP standard actions Discuss Custom Tags Library Introduce...
CSBP 461 Internet Computing: Java Server Pages (JSP) M. Elarbi Badidi Objectives Introduce JSP Web components Compare JSP with Servlets Present the JSP life cycle ▪ Introduce JSP scripting elements Discuss JSP standard actions Discuss Custom Tags Library Introduce the Expression Language 2 Java Server Pages (JSP) The Java Server Pages (JSP) technology allows Web developers to generate static and dynamic HTTP contents. The JSP is just like the ordinary Web pages with some additional embedded Java code. For example, a simplest JSP page can just be a simple HTML page with a.JSP extension. This is a simplest JSP page This is the simplest JSP page, without any embedded Java code. It can be treated just like an HTML page. 3 A Simple JSP Page (Blue: static, Red: Dynamic contents) Hello World! Current time is 4 Output 5 Servlet vs. JSP 6 JSP Benefits ▪ Content and display logic are separated ▪ Simplify web application development with JSP, JavaBeans and custom tags ▪ Supports software reuse through the use of components (JavaBeans, Custom tags) ▪ Automatic deployment Recompile automatically when changes are made to JSP pages ▪ Easier to author web pages ▪ Platform-independent 7 Why JSP over Servlet? ▪ Servlets can do a lot of things, but it is pain to: Use those println() statements to generate HTML page Maintain that HTML page ▪ Although JSP technically can’t do anything servlets can’t do, JSP makes it easier to: Write HTML Read and maintain the HTML ▪ JSP makes it possible to: Use standard HTML tools such as Macromedia DreamWeaver or Adobe GoLive. Have different members of your team do the HTML layout than do the Java programming ▪ JSP encourages you to Separate the (Java) code that creates the content from the (HTML) code that presents it ▪ 7 8 Java Server Pages (JSP) (cont.) Most of JSP pages have embedded Java code. This allows access to server-side data and implements business logic. Java Server Pages are an extension of Java Servlet technology. JSP can not work without Servlet container support. When a Web server gets a JSP request from a client the JSP engine converts the JSP page into a Java Servlet code and compiles it into Servlet classes. The generated Servlet code is run on the Servlet container and finally sends the results back to the Web client. JSP focuses on the data presentation while the other Web components such as Servlets, JavaBeans, custom tags, and EJB take care of business logic processing. 9 Java Server Pages (JSP) (cont.) JSP also makes the tag library extensible so that developers can develop their own reusable custom tags. The new features of JSP 2.0 such as Expression Language (EL) make Web server page authoring even easier. JSP provides a more consistent way for Web developers to access different types of data such as implicit server objects, JavaBeans, Servlets, and even other remote distributed data. 10 JSP/Servlets in the Real World: Travel Sites 11 JSP/Servlets in the Real World: Retail 12 JSP/Servlets in the Real World: Search/Portals www.ask.com www.aol.com www.duckduckgo.com www.yahoo.com www.ecosia.org 13 JSP Basics JSP Life Cycle JSP is a Web server side programming technology based on Servlet technology. The JSP specification is built on the top of the Servlet API. Any JSP page is translated into a Java Servlet by a JSP engine at runtime so that the JSP life cycle is determined by Servlet technology. The JSP engine is a JSP specification implementation which comes with web servers that implement JSP. Tomcat is one example. When a request comes to a JSP page, it may come from client browser or come from another Web component such as a Servlet or JSP. 14 JSP Life Cycle (cont.) The Web server asks the JSP engine to check whether the JSP page has never been accessed before, or it has been modified since its last access. If this is the case the JSP engine will 1. Parse the JSP document to translate into a Servlet Java file 2. Compile the Servlet Java file into a class file. Then the Servlet container loads the Servlet class for execution and sends the results back to the client. 15 JSP Life Cycle (cont.) Process of a JSP page 16 The JSP Page Life Cycle Generate HTTP Request http://localhost:8080/MySum.jsp s MySum_jsp.java Ye Web Compile Web First Brows Server Call er HTML MySum_jsp.class N o Page HTTP Response Call the method HTML _jspService (.. ,.. ) Page Generate 17 JSP Life Cycle (cont.) JSP initialization The jspInit() method is executed first after the JSP is loaded. If the JSP developer needs to perform any JSP-specific initialization such as database connections at the beginning this method can be specified. is a JSP declaration element which is used to declare variable or methods. The jspInit() is only called once during any JSP component life time. 18 JSP Life Cycle (cont.) JSP execution Public _service (HttpServletRequest req, HttpServletResponse res) “_service” is a JSP service method the same as the service() method of a Servlet class. This method never needs to be customized. All Java code defined in scripting elements are inserted in this method by JSP engine. JSP termination This method allows developers to specify resource cleanup jobs such as database disconnections. 19 First Simple Interactive JSP example (cont.) Basically, this JSP page takes a user name input from a Web client and generates a dynamic page to Demo1 welcome the user. Please enter the user name : UserName : 20 First Simple Interactive JSP example (cont.) This HTML takes a string of a user name from the HTML form and submits a request to helloJsp.jsp as specified in the action attribute of the HTML form. For example, a user types SPSU in the form and pushes the Submit button. 21 First Simple Interactive JSP example (cont.) 22 First Simple Interactive JSP example (cont.) The page helloJsp.jsp is placed in the same directory as index.html and WEB-INF. All HTML tags can be used in a JSP page since JSP is an extension of HTML. A JSP file can be placed anywhere an HTML file can be placed. Hello ! 23 JSP Syntax Elements Directives Declarations Scriplets Expressions Comments 24 First Simple Interactive JSP example (cont.) The first line is a JSP directive element tag () which directs the JSP engine to set the page structure. It will not result in any Servlet code, just like the import directive in Java. This directive element tells the JSP engine to import all classes in the java.util package to allow use of the Date class and tells JSP engine that content type of this page is text/html not text/xml. The second line is a JSP declaration element which tells the JSP engine to insert the enclosed java code into the generated Servlet java source code somewhere outside of any method. is a JSP comment scripting element which stays on the server while is a regular HTML comment which is sent back to the client. 25 First Simple Interactive JSP example (cont.) The expression scripting element will display values of the enclosed expression in string format. In this JSP example, the helloJsp.jsp gets the parameter input string by the getParameter() method of HttpServletRequest object. The input string either comes from the input text field of the request form or the URL query string of this JSP address. The “userName” of the getParameter() method matches the “userName” text input component name in the HTML form. The next JSP scripting element is scriptlet (java servelt code) which is insered into the service() method of the generated Servlet code JSP instantiates a new instance of Date class and the current date is displayed in the next expression scripting element. 26 Directives Directives provide general information about the JSP page to the JSP engine. Informs the JSP engine that we will be using java as the scripting language in our JSP page. As of JSP 1.2, java is the only one allowed. Imports classes and packages that we want to use in the JSP page. example...... 27 Directives Specifies whether the JSP page takes part in an HTTP session (more details will be given in the Implicit Variables Section). Used to delegate the exceptions to another HTML or JSP page. example...... 28 Directives Specifies the content type and Character Encoding for the output. example This is a Test 1 2 3 4 5 6 7 8 This is a tabulation 29 Directives Tells the JSP engine to include the contents of another file (HTML, JSP,..) in the current page. example1.jsp header.html... 30 Declarations Directives Declarations Scriplets Expressions Comments 31 Declarations Declarations define Variables and Methods that can be used in the JSP page. example 1... Don’t forget it example 2 32 Scriplets Directives Declarations Scriplets Expressions Comments 33 Scriplets Scriplets are Java code fragments that are embedded in the JSP page. example In this case, the jsp:setProperty is executed only if a new object is instantiated, i.e., no existing bean object exists yet. The following action sets myBook’s price property to 31.99. 61 jsp:setProperty Action (cont.) The required “name” attribute is the id of the bean specified in action tag. The required “property” attribute specifies the property you want to set. You can also assign a "*" to the property if all request parameter names match bean property names. It will set all corresponding properties of the bean with the values of request parameters either from request form or request string. The “value” attribute specifies the value for the property. The String type value will be converted to the correct type for the property. 62 jsp:setProperty Action (cont.) You can also associate the bean properties with the input parameters. The next example shows that the bookPrice input parameter in the request form or query string is associated with the price property of myBook bean. Or you can associate all properties with input request parameters with the “*” wildcard character. Assume that there are four input request parameters whose names match four property names: title, isbn, price, and quantity. Whatever data you input to the parameters will be assigned to the properties with same names. This is one of the most useful javaBean features. 63 jsp:setProperty Action (cont.) You can't use both value and param at same time, but it is allowed to use neither. If you use neither param nor value, that indicates that a parameter name matches the property name. JSP will take the input from the parameter which has the same name as the property name. jsp:setProperty action is much more powerful than the setXXX() methods in that it can automatically convert String type data to the required data type of the bean property and set multiple properties using only one single command. 64 jsp:getProperty Action Element This element retrieves the value of a bean property, converts it to a string, and inserts it into the JSP outputs. The two required attributes are name – the id of a bean defined via jsp:useBean, and property – the property whose value should be inserted.... The next action can return the number of copies of myBook, which may reference a specific book at the time. To return the price of the same book: 65 jsp:getProperty Action Element(cont.) The form.jsp takes user name input on the form request, and calls response.jsp. The response.jsp JSP page saves the input in a JavaBean, gets the username from the bean, and finally it responds to the user with a message “Hello, ”. This is the form.jsp. 66 jsp:getProperty Action Element (cont.) Here is the NameBean javaBean file. package user; public class NameBean { String userName; public NameBean() { userName=null; } Public void setUserName (String name) { userName=name; } public String getUserName() { return userName; } } Here is the response.jsp file Hello, 67 jsp:plugin Action Element The jsp:plugin action can insert an Java Applet client-side component into a server-side JSP page component. It downloads Java plug-in software (if necessary) and client-side component such as Applet and executes the client-side component. The syntax is as follows.... … 68 jsp:plugin Action Element (cont.) The element can display an Applet object or a bean object in the client Web browser, using a Java plug-in which is part of the browser or downloaded from a specified URL. When the JSP file sends an HTML response to the client, the element is replaced by an element in HTML specification. In general, the attributes to the element specify whether the object is a bean or an applet, locate the code that will be run, position the object in the browser window, specify an URL from which to download the plug-in software, and pass parameter names and values to the object. 69 JSP implicit variables (cont.) application: represents the ServletContext obtained from servlet configuration object. You can set a attribute by application.setAttribute(key,value) and get the attribute value by application.getAttribute (key). The application object has Application scope. config: represents the ServletConfig for the JSP. The JSP initialization parameters can be read via it. It has a page scope. page: synonym for the "this" operator. Not used often by page authors. session: an HttpSession object with session scope. session.setAttribute(key,data); session.getAttribute(key), and session.getId() are examples. These implicit objects are only visible within the system generated _jspService() method. 70 JSP CUSTOMIZED TAG Custom Tag Library A custom tag library feature allows JSP developers to define their own reusable custom tags. Customized tags are stored in tag libraries called taglibs. The advantages of custom tags are as follows: Separates HTML page authoring from Java programming. Encapsulates complex Java code behind the tag interface that makes it easy to reuse. Easy to maintain because any change of tag implementation will not result in any change of the tag application. In order to make custom tags work, there must be a XML descriptor file to map the tag to its implementation class file, called the tag handler class; there must also be a Java tag handler class. Of course, the custom defined tag is used in a JSP file. Figure 4.4 shows the relations among these three files. 72 Custom Tag Library 73 Custom Tag Library Tag implementation class First, let’s discuss the WelcomeTag tag handler class which just displays “Welcome!” The file is saved in webapps\tagLib\myLib\WelcomeTag.java in Tomcat where taglib is this Web application root directory. package myLib; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; public class WelcomeTag implements TagSupport { { 75 Tag implementation class (cont.) public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.print(“ Welcome! ”); } catch(Exception e) { throw new JspException("error"); } return SKIP_BODY; } } 76 Tag implementation class (cont.) The container invokes the doStartTag() when the start-tag is encountered. It is processed in the same way as the Java Simple API for XML parser (SAX) handles XML tag elements. Next, let’s look at the application of this welcome tag used in the webapps\tagLib\myFirst.jsp This JSP specifies the location of the myLib.tld file which maps the definition of Welcome custom tag to its WelcomeTag tag handler class file. The prefix attribute in the taglib directive plays a role of “namespace”. When this myFirst.jsp file is browsed the word “Welcome!” is displayed on the browser screen. 77 Tag implementation class (cont.) The webapps\tagLib\WEB-INF\myLib.tld defines the welcome tag and maps the welcome tag name to its tag handler class myLab.Welcome.class. 1.0 1.2 myLib welcome myLib.WelcomeTag empty 78 JSP 2.0 EXPRESSION LANGUAGE Expression Language (EL) A new feature of JSP technology version 2.0 is the Expression Language (EL). The EL is a simple and very powerful notation which makes it easier for the JSP page author to write code for accessing application data such as data stored in JavaBean components and attribute data of pageContext, request, session, and application. EL uses a shorthand notation of ${expr } instead of. For example, you have a Book JavaBean class in shopping package package shopping; public class Book {... float price; public Book() {... price= 0; }... public void setPrice(float p) { price=p; } public float getPrice() { return price; }... } 80 Expression Language (EL) (cont.) After you specify you can use ${myBook.price} to get the value of the price property of the bean instead of using the following scripting elements:... You can also use ${myBook.price} to replace the following JSP action elements: If the myBook.price does not exist the expression just returns Null value rather than throwing an exception. 81 Expression Language (EL) (cont.) The Expression Language also simplifies access to collection type data: request parameters, cookies, etc. It supports the conditional expression ${test? Opt1, Opt2} which is an alternative to a scriptlet element. It also supports automatic type conversion. Addition to above, another useful feature of EL is the nested notation, such as ${student.address.state} where state is a property of address class and the address is a property of the student class. EL can retrieve data but can never set any data because EL is an expression language only. 82 General syntax for bean access ${expr1.expr2} or ${expr1[“expr2”]} where expr1 is the bean reference and expr2 is the property of the bean. 83 Syntax for collection data access ${expr1[expr2]} where expr1 is a reference to an array or a list and expr2 is an integer index. For example, ${myList} returns a value at 3rd position of this list. ${expr1[expr2]} or ${expr1.expr2} where expr1 is a map and expr2 is the key of the map that the value of this key is returned. For example, ${myMap[“Smith”]} returns the phone number of Smith. There is an entry in the MyMap for Smith. Examples ${param['userName']} is equivalent EL notation to ${pageContext.session.id} returns an id number of the session the page belongs to. 84