{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

JSP_DAY_2 - JSP – Dynamic JSP – Dynamic Content...

Info icon This 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...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern