JSP_DAY_2

JSP_DAY_2 - JSP – Dynamic JSP – Dynamic Content Generation Agenda Agenda Reading url parameters in jsp Reading parameters from form elemets

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: JSP – Dynamic JSP – Dynamic Content Generation Agenda Agenda Reading url parameters in jsp Reading parameters from form elemets What is a template text JSP predefined objects(out,request,response…) Jsp declarations Jsp elements Directives Action scripting JSP and Tags Jsp and beans How it works? How it works? Unlike javaScript which is interpreted in the web browser, JSP pages are translated into java servlets and execute in the servlet engine.. All the work is done on the server and all the browser see is ordinary HTML. Steps.. Steps.. A JSP page is written and stored in the document tree of a Web server, usually as a file with name ending in .jsp The web server receives a request for the document. Since the name ends in .jsp, it forwards the request to the servlet engine The servlet engine passes the request on to the JSP engine, which is typically a servlet itself. The last step… The last step… The JSP engine determines whether the .jsp file is newer than the servlet class that implements if. If this is the case, it parses the .jsp file and creates java source code for the equivalent servlet. It then compiles the servlet and causes the servlet engine to load and execute it. Remember… Remember… When a .jsp file is first requested from a web browser, the JSP engine compares its timestamp with the timestamp on the generated servlet class. If the class is older(or non existent), the JSP engine creates the java source code for the servlet and compiles it. The generated class is then loaded as any other servlet would be. The JSP Syntax The JSP Syntax Inline Java code delimited by <% and %>. Also printing of expressions as text by using <%= %>. Special tags to declare class wide variables and methods. Special tags to use with JavaBeans. Special tags to expose JSP services. JSP directives to specify. Interfaces implemented by the Servlet, classes it extends, packages to import etc. JSP Directives and Scripting JSP Directives and Scripting Elements Directives Declarations Expressions Code Fragment/Scriptlet Comments <%@ directive %> <%! declaration %> <%= expression %> <% code fragment %> <%­­ comment ­­%> Servlets and JSP Servlets and JSP Servlets simple "HelloWorld" servlet, that also prints the current date. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>HelloWorld</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>Hello World</H1>"); out.println("Today is: " + (new java.util.Date().toString()) ); out.println("</BODY></HTML>"); } // doGet } // HelloWorld // JSP JSP The same page as above using JSP looks as shown below: <HTML> <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H1>Hello World</H1> Today is: <%= new java.util.Date().toString() %> </ Today BODY> BODY> </HTML> </HTML> Elements of JSP Elements of JSP Whenever a .jsp is requested for the first time, the server does the following: 1. Translates the .jsp page into a servlet 2. Compiles the servlet into a class file 3. Executes the servlet (response is sent to the client) Subsequent requests (as long as the .jsp page is unchanged) use the same loaded class file. Anatomy of a JSP Page Anatomy of a JSP Page A JSP page is a mixture of standard HTML tags, web page content, and some dynamic content that is specified using JSP constructs. Everything except the JSP constructs is called Template Text. Template text and JSP elements Template text and JSP elements Template text(html/wml/xml) Template text(html/wml/xml) Everything in the page that isn't a JSP element is called template text. Template text can be any text: HTML, WML, XML, or even plain text. but JSP has no dependency on HTML; it can be used with any markup language. Template text is always passed straight through to the browser. When a JSP page request is processed, the template text and dynamic content generated by the JSP elements are merged, and the result JSP Processing JSP Processing Refer the JSP_DAY_1 SLIDE JSP Constructs JSP Constructs 1. JSP Comments: Different from HTML comments 2. (JAVA) Expressions <%= some_java_expression %> <%= <!-- an HTML comment --> <!-<%-- a JSP comment --%> JSP comments are used for documenting JSP code and are not visible client­side (using browser's View Source option) where as HTML comments are visible. Example: <%= new java.util.Date().toString() %> Output of the expression is placed in the HTML template at the same location. JSP Elements JSP Elements scriplets Jsp scripting elements Jsp scripting elements There are three types of scripting elements in JSP: Scriptlets—Scriptlets can contain Java code. This is the most general of all the scripting elements. Declarations—Declares a variable or a method for use in your code. Expressions—Contains a Java expression that the server evaluates. The result of the expression is expression is inserted into the Web page. Scriptlets Scriptlets Scriptlets let the developer place inline Java code inside the HTML General syntax: <% Java code %> <% i++; %> Expression placement lets the developer place a Java expression (converted to a String) inline with the HTML General syntax <%= expression %> <%= new Date() %> Scriptlets and Conditional Scriptlets and Conditional HTML Scriptlets can be used to implement conditional HTML <% if(variable ) { %> <h1> variable is true </h1> <% } else { %> <h1> variable is false </h1> <% } %> Scriptlets and Looping Scriptlets and Looping Scriptlets can be used to implement loops inside the HTML. <% for(int k = 0 ; k < 10 ; k++ ) { %> <h1> variable’s value is <%= k %> </h1> <% } %> "out" variable can be used to generate HTML output from within a scriptlet Scriplets examples Scriplets examples JSPscriptlet.jsp http://localhost:8080/examples/jsp/JSPscriptlet.jsp? JSPExpressions.jsp Example of mixing scriptlets and HTML Example of mixing scriptlets and HTML <% if ( hello ) { %> <P>Hello, world <% } else { %> <P>Goodbye, world <% } %> Scriplets examples Scriplets examples 3. Scriptlets Scriptlets are arbitrary pieces of Java code inserted in the page using the format: <% some_java_code %> Examples ScripletsEg.jsp Enter the code above in a file called, bgcolor.jsp and run it Enter using the following URLs: using http://server.address/youraccount/bgcolor.jsp? COLOR=FF0000 http://server.address/youraccount/bgcolor.jsp? COLOR=00FF00 http://server.address/youraccount/bgcolor.jsp Scriplets example 2 Scriplets example 2 ScripletsEg1.jsp http://server.address/youraccount/bgcolor2.jsp? COLOR=FF0000 http://server.address/youraccount/bgcolor2.jsp? COLOR=00FF00 http://server.address/youraccount/bgcolor2.jsp 3. Scriptlets, contd. 3. Scriptlets, Using Arrays One can easily use scriptlets to loop over arrays. In this example, the user is presented with choice boxes. When s/he presses the submit button, the choices are displayed. Example: choices.jsp 4. Declarations 4. Declarations <%! some JAVA declarations %> You can define variables and/or methods. Example1­declare.jsp The following JSP page illustrates the use of a counter variable as well as a method (that sets the color of text to a random color) using the JSP declaration construct. Jsp declarations contd… Jsp declarations contd… Example 2­declare1.jsp Here we are declaring a Date variable theDate, and the method getDate. Comments in JSP Comments in JSP There are two types of comments in JSP. HTML comments that should arrive to the client's browser. These comments can contain JSP code and Scriptlets that are executed. <!­­ <% out.print("My comment"); %> ­­> Comments to the JSP page itself. These comments and their content are not interpreted and will not arrive to the client. <%­­ anything but a closing ­­%> ... ­­%> Expression Expression <%= 1+2 %> or <%= mystring %> must be complete valid java expression that results in or can be converted to a string. all JSP implicit variables are visible in an expression element Predefined Objects Predefined Objects There are some pre­defined Java variables/objects available for use in expressions (provide access to important servlet functionality): Predefined objects.. Predefined objects.. out: The output stream to collect dynamic data to be mixed into the final Web document. this: The instance of the special Servlet class. request: An HttpServletRequest object representing the request received from the Web browser. response: An HttpServletResponse object representing the response to be delivered back to the Web browser. Predefined objects.. Predefined objects.. session: An HttpSession object representing the concept of linking multiple trips of requests and response into a single process unit. application: A ServletContext object representing the concept of grouping Servlets into a single application. config: A ServletConfig object. pageContext: A PageContext object. Some examples of predefined Some examples of predefined objects PredefinedObejcts1.jsp http://localhost:8080/examples/jsp/PredefinedObjects1. PredefinedObjects.jsp The "session" Object The "session" Object session: A object provided by the JSP A object provided by the JSP server to hold information and methods common to all JSP pages running under one session. The session object must be an instance of a class that implements the javax.servlet.http.HttpSession interface Some session objects methods Some session objects methods getAttribute(): Returns the object that is associated to the specified key string. defined in the session. getAttributeNames(): Returns an Enumeration object that contains all the key strings defined in the session. getCreationTime(): Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. getId(): Returns the session ID as a string. setAttribute(): Associate an object with the specified key string and store them to this session. Summary of JSP Constructs Summary of JSP Constructs Expressions 2. Scriptlets 3. Declarations 4. Availability of pre­defined objects 1. JSP Elements JSP Elements There are three types of JSP elements you can use: Directive(page,include and taglib) action and scripting.(Adding Java to a plain HTML page) JSP Elements JSP Elements directive Jsp Directives Jsp Directives JSP Directives <%@ directive attribute="value" %> <%@ <%@ directive attr1="value" <%@ attr2="value" ... attrN="value" %> attr2="value" Directives are used to specify the structure of the resulting servlet. Directives … Directives … Directives are used during the translation phase all other elements are used during request processing phase Types of directives Types of directives There are three directives: page include <%@ include file="filename.jsp" %> taglib Page directive Page directive The page Directive There are 11 specifiable attributes for this directive: import, contentType, isThreadSafe, session, buffer, autoflush, extends, info, errorPage, and language Examples page directive Examples page directive //example import //example contentType <%@ page contentType="text/html" %> //example for non error page <%@ page import="java.util.*" %> <%@ page isErrorPage=false %> //example for a thread safe JSP <%@ page isThreadSafe=true %> Examples page directive Examples page directive <%@ page language="java" contentType="text/html" %> < %@ page contentType="application/vnd.ms­excel" %> <%@ page import="java.util.*" %> <%@ page import="java.util.*,java.io.*" %> Examples page directive Examples page directive <%@ page language="java" contentType="text/html <%@ import="java.util.*" %> <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H1>Hello World</H1> Today is: <%= new Date().toString() %> </BODY> </HTML> </BODY> Examples include directive Examples include directive The include directive is used to physically include the contents of another file. The included file can be HTML or JSP or anything else ­­ the result is as if the original JSP file actually contained the included text. To see this directive in action, create a new JSP Example Include directive Example Include directive <HTML> <HTML> <BODY> <BODY> Going to include hello.jsp...<BR> <%@ include file="hello.jsp" %> </BODY> </HTML> </HTML> Examples : page1.jsp,page2.jsp,page3.jsp Header.html,footer.html 10.8 Custom Tag Libraries 10.8 Custom Tag Libraries Custom­tag libraries Encapsulates complex functionality for use in JSPs Define custom tags Used for creating dynamic content Classes that implement interface Tag Pacakge javax.servlet.jsp.tagext 10.8 Custom Tag Libraries 10.8 Custom Tag Libraries (cont.) A ttrib ute uri De sc rip tio n Specifies the relative or absolute URI of the tag library descriptor. tagPrefix Specifies the required prefix that distinguishes custom tags from built-in tags. The prefix names jsp, jspx, java, javax, servlet, sun and sunw are reserved. Fig. 10.29 A ttrib utes o f the taglib d irec tive . JSP Elements JSP Elements Action Difference between directives Difference between directives and actions JSP also includes actions. As their name implies, actions let you perform some action. Unlike directives, actions are re­evaluated each time the page is accessed. There are two types of actions: custom and standard. Custom actions are actions you create yourself, and standard actions come built into JSP. Here are the standard actions in overview: Standard Actions Standard Actions JSP standard actions Provide access to common tasks performed in a JSP Including content from other resources Forwarding requests to other resources Interacting with JavaBeans JSP containers process actions at request time Delimited by <jsp:action> and </jsp:action> Standard Actions Standard Actions Ac tio n <jsp:include> <jsp:forward> <jsp:plugin> <jsp:param> Fig. 10.5 Desc rip tio n Dynamically includes another resource in a JSP. As the JSP executes, the referenced resource is included and processed. Forwards request processing to another JSP, servlet or static page. This action terminates the current JSP’s execution. Allows a plug-in component to be added to a page in the form of a browser-specific object or embed HTML element. In the case of a Java applet, this action enables the downloading and installation of the Java Plug-in, if it is not already installed on the client computer. Used with the include, forward and plugin actions to specify additional name/value pairs of information for use by these actions. JSP sta nd a rd a c tio ns (p a rt 1 o f 2). Standard Actions (cont.) Standard Actions (cont.) Ac tio n JavaBean Manipulation <jsp:useBean> <jsp:setProperty> <jsp:getProperty> Fig. 10.5 Desc rip tio n Specifies that the JSP uses a JavaBean instance. This action specifies the scope of the bean and assigns it an ID that scripting components can use to manipulate the bean. Sets a property in the specified JavaBean instance. A special feature of this action is automatic matching of request parameters to bean properties of the same name. Gets a property in the specified JavaBean instance and converts the result to a string for output in the response. JSP sta nd a rd a c tio ns (p a rt 2 o f 2). <jsp:forward>—Forwards the browser request for a new Web page to an HTML file, JSP page, or servlet. In this way, you can delegate how your Web applications respond to the browser. <jsp:include>— Includes a file or Web component. Note that <jsp:include> is different than the include directive because it re­evaluates the included file every time the page is accessed, whereas the include directive does not. <jsp:plugin>— Lets you execute applets or JavaBeans with a plug­in. If the browser doesn't have the required plug­in module, it will display a dialog box asking you to download it. <jsp:getProperty>, <jsp:setProperty>, and <jsp:useBean>—You use these actions with JavaBean components, as you'll see in the next slides. <jsp:forward> <jsp:forward> The <jsp.forward> tag can be used to cause a client request to be forwarded to an HTML file, another JSP file, or a servlet for processing. Whenever the <jsp.forward> tag is encountered by the JSP engine, the engine forwards the request that was sent to the JSP file to another file. The JSP engine doesn't process the remainder of the current JSP file. When a request is received by a JSP, it can be forwarded directly onto another relative URL from the same Web application to be processed. This must be a resource within the same Web application. To do this, you can use the <jsp:forward> standard action. Forward is not as redirecting.. Forward is not as redirecting.. Forwarding is not the same as redirecting. Redirecting involves the browser being sent elsewhere for a resource, effectively resulting in the browser issuing two requests. Forwarding is the browser requesting a resource, and the response coming from the resource that has been forwarded to <jsp:forward> contd… <jsp:forward> contd… This action lets you forward the request to another page. It has a single attribute, page, which should consist of a relative URL. This could be a static value, or could be computed at request time, as in the two examples below. <jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward <jsp:forward page="<%= someJavaExpression %>" /> <jsp:forward <jsp:forward page="gotForwardedRequest.jsp"/> <jsp:forward <jsp:forward page="/servlet/login" /> <jsp:forward Examples <jsp:forward> Examples <jsp:forward> <jsp:forward> : forward1.jsp forward2.jsp <jsp:include page> <jsp:include page> <jsp:include> action Enables dynamic content to be included in a JSP More flexible than include directive Requires more overhead when page contents change frequently Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. This pays a small penalty in efficiency, and precludes the included page from containing general JSP code (it cannot set HTTP headers, for example), but it gains significantly in flexibility. Attrib ute page flush Fig. 10.6 Desc rip tio n Specifies the relative URI path of the resource to include. The resource must be part of the same Web application. Specifies whether the buffer should be flushed after the include is performed. In JSP 1.1, this attribute is required to be true. Ac tio n <jsp:include> a ttrib utes. <HTML> <HTML> <HEAD> <TITLE>What's New</TITLE> <LINK REL=STYLESHEET HREF="My­Style­Sheet.css" TYPE="text/css"> </HEAD> <TABLE BORDER=5 BGCOLOR="#EF8429"> <TR><TH CLASS="TITLE"> What's New at JspNews.com</TABLE> </CENTER> <P> Here is a summary of our four most recent news stories: <OL> <LI><jsp:include page="news/Item1.html" flush="true"/> <LI><jsp:include page="news/Item2.html" flush="true"/> <LI><jsp:include page="news/Item3.html" flush="true"/> <LI><jsp:include page="news/Item4.html" flush="true"/> </OL> The jsp:plugin Action The jsp:plugin Action <jsp:plugin type=applet code="Molecule.class" <jsp:plugin codebase="/html"> <jsp:params> <jsp:params> <jsp:param name="molecule" value="molecules/benzene.mol" /> </jsp:params> <jsp:fallback> <p>Unable to load applet</p> <p>Unable </jsp:fallback> </jsp:plugin> Example PluginJsp.jsp HelloWorld.class JSP, Java Beans and JSP, Java Beans and Tags JavaBeans Components in JSP JavaBeans Components in JSP Pages JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component. JavaServer Pages technology directly supports using JavaBeans components with JSP language elements. You can easily create and initialize beans and get and set the values of their properties. JSP and JavaBeans JSP and JavaBeans JavaBeans is the component model used for the Java language: Beans are: Portable. Platform independent. Written in Java. Java classes. Reusable software components. You can combine several beans to create a bigger whole. One of the main ideas in JSP is that developers can use JavaBeans to separate the HTML view from the Java implementation code. Developers integrate the JavaBeans into the JSP page using special tags and Scriptlets. Why use a javabeans Why use a javabeans component? A JSP page can create and use any type of Java programming language object within a declaration or scriptlet. The following scriptlet creates the bookstore shopping cart and stores it as a session attribute: <% ShoppingCart cart = (ShoppingCart)session. <% getAttribute("cart"); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } %> If the shopping cart object conforms to JavaBeans conventions, JSP pages can use JSP elements to create and access the object. For example, the Bookstore pages bookdetails.jsp, catalog.jsp, and showcart.jsp replace the scriptlet with the much more concise JSP useBean element: <jsp:useBean id="cart" class="cart.ShoppingCart" <jsp:useBean scope="session"/> The "jsp:useBean" Action Elements jsp:useBean: A JSP action element that loads a JSP JavaBean object into the JSP page. <jsp:useBean id="object_name" class="class_name"/> where "object_name" is the name of the object to be where created, and "class_name" is the class name of the JavaBean class from which the object will be instantiated. Scope.. Scope.. <jsp:useBean id="localName" class="Person" <jsp:useBean scope="application" />. scope="application" The <jsp:useBean> tag requires you to identify the bean with The the id attribute id With the help of the scope attribute, you can tell the bean to With maintain its information for the single page (the default) [scope="page"]; for the request [scope="request"]; for for the session [scope="session"]; for or for the whole application [scope="application"]. or With session scope, you can maintain items such as shopping With carts very easily within JSP pages. carts Accessing/changing java bean Accessing/changing java bean properties Once a bean object is loaded into the page, you Once can use two other action elements to manipulate it. <jsp:setProperty name="obj" property="prop_name" <jsp:setProperty value="prop_value"/> value="prop_value"/> <jsp:getProperty name="obj" property="prop_name"/> <jsp:getProperty The "setProperty" action will set a new value The to the specified property of the specified bean object. The "getProperty" action will get the current The value of the specified property of the specified bean object. This value will be converted into a string or just directly set with a name and value: <jsp:setProperty id="localName" <jsp:setProperty property="serialNumber" value="string" /> or <jsp:setProperty id="localName" <jsp:setProperty property="serialNumber" value= <%= expression %> />. property="serialNumber" Once a bean object is loaded into the page, it can be used Once in other scripting elements in the same JSP page. Bean Tags in JSP Bean Tags in JSP JSP introduces new tags to handle beans: Attaching to a certain bean. jsp:useBean Initializing a bean. Setting a bean attribute jsp:setProperty Getting a bean attribue. jsp:getProperty Example 1: beans­date.jsp Example 1: beans­date.jsp Using beans in JSP Pages <jsp:useBean id="name“ class="package.class" /> Step 1: date.jsp Step 2: Accessing Bean properties <jsp:getProperty name="objectName" <jsp:getProperty property="propertyName" %> Setting Bean Properties <jsp:setProperty name="objectName" <jsp:setProperty property="propertyName" value="value" /> property="propertyName" Beans example Beans example Example Bean package ecom; public class SecretMessage { private String message = "No message."; public String getMessage() { public return message; } public void setMessage(String s) { public message = s; } } Using the SecretMessage Bean Using the SecretMessage Bean <HTML> <HTML> <HEAD> <TITLE> <HEAD> Using the SecretMessage Bean</TITLE> </HEAD> <BODY BGCOLOR="WHITE"> <BODY <H1>Using the Secret Message Bean</H1> <H1>Using <jsp:useBean id="MyMessage" class="ecom.SecretMessage" /> <OL> <jsp:useBean <LI> Initial Message (using getProperty): <I> <jsp:getProperty name="MyMessage" property="message" /> </I> <LI> <jsp:setProperty name="MyMessage" property="message" value="Meet me at the Foggy Bottom Metro" /> Secret message (after setting): <I> <jsp:getProperty name="MyMessage" property="message" /> </I> </OL> </BODY> </HTML> </BODY> Example 2 of bean Example 2 of bean Using the SecretMessage Bean SecretMessage.jsp Bean example 3: Bean example 3: http://localhost:8080/examples/jsp/GetName.html http://localhost:8080/examples/jsp/SaveName.jsp http://localhost:8080/examples/jsp/NextPage.jsp Beanmyname.jsp Beanmyname.jsp Print a name as submitted by the user Uses JavaBeans and JSP JavaBeans tags: To parse the parameters sent Print the parameters Beanmyname.jsp – The code Beanmyname.jsp – The code <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 <!DOCTYPE Transitional//EN"> Transitional//EN"> <HTML> <HEAD> <%@ page language="java" contentType="text/html; charset=WINDOWS-1255" contentType="text/html; pageEncoding="WINDOWS-1255" pageEncoding="WINDOWS-1255" import="NameBean" import="NameBean" %> <META http-equiv="Content-Type" content="text/html; charset=WINDOWS-1255"> <TITLE>beanmyname.jsp</TITLE> </HEAD> <jsp:useBean id="myusername" scope="page" class="NameBean"> <jsp:setProperty name="myusername" property="*" /> </jsp:useBean> Beanmyname.jsp – The code Beanmyname.jsp – The code <BODY> <BODY> <H1>Print my name using JavaBeans</H1> Your full name Is: <jsp:getProperty name="myusername" property="name" /> <jsp:getProperty name="myusername" property="family" /> <H1>Send Your Name</H1> <FORM method="GET" action="beanmyname.jsp"> <P>Your Name: <INPUT type="text" name="name" <P>Your size="20"></P> size="20"></P> <P>Your Family: <INPUT type="text" name="family" <P>Your size="20"></P> size="20"></P> <P><INPUT type="submit" value="Submit"> <INPUT <P><INPUT type="reset"value="Reset"></P> type="reset"value="Reset"></P> </FORM> NameBean – The code NameBean – The code import java.io.Serializable; public class NameBean implements Serializable { class implements String nameProperty = null; null String fnameProperty = null; null public void setName(String name) { public void nameProperty = name; nameProperty } public String getName() { public return nameProperty; return } public void setFamily(String name) { public void fnameProperty = name; } public String getFamily() { public return fnameProperty; return } Beanmyname.jsp – Output Beanmyname.jsp – Output Reminders… Reminders… Data access and business logic is done in Java. JSP get to see the results of this business logic via JavaBeans/special tags. Servlets and JSP can interact in two access models known as Model­1 and Model­2 ...
View Full Document

This note was uploaded on 07/15/2011 for the course ECO 2023 taught by Professor Mr.raza during the Summer '10 term at FAU.

Ask a homework question - tutors are online