1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to...
-
Upload
nigel-parks -
Category
Documents
-
view
214 -
download
0
Transcript of 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to...
![Page 1: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/1.jpg)
1
JSP – Java Server Pages: JSP – Java Server Pages: The Gory DetailsThe Gory Details
10 fake-points (which aren’t worth anything) to whoever:1) spots the quote in this slide and names its source
2) Figures out why the container we use is named Apache Tomcat
![Page 2: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/2.jpg)
2
Using External ParametersUsing External Parameters
![Page 3: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/3.jpg)
3
JSP Initial ParametersJSP Initial Parameters• Like Servlets, initialization parameters can be passed to
JSP files using the <servlet> element of the application configuration file web.xml
• Use the sub-element <jsp-file> instead of the sub-element <servlet-class>
• Since a <servlet> element is being used, a <servlet-mapping> element is also needed
- Use the real JSP URL as the <jsp-file>- Remember that just like in servlets mapping, you have the
flexibility of being able to map several URLs to the same jsp or servlet, each with different init parameters.
![Page 4: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/4.jpg)
4
<web-app>
<context-param>
<param-name>dbLogin</param-name>
<param-value>snoopy</param-value>
</context-param>
<context-param>
<param-name>dbPassword</param-name>
<param-value>snoopass</param-value>
</context-param>
An ExampleAn Example
web.xml
Application scoped initialization parameters (we haven’t discussed
these, but by now you can guess what they do and what they’re good for…)
![Page 5: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/5.jpg)
5
<servlet>
<servlet-name>ParamPage</servlet-name>
<jsp-file>/paramPage.jsp</jsp-file>
<init-param>
<param-name>tableName</param-name>
<param-value>users</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ParamPage</servlet-name>
<url-pattern>/paramPage.jsp</url-pattern>
</servlet-mapping>
</web-app>
web.xml
JSP scoped initialization parameters
In the case of JSP, the relative
location of the JSP (relative to the
application’s root directory) should be given instead of the Servlet classname since the Servlet is created from it by
the container.
You can also map a different URL to this JSP (highly useful if you need the URL
to end with an extension other than .jsp)
![Page 6: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/6.jpg)
6
<html>
<head><title>JSP initial parameters</title></head>
<body>
<h1>Hello</h1>
<h2>I should use the table
<i><%= config.getInitParameter("tableName") %></i>
</h2>
<h2>To access the Database, I should use the login
<i><%= application.getInitParameter("dbLogin") %></i>
and the password
<i><%= application.getInitParameter("dbPassword") %></i>.
</h2>
</body>
</html>
paramPage.jsp
JSP scoped initialization parameters
Application scoped initialization parameters
You can omit the config and call getInitParameter() directly, since the generated servlet extends
HttpJspBase which extends HttpServlet which implements the ServletConfig interface
Reminder: within a JSP this is Equivalent to getServletContext().getInitParameter()
within a Servlet
![Page 7: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/7.jpg)
7
Interacting with other Interacting with other ResourcesResources
![Page 8: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/8.jpg)
8
JSP CooperationJSP Cooperation
• We will consider several ways in which JSP and other resources cooperate- Forwarding the request handling to other resources
- Including the content of other sources
- Including the code of other JSP files
- Forwarding exception handling to other JSPs
![Page 9: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/9.jpg)
9
ActionsActions
• JSP actions use constructs in XML syntax to control the behavior of the Servlet engine
• Using actions, you can
- forward the request to another resource in the application
- dynamically include a resource content in the response
A Quick Reference to JSP Elements
![Page 10: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/10.jpg)
10
The The forwardforward Action Action• jsp:forward - Forwards the requester to a new
resource <jsp:forward page="{relativeURL|<%= expression %>}">
<jsp:param name="parameterName"
value="{parameterValue | <%= expression %>}" /> *
</jsp:forward>
• Can you write down the code this translates to?
- Hint: Recall RequestDispatcher from last week
You can use %=, % instead of <%=, %> so
that the code would be a legal XML
0 or more parameters (not attributes!)
added to the original request parameters
The forward action
![Page 11: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/11.jpg)
11
<%! int even = 0; %><% even = (1 - even); %><% if (even == 0) { %>
<jsp:forward page="/requestParams.jsp" ><jsp:param name="sessionID" value="<%= session.getId() %>" /><jsp:param name="even" value="true" />
</jsp:forward><% } else { %>
<jsp:forward page="/requestParams.jsp" ><jsp:param name="sessionID" value="<%= session.getId() %>" /><jsp:param name="even" value="false" />
</jsp:forward><% } %>
Forward Action ExampleForward Action Example
forward.jsp
![Page 12: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/12.jpg)
12
<html>
<head><title>Print Request Params</title></head>
<body>
<%@ page import="java.util.*" %>
<% Enumeration parameterNames = request.getParameterNames(); %>
<% while (parameterNames.hasMoreElements()) { %>
<% String name = (String)parameterNames.nextElement(); %>
<h2><%= name %> : <%= request.getParameter(name) %> </h2>
<% } %>
</body>
</html>
Open /forward.jsp?year=2006
requestParams.jsp
![Page 13: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/13.jpg)
13
The The includeinclude Action Action• jsp:include - Include a resource content
at run time <jsp:include page="{relativeURL|<%= expression %>}">
<jsp:param name="parameterName"
value="{parameterValue | <%= expression %>}" />*
</jsp:include>
• This action is also translated to an invocation of
the RequestDispatcher
The include action
0 or more parametersadded to the original request
parameters
![Page 14: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/14.jpg)
14
<html> <head> <title>Include (action) Example</title> </head> <body> <h2>Included part begins:<h2><hr/> <jsp:include page="/requestParams2.jsp" >
<jsp:param name="sessionID" value="<%= session.getId() %>" /> </jsp:include> <hr/><h2>Included part ends<h2> </body></html>
Include Action ExampleInclude Action Example
include.jsp
![Page 15: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/15.jpg)
15
<%@ page import="java.util.*" %>
<% Enumeration parameterNames = request.getParameterNames(); %>
<% while (parameterNames.hasMoreElements()) { %>
<% String name = (String)parameterNames.nextElement(); %>
<h2><%= name %> : <%= request.getParameter(name) %> </h2>
<% } %>
requestParams2.jsp
Open /include.jsp?year=2006
The html tags were removed. Otherwise the main JSP output HTML code would have 2 html elements for
example…
![Page 16: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/16.jpg)
16
The The includeinclude Directive Directive
• This directive lets you include files at the time the JSP page is translated into a Servlet
• The directive looks like this: <%@ include file="url" %>
• Included JSP content can affect main JSP page- e.g. included page directive can affect the result ContentType
• As of Tomcat 5.x, generated Servlets are updated when included files change (unlike older versions...)
The include directive
![Page 17: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/17.jpg)
17
Include - ActionInclude - Action
File1.jsp
Servlet1
File2.jsp Servlet2
HTMLcontent
HTMLcontent
HTMLcontent
Using RequestDispatcher
Main JSP
![Page 18: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/18.jpg)
18
Include DirectiveInclude Directive
File1.jsp
File2.jspServlet
HTMLcontent
![Page 19: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/19.jpg)
19
includeinclude Action vs. Directive Action vs. Directive
• When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime (so the resource needs not be a JSP or even a Servlet)
• When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation (so the included resource must have JSP syntax)
• In which of the above cases can the included resouce change the HTTP headers or status?
Compare the results of includeaction.jsp, includedirective.jsp
![Page 20: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/20.jpg)
20
<html>
<head><title>Including JSP</title></head><body>
<h2>Here is an interesting page.</h2>
<p>Bla, Bla, Bla, Bla.</p>
<%@ include file="/AccessCount.jsp" %>
<jsp:include page="/dbimail.jsp"/>
</body></html>
BlaBla.jsp
<%! private int accessCount = 0; %>
<hr><p>Accesses to page since Servlet init:
<%= ++accessCount %></p>
<hr><p>
Page Created for Dbi Course at <%= new java.util.Date() %>. Email us <a href="mailto:[email protected]">here</a>. </p>
AccessCount.jsp
dbimail.jsp
![Page 21: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/21.jpg)
21
out.write("<html>\r\n");
out.write(" <head><title>Including JSP</title></head>\r\n");
out.write(" <body>\r\n");
out.write(" <h2>Here is an interesting page.</h2>\r\n");
out.write(" <p>Bla, Bla, Bla, Bla.</p>\r\n");
out.write("<hr>\r\n");
out.write("<p> \r\n");
out.write(" Accesses to page since Servlet init: \r\n");
out.print( ++accessCount );
out.write("</p>\r\n");
org.apache.jasper.runtime.JspRuntimeLibrary.
include(request, response, "/dbimail.jsp", out, false);
out.write(" </body>\r\n");
out.write("</html>\r\n");
BlaBla_jsp.java
Original JSP
Included JSP
Similar to RequestDispatcher().include()
Original JSP
![Page 22: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/22.jpg)
22
Directive Included CounterDirective Included Counter
• Suppose that the file BlaBla2.jsp is similar the BlaBla.jsp
• How will the counter of BlaBla2.jsp act? Why?- Will it be identical to the 1st counter or
• What if we used a JSP action instead of a JSP directive for the counter?- Will it be to the 1st counter or not? Why?
not?
identical
![Page 23: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/23.jpg)
23
Error PagesError Pages• We can set one JSP page to be the handler of uncaught
exceptions of another JSP page, using JSP directives- The default behaviour is displaying a
500 Internal Server Error with a partialstack trace with other exception infoto the client (ugly and a security risk).
- You can log the entire stack trace alongwith other data for easier debugging
• <%@ page errorPage="url " %>- Defines a JSP page that handles uncaught exceptions- The page in url should have true in the page-directive:
• <%@ page isErrorPage="true|false" %>- The variable exception holds the exception thrown by the
calling JSPCreating an error page without isErrorPage=true, is legal but the exception
object is not created in the generated Servlet.If you refer to exception in such a JSP, you’ll have a compilation error…
Runtime exceptions or other exceptions which are declared as thrown by methods your JSP
code use.Other exceptions cannot be thrown or else your generated servlet code
wouldn’t compile
![Page 24: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/24.jpg)
24
<html>
<head><title>Reading From Database </title></head>
<body>
<%@ page import="java.sql.*" %>
<%@ page errorPage="errorPage.jsp" %>
<%
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection
("jdbc:postgresql://dbserver/public?user=" + "snoopy");
%>
<h2>Can Connect!!</h2>
</body>
</html>
connect.jsp
Reminder:• The driver is loaded dynamically• Creates an instance of itself• Register this instance with the DriverManager
![Page 25: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/25.jpg)
25
<html>
<head><title>Connection Error</title></head>
<body>
<%@ page import="java.io.*" %>
<%@ page isErrorPage="true" %>
<h1>Oops. There was an error when you accessed the
database.</h1>
<h2>Here is the stack trace:</h2>
<pre style="color:red">
<% exception.printStackTrace(new PrintWriter(out)); %>
</pre>
</body>
</html>
errorPage.jsp
A method of any exception object (and not a JSP special method) that prints the stack trace into a given PrintWriter.
In our case, the PrintWriter is the out implicit object.If you want to sleep better at night, flush the PrintWriter before continuing (why, if we aren’t using out anymore?)
![Page 26: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/26.jpg)
26
This is the result you’ll see if the server can find the driver package, and connect to the
database using the driver created with user=snoopy
![Page 27: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/27.jpg)
27
This is the result you’ll see if the server can find the driver
package, but fails to connect to the database using the driver
created with user=snoopy
Check the result of calling connect2.jsp which raises an exception after trying to load a non-existing class
This time the error page is errorPage2.jsp in which isErrorPage=true is missing…
![Page 28: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/28.jpg)
28
Custom JSP TagsCustom JSP Tags
![Page 29: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/29.jpg)
29
Custom JSP TagsCustom JSP Tags
• JSP code may use custom tags – tags that are defined and implemented by the programmer
• The programmer defines how each of the custom tags is translated into Java code
• There are two methods to define custom tags:- Tag libraries - used in old versions of JSP
- Tag files - much simpler, introduced in JSP 2.0
![Page 30: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/30.jpg)
30
Tag LibrariesTag Libraries
• A tag library consists of:- Tag handlers - Java classes that define how each of
the new tags is translated into Java code
- A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag
Tag Libraries tutorial
The taglib directive
![Page 31: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/31.jpg)
31
package dbi;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
public class DateTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
getJspContext().getOut().print(new java.util.Date());
}
}
DateTag.java
A Simple TagLib ExampleA Simple TagLib Example
Using the JSP-context, You can also acquire other implicit
objects by calling getSession(), getRequest() etc…
The class file is placed in webapps/dbi/WEB-INF/classes/dbi/
The java file is placed in webapps/dbi/WEB-INF/src/dbi/
Base class of tags which
don’t handle the body or the
attributes
Read more about SimpleTagSupport Class
We must use a package (not necessarily named like your application) since this is a helper class which is imported form the JSP’s generated Servlet that is placed
within a named package
• Goal: <dbitag:date/>
![Page 32: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/32.jpg)
32
<taglib>
<tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version>
<tag>
<name>date</name>
<tagclass>dbi.DateTag</tagclass>
<body-content>empty</body-content>
</tag>
</taglib> dbi-taglib.tld
<%@ taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib.tld" %>
<html><body>
<h1>Hello. The time is: <dbitag:date/></h1>
</body></html> taglibuse.jsp
As you can see from the path, the taglib is specifically defined to the current application
context.
The prefix for this tag must appear before the tag itself (looks like a namespace).The Prefix can’t be empty
The path could be a URL.If you choose to use a local path, it must begin with /WEB-INF/tags/
Set this value that indicates your tag library version
Name of the tag
Tag’s class file in/dbi/WEB-INF/classes/dbi/
This defined tag contains no body
You can add here more
tags…
![Page 33: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/33.jpg)
33
Taglib with AttributesTaglib with Attributespackage dbi;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
public class DateTag2 extends TagSupport {
private boolean isLongFormat = false;
public void setIsLongFormat(boolean b) {
isLongFormat = b; }
public boolean getIsLongFormat() {
return isLongFormat; { DateTag2.java
Base class of tags which do
handle attributes
In our example the attribute is defined as not
required so it must have a default value
Attribute’s setter
method
Attribute’s getter method
This member’s name should be identical to the
attribute’s.
The setter/getter methods should be named after the attribute
(i.e. “get” + capital (<attribute>))
![Page 34: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/34.jpg)
34
public int doStartTag() throws JspException { try {
if (isLongFormat) { pageContext.getOut().print(new java.util.Date().getTime()); } else { pageContext.getOut().print(new java.util.Date()); }
} catch (Exception e) { throw new JspException("DateTag: " + e.getMessage()); } return SKIP_BODY; }
public int doEndTag() { return EVAL_PAGE; }}
Invoked when the generated Servlet starts processing the “start tag”
Prints the date according to the isLongFormat attribute
Signals the generated Servlet there’s no body within the tag
to process
Invoked when the generated Servlet starts processing the
“end tag”Signals the generated Servlet
to continue executing the generated Servlet code
Read more about TagSupport Class
![Page 35: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/35.jpg)
35
<tag><name>date2</name><tagclass>dbi.DateTag2</tagclass><body-content>empty</body-content>
<attribute><name>isLongFormat</name><required>false</required>
</attribute></tag> dbi-taglib2.tld
<%@ taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib2.tld" %>
<html><body>
<h1>Hello.</h1>
<h2>The time is: <dbitag:date2/></h2>
<h2>Milliseconds since the epoch : <dbitag:date2 isLongFormat="true" /></h2>
</body></html> taglibuse2.jsp
Same as before, only with different names for the
tag,class
You can put several blocks one after another
The attribute is “not required” so you have to define a default value in
DateTag2.java
Uses default attribute value
Uses a given attribute value
![Page 36: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/36.jpg)
36
How does it work?How does it work?
taglibuse2.jsp
taglibuse2_jsp.java
JspContext
DateTag2
setIsLongFormat()
doStartTag()
doEndTag()
JSP to Java Servlet translation
Create the JspContext
When the translation engine first encounters
<dbitag:date2> it creates a new instance
of DateTag2 (so we needn’t worry about concurrency issues)
and passes it the JspContext reference
The attribute value is set using the setter method.
The translator actually translated the attribute
string value as it appears in the JSP source, to a boolean value as the
Java tag class expects it…
“Start tag” is reached
“End tag” is reached
![Page 37: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/37.jpg)
37
Tag FilesTag Files
• JSP 2.0 provides an extremely simplified way of defining tags
• The movitation: JSP programmers don’t like writing cumbersome code or class files.
• The idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code
• This way, the programmer can avoid creating tag handlers and TLD files
![Page 38: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/38.jpg)
38
<%= new java.util.Date() %>
The Simplified ExampleThe Simplified Example
<%@ taglib prefix="dbitag" tagdir="/WEB-INF/tags/" %>
<html>
<body>
<h1>Hello. The time is: <dbitag:date/></h1>
</body>
</html>
date.tag
taguse.jsp
In this new mechanism we use tagdir instead of uri we used in the old taglib
implementation
![Page 39: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/39.jpg)
39
<%@ attribute name="isLongFormat" required="false" %>
<%!private String createDate(String isLong) {
if ((isLong == null) || (isLong.equals("false"))) {
return new java.util.Date().toString();}
else { return new Long(new java.util.Date().getTime()).toString();}
} %>
<%=createDate(isLongFormat)%>
The Attributes ExampleThe Attributes Example
<%@ taglib prefix="dbitag" tagdir="/WEB-INF/tags/" %>
<html><body>
<h1>Hello.</h1>
<h2>The time is: <dbitag:date3/></h2>
<h2>Milliseconds since the epoch : <dbitag:date3 isLongFormat="true" /></h2>
</body></html>
date3.tag
taguse3.jsp
Private method declaration
Default and isLongFormat=“false”
case
Calls the private method
isLongFormat=“true” case
Default case
isLongFormat=“true”
A new directive
The isLongFormat parameter is identified as the isLongFormat attribute because we used the attribute directive
![Page 40: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/40.jpg)
40
Other Capabilities of Custom TagsOther Capabilities of Custom Tags
• Attributes- You can add validation mechanism for the attributes
values
• Tag Body- Tag translation may choose to ignore, include or
change the tag body
![Page 41: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/41.jpg)
41
Java Beans in JSPJava Beans in JSP
Read more about JavaBeans
The useBean action
The setProperty action
The getProperty action
![Page 42: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/42.jpg)
42
MotivationMotivation
• Software components (e.g. objects, data structures, primitives) are extensively used in Web applications
• For example:
- Service local variables
- Attributes forwarded in requests
- Session attributes, like users information
- Application attributes, like access counters
![Page 43: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/43.jpg)
43
MotivationMotivation
• Standard actions are used to manipulate
components: declaration, reading from the
suitable context, setting of new values (according
to input parameters), storing inside the suitable
context, etc.
• Java Beans provide a specification for automatic
handling and manipulation of software
components in JSP (and other technologies...)
![Page 44: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/44.jpg)
44
Java Beans: The IdeaJava Beans: The Idea
• Java Beans are simply objects of classes that follow some (natural) coding convention:- An empty constructor
- A readable property has a matching getter
- A writable property has a matching setter
• Use JSP actions to access and manipulate the bean, and special action attributes to specify the properties of the bean, like its scope
• JSP programmers don’t like writing cumbersome code or class files.
![Page 45: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/45.jpg)
45
Example 1: Access CounterExample 1: Access Counter
In the following example, we use a Bean to maintain an access counter for requests to the
pages
![Page 46: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/46.jpg)
46
package dbi;
public class CounterBean {
private int counter;
public CounterBean() { counter = 0; }
public int getCounter() { return counter; }
public void setCounter(int i) { counter = i; }
public void increment() { ++counter; }
}
Counter BeanCounter Bean
CounterBean.java
Bean must reside in a package
A Bean is created by an
empty constructor
Counter setter and getter
Other methods can be implemented as well
A Bean is a concept and therefore there’s no need
to extend any class or implement any interface!
(though it would’ve been very Java-ish to create an empty interface “Bean”)
![Page 47: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/47.jpg)
47
<html>
<head><title>Bean Example</title></head><body>
<jsp:useBean id="accessCounter"
class="dbi.CounterBean" scope="application"/>
<% accessCounter.increment(); %>
<h1> Welcome to Page A</h1>
<h2>Accesses to this application:
<jsp:getProperty name="accessCounter" property="counter"/>
</h2>
<a href="pageB.jsp">Page B</a></body>
</html>
pageA.jspInvokes getCounter()
An instance named according to the given id is
either found in the right scope or created.Any tags inside
<jsp:useBean> will be executed on instantiation only (but not if the instance is already an attribute of the
right scope)
The default
scope is page
You could also use the type attribute in order to instantiate a data type which is
either superclass of class or an interface that class implements
![Page 48: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/48.jpg)
48
<html>
<head><title>Bean Example</title></head><body>
<jsp:useBean id="accessCounter"
class="dbi.CounterBean" scope="application"/>
<% accessCounter.increment(); %>
<h1> Welcome to Page B</h1>
<h2>Accesses to this application:
<jsp:getProperty name="accessCounter" property="counter"/>
</h2>
<a href="pageA.jsp">Page A</a></body>
</html>
pageB.jsp
A very similar JSP
Since an instance named according to the given id
can be found in the application scope, no
instantiation takes place
![Page 49: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/49.jpg)
49
dbi.CounterBean accessCounter = null;
synchronized (application) {
accessCounter = (dbi.CounterBean) _jspx_page_context.getAttribute("accessCounter",
PageContext.APPLICATION_SCOPE);
if (accessCounter == null) {
accessCounter = new dbi.CounterBean();
_jspx_page_context.setAttribute("accessCounter",
accessCounter, PageContext.APPLICATION_SCOPE);
}
}
From the Generated ServletFrom the Generated Servlet
Similar effect to getServletContext().setAttribute()
Similar effect to getServletContext().getAttribute()
The instance is created and kept in the application’s
scope as required. Note however that
accessing this instance is out of the synchronized
scope
![Page 50: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/50.jpg)
50
Example 2: Session DataExample 2: Session Data
In the following example, we use a Bean in order to keep a user's details throughout the session
![Page 51: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/51.jpg)
51
package dbi;
public class UserInfoBean {
private String firstName;
private String lastName;
public UserInfoBean() { firstName = lastName = null;}
public String getFirstName() {return firstName;}
public String getLastName() { return lastName;}
public void setFirstName(String string) {firstName = string;}
public void setLastName(String string) {lastName = string;}
} UserInfoBean.java
![Page 52: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/52.jpg)
52
<html>
<head><title>Information Form</title></head>
<body>
<h1>Fill in your details:</h1>
<form action="infoA.jsp" method="get"><p>
Your First Name:
<input type="text" name="firstName" /> <br/>
Your Last Name:
<input type="text" name="lastName" /><br/>
<input type="submit" /></p>
</form>
</body></html> infoForm.html
![Page 53: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/53.jpg)
53
<jsp:useBean id="userInfo" class="dbi.UserInfoBean"
scope="session"/>
<jsp:setProperty name="userInfo" property="*"/>
<html>
<head><title>Page A</title></head><body>
<h1>Hello
<jsp:getProperty name="userInfo" property="firstName"/>
<jsp:getProperty name="userInfo" property="lastName"/>,
</h1>
<h1>Have a nice session!</h1>
<h2> <a href="infoB.jsp">User Info B</a></h2>
</body></html> infoA.jsp
Match all the request parameters to corresponding properties. You could
match parameters to properties explicitly using property=… param=…
You can also set properties with explicit values using property=… value=…
The String values are converted to the right
bean’s property types..
![Page 54: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/54.jpg)
54
<jsp:useBean id="userInfo" class="dbi.UserInfoBean"
scope="session"/>
<jsp:setProperty name="userInfo" property="*"/>
<html>
<head><title>Page B</title></head><body>
<h1>Hello
<jsp:getProperty name="userInfo" property="firstName"/>
<jsp:getProperty name="userInfo" property="lastName"/>,
</h1>
<h1>Have a nice session!</h1>
<h2> <a href="infoA.jsp">User Info A</a></h2>
</body></html>infoB.jsp
A very similar JSP
This time the request has no parameters so no
bean properties are set
![Page 55: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/55.jpg)
55
Advantages of Java BeansAdvantages of Java Beans
• Easy and standard management of data
- Automatic management of bean sharing and lots more
• Good programming style
- Allow standard but not direct access to members
- You can add code to the setters and getters (e.g. constraint
checks) without changing the client code
- You can change the internal representation of the data without
changing the client code
• Increase of separation between business logic (written
by programmers) and HTML (written by GUI artists)
![Page 56: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/56.jpg)
56
JSP Expression LanguageJSP Expression Language
Read more about JSP EL
![Page 57: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/57.jpg)
57
JSP Expression LanguageJSP Expression Language
• JSP expression language is a comfortable tool to access useful objects in JSP
• This language provides shortcuts in a somewhat JavaScript-like syntax
• An expression in EL is written as ${expr}
• For example:
Hi, ${user}. <em style="${style}">Welcome</em>
Note that the EL expression does not violate the XML syntax as opposed to <%= expression %>
![Page 58: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/58.jpg)
58
EL VariablesEL Variables• JSP EL does not recognize JSP's implicit objects,
but rather has its own set
• Each of these objects maps names to valuesparam, paramValues,
header ,headerValues,
cookie,
initParam,
pageScope, requestScope, sessionScope, applicationScope
• For example, use the param[“x”] or param.x to get the value of the parameter x
Map a parameter name to a single value or to multiple values
Map a header name to a single value or to multiple values
Maps a
cookie name to a
single value
Maps a context initialization parameter name to a single value
Variables belonging to the different scopes. Now is a good time to make sure you
remember they exist and what they mean…
![Page 59: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/59.jpg)
59
EL Variables (cont)EL Variables (cont)
• A variable that is not an EL implicit object is looked up at the page, request, session (if valid) and application scopes
• That is, x is evaluated as the first non null element obtained by executing pageContext.getAttribute("x"), request.getAttribute("x"), etc.
• Might be confusing. Make sure you know what you’re accessing!
![Page 60: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/60.jpg)
60
Object PropertiesObject Properties
• In JSP EL, Property prop of Object o is referred to as o[prop]
• Property prop of Object o is evaluated as follows:- If o is a Map object, then o.get(prop) is returned
- If o is a List or an array, then prop is converted into an integer and o.get(prop) or o[prop] is returned
- Otherwise, treat o “as a bean”, that is: convert p to a string, and return the corresponding getter of o, that is o.getProp()
• The term o.p is equivalent to o["p"]
![Page 61: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/61.jpg)
61
An ExampleAn Example
<% response.addCookie(new Cookie("course","dbi"));
session.setAttribute("dbiurl",new
java.net.URL("http://www.cs.huji.ac.il/~dbi/index.html"));
String[] strs = {"str1","str2"};
session.setAttribute("arr", strs); %>
<html><head><title>JSP Expressions</title></head><body>
<form method="get" action="el.jsp">
<h2>Write the parameter x: <input name="x" type="text" />
<input type="submit" value="send" /></h2>
</form>
</body></html> elcall.jsp
![Page 62: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/62.jpg)
62
<%@ page isELIgnored="false" %>
<html>
<head><title>EL Examples</title></head>
<h1>Expression-Language Examples</h1>
<h2>Parameter <code>x</code>: ${param["x"]} </h2>
<h2>Cookie <code>course</code>:
${cookie.course.value}</h2>
<h2>Header <code>Connection</code>:
${header.Connection} </h2>
<h2>Path of session attr. <code>dbiurl</code>:
${sessionScope.dbiurl.path}</h2>
<h2>Element <code>arr[${param.x}]</code>:
${arr[param.x]} </h2>
</body></html> el.jsp
The default value is TRUE
cookie[“course”].getValue()
header [“Connection”]
sessionScope[“dbiurl”].getPath().
You can omit the sessionScope
${…} means evaluate the expression inside the {}
Only the ${param.x} is evaluated
sessionScope[“arr”][param[“x”]
![Page 63: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/63.jpg)
63
JSP and XMLJSP and XML
![Page 64: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/64.jpg)
64
Simple XML ProductionSimple XML Production
<?xml version="1.0"?>
<!DOCTYPE colors SYSTEM "colors.dtd">
<?xml-stylesheet type="text/xsl" href="colors.xsl"?>
<%! static String[] colors = {"red","blue","green"}; %>
<%@ page contentType="text/xml" %>
<colors>
<% for(int i=0; i<3; ++i) { %>
<color id="<%=i%>"><%= colors[i] %></color>
<% } %>
</colors>
JSP directive which sets the MIME-type
of the result…
Ordinary XML declarations
Ordinary XML declarations
Link with XSL stylesheet
Open colors.jsp
Check the result of the same JSP without the page contentType directive
![Page 65: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/65.jpg)
65
Generated XMLGenerated XML
<?xml version="1.0"?>
<!DOCTYPE colors SYSTEM "colors.dtd">
<?xml-stylesheet type="text/xsl" href="colors.xsl"?>
<colors>
<color id="0">red</color>
<color id="1">blue</color>
<color id="2">green</color>
</colors>
![Page 66: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/66.jpg)
66
• JSPX files are JSP files that have the extension jspx and have XML syntax
• JSPX files are also referred to as JSP documents• Special JSP tags are used to replace non-XML JSP
symbols (<%, <%@, etc.) (Tags and EL can help too!)• The default content type of JSPX is text/xml (and not
text/html)• You can also keep the .jsp suffix and tell the container
that a JSP file acts as a JSPX file (and therefore its output is of XML type etc.)
JSPX Files (JSP Documents)JSPX Files (JSP Documents)
Sun JSP Documents Tutorial
![Page 67: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/67.jpg)
67
Advantages/Disadvantages of JSPXAdvantages/Disadvantages of JSPX• Since JSPX documents conform to a legal XML
structure you can:- Check if the document is well formed XML
- Validate the document against a DTD
- Nest and scope namespaces within the document
- Use all kinds of XML tools (e.g. editors)
• The main disadvantage is JSPX documents they can grow very long and very (very) cumbersome (as will soon become apparent).
• Much ado about nothing? sometimes the above “advantages” simple aren’t needed or are of little help.
![Page 68: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/68.jpg)
68
<%= Expression %><jsp:expression>
Expression </jsp:expression>
<% Code %><jsp:scriptlet>
Code
</jsp:scriptlet>
<%! Declaration %><jsp:declaration>
Declaration </jsp:declaration>
<%@ Directive %><jsp:directive.type
Attribute="value"/>
An empty element
![Page 69: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/69.jpg)
69
Problems on the way to a legal XMLProblems on the way to a legal XML
• The XML declaration (<?xml version="1.0"?>) and the DOCTYPE definition are now those of the JSPX file.- How do we include the declaration+dtd of the original XML
document in the result XML?
- Solution: use the <jsp:output> tag to explicitly require DOCTYPE and XML declarations (next slide…)
• How do we generate dynamic attribute values and still keep the document well formed?
- Solution 1: use <jsp:element> for explicit element construction
- Solution 2: use an EL expression
The following line is an illegal XML opening tag:<color id=“<jsp:expression>i</jsp:expression>“>
![Page 70: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/70.jpg)
70
<?xml version=“1.0” ?>
<colors xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:output doctype-root-element="colors"
doctype-system="colors.dtd" />
<jsp:output omit-xml-declaration="false"/>
<jsp:declaration>
static String[] colors = {"red","blue","green"};</jsp:declaration> <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet>
<jsp:element name="color"><jsp:attribute name="id"> <jsp:expression>i</jsp:expression></jsp:attribute>
<jsp:expression>colors[i]</jsp:expression></jsp:element>
<jsp:scriptlet>} </jsp:scriptlet></colors>
Namespace of basic JSP elements and Tag libraries..
Root element + DTD of the resulting XML
Do not omit the XML declaration of the result
The result is equivalent to the original line:
<color id="<%=i%>"><%= colors[i] %></color>
CDATA is used because
of <.Altenatively:
use <
Open colors.jspx, result of the same JSP with omit-xml-declaration=true (omittruecolors.jspx)
![Page 71: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/71.jpg)
71
A few more problems on the way…A few more problems on the way…
• Where can we add an XSL declaration? it should both be:- outside the root element (colors)
- after jsp:output which must be defined after jsp namespace declaration within the colors element…
• When using the include directive, the JSP might become illegal XML with more than a single root.
• A solution: Use the <jsp:root> element as the document root
• Does this solve all the problems which might arise when using the include directive?
![Page 72: 1 JSP – Java Server Pages: The Gory Details 10 fake-points (which aren’t worth anything) to whoever: 1)spots the quote in this slide and names its source.](https://reader035.fdocuments.us/reader035/viewer/2022070407/56649e165503460f94b01338/html5/thumbnails/72.jpg)
72
<?xml version=“1.0” ?><jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"> <jsp:output doctype-root-element="colors" doctype-system="colors.dtd" />
<jsp:output omit-xml-declaration="false"/>
<![CDATA[<?xml-stylesheet type="text/xsl" href="colors.xsl"?>]]>
<colors >
<jsp:declaration>static String[] colors = {"red","blue","green"};
</jsp:declaration>
<jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet>
<jsp:element name="color">
<jsp:attribute name="id">
<jsp:expression>i</jsp:expression></jsp:attribute>
<jsp:expression>colors[i]</jsp:expression>
</jsp:element>
<jsp:scriptlet>}</jsp:scriptlet>
</colors>
</jsp:root> Open colors1.2.jsp
Now we can add the XSL
We use CDATA because of the <?, ?> etc
Still problematic: Which DTD should we use? the DTD should enable every JSP element within every other element…