Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
13/05/2014
Servlets
• Sun expected Servlets to replace CGI
• Basically …
Java Server Pages
• They didn't.
– They were popular with banks, insurance companies, and other high end applications
– But were unappealing to amateur developers
– Small ISPs and web hosting companies unwilling to deploy Java server side
A prettier form of servlet!
1
ASP & PHP
2
ASP & PHP advantage
• Microsoft's Active Server Page technology proved more popular – though limited to Microsoft IIS server
• PHP came from nowhere and easily outgrew servlets – in number of sites, if not importance of sites
• Amateur developers mostly developing webapps with lots of markup and little processing code
– Compose a page as HTML
– Embed little scraps of code that supply dynamic content
3
Sun's response …
4
JSP & Servlets
• Java Server Pages
• JSP is a servlet technology
• JSP page "compiled into a servlet" before use.
• Often combined with other servlets
– Basically a HTML document
– Embedded
• Directives
• Actions
• Scriptlets
– Servlets do the "heavy lifting", results left in shared data structures
– Servlet forwards control to JSP page
– JSP page adds the "pretties“
– These embedded elements invoke processing
• Return data strings that get embedded into the HTML
• Data extracted from shared data structures and embedded in amongst the “pretties”
5
As commented previously, servlet/JSP combination is similar to the more recently devised PHP‐script/Smarty combination
6
1
13/05/2014
Beans
“Beans”
Little lumps of pure concentrated Java coffee
• Typically:
– Servlet, along with application specific classes implementing business logic, perform the operations required by the web request
• Add data to persistent store
• Retrieve other data
– Servlet packages the retrieved data and reports into “struct” like classes, and forwards these to a JSP for display
• Those “struct” like classes must comply with certain naming conventions if they are to be used in the JSPs
• These conventions invented earlier with Java “Beans”
7
• “Bean” terminology had been introduced into Java earlier.
• Sun envied Microsoft’s success with GUI builder wizards and wanted to provide Java with features that would allow construction of similar sophisticated GUI builders.
– Sun added • “Java reflection” – the ability for code at run‐time to examine the interface of a class and invoke the methods of an instance of that class
• Bean naming conventions – primarily for accessor and mutator functions (getters and setters)
Again Sun built enabling technology and expected others to build the wizards that used it.
8
Bean classes
• Important to follow naming conventions for any little “struct” like classes used to pass data around amongst servlets and JSPs.
– Not too hard – NetBeans knows the conventions will help you when you create the classes
The adventures first,
explanations take too much time
• You specify the data members
• You let NetBeans generate the getters and setters with appropriate Bean convention names
9
10
The Guru
A better class of
“Hello World”
Program
The Guru is a “fortune cookie” program.
It makes a random choice from a collection of
aphorisms and prints this as its advice.
11
Aphorism: a wise or witty saying
12
2
13/05/2014
Advice.jsp & Guru.java
Advice.jsp
• JSP – Using “scriptlets” – small fragments of Java used to invoke operations of an object
• A simple semi‐bean class “Guru”
– Only one method defined – String enlightenMe()
• No XML deployment file needed (well, not in simple cases)
13
Advice.jsp
14
Mostly standard HTML markup
• Page directives
– These provide information to the code‐generator that will create a working servlet from the JSP page
• Code‐generator runs when the web‐app is deployed, creates a new servlet – it is this servlet that actually runs
• Most of a JSP will be standard HTML
– HTML tags
– Fixed content text
• (JSP documentation uses the term “template text”)
• Two page directives here
– contentType – specify return page type and character encoding
– import – specify any import directives that will have to be put into the generated servlet; here need to explicitly say that will be using a class from the mystuff package deployed with this JSP
• JSP should be editable in your favourite HTML editor
15
16
“Scriptlet” code
Scripting elements
• Scriptlet
• Scriptlet code
– Embedded code in the fashion of ASP and PHP
• Java code – though the specification did allow for other languages to be used!
• Scriptlet code‐ uhm!
– A temporary expedient when JSPs first introduced
– Rarely used later (after the introduction of useful sets of “action tags”)
– Use now?
• Only for quick prototyping!
• Why disfavoured?
<% some Java code
%>
The code is dropped into the generated servlet.
Can include variable declarations – they are defined as local variables of the “service” function.
• Expression
– Code in amongst HTML
<%= Java expression %>
• always at risk from enthusiastic “web designers” wanting to improve appearance of page
gets translated into something like “out.print(Java expression )”
– Mixing of very different genres
• Declarations
• Declarative style HTML markup
• Procedural style code
–…
17
18
3
13/05/2014
Guru class
It works!
An instance of the random number generator
A collection of aphorisms
A function that returns a randomly selected aphorism
19
20
But how?
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import mystuff.Guru;
Service method
A generated servlet
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
public final class Advice_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
Initialize host of variables
try {
Do the work
…
} catch (Throwable t) { … }
finally { … }
}
public java.util.List<String> getDependants() { return _jspx_dependants; }
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
…
}
21
}
22
Doing the work
Doing the work
try {
response.setContentType("text/html;charset=UTF‐8");
response.setHeader("X‐Powered‐By", "JSP/2.2");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
Just a little more initialization
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
…
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http‐equiv=\"Content‐Type\" content=\"text/html; charset=UTF‐8\">\n");
out.write(" <title>The Guru confers advice</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h1 align=center>\n");
out.write(" <font color=red>\n");
out.write(" Today’s advice from the Guru\n");
out.write(" </font>\n");
out.write(" </h1>\n");
out.write(" ");
Oooh look what it has done!
It’s written all those tiresome out.print(…) statements
And it has embedded the scriptlet code into the body of
Guru theGuru = new Guru(); the service method
out.write("\n");
out.write(" <p>\n");
out.write(" ");
Now start outputting the response page
out.print( theGuru.enlightenMe());
out.write("\n");
out.write(" </body>\n");
out.write("</html>\n");
out.write("\n");
out.write("\n");
}
23
write/print?? If argument string is null, print prints “null”,
24
but write has an exception
4
13/05/2014
Sun’s view of scriptlet code
Just a bunch of out.write statements
• Procedural code in amongst the declarative HTML – not the brightest idea (even though it’s working for PHP and ASP)
• Couldn’t some more declarative style be adopted.
• And really, that is all there is to JSPs.
• The code‐generator writes all those output statements that were so tiresome when you worked with servlets directly.
• Sun decided to add “action tags”
–
–
–
–
Like XML markup
Action ~verb e.g. create object, print value, …
Parameters ~ adverbs and adjectives
Reference to a class instance, ~noun, the thing being manipulated
25
Sun’s approach
26
Action tag style
• Slight modification of the Guru class is needed
• Can then build a version of the Advice application using Sun’s jsp: tag library
1. Build an enabling technology
2. Provide a limited proof of concept implementation
3. Leave it to others to create working instances
• Enabling technology
• The results may not seem that impressive
– “Tag libraries”
– The difference in clarity of the declarative action tag approach only really shows in larger examples
• Limited proof of concept
– “jsp:” tag library
27
Action tag JSP page
28
JSP page with jsp: tag
• jsp: tag library
• jsp:useBean
– Provided by default, don’t need to configure or install anything
– Create instance of specified class
– Give instance an identifier
• jsp:getProperty
– Get, as a String, the value of a specified property of a chosen object
• Property – which property
• Name – which object
29
I never did find why it’s “id” in useBean but “name” in getProperty
30
5
13/05/2014
Modified Guru class
Bean naming conventions
• jsp:getProperty
– enlightenment
• Object must have a
– getEnlightenment() method
31
Again – how did it work?
A generated servlet
32
Service()
• The translator that creates servlets from JSPs
with scriptlet code simply embeds that code in the service method of the generated servlet.
• Tags?
useBean – i.e. create it, add it to page
– They are a bit like macros
– The translator can expand them out to appropriate Java:
getProperty
33
These generated files are found in places like:
C:\Program Files\glassfish‐3.1.1\glassfish\domains\domain1\generated\jsp\Guru2\org\apache\jsp
34
Defining own tags
• Sun’s jsp: tag library was quite limited
– Create instance of class
– Use getters/setter to change data members
Define your own tag class
• You needed scriptlet code to do anything more elaborate with class instances – such as call member functions other than getters and setters
– Deal with “forward” and “include” – same facilities as already existed in servlets
Sun didn’t expect you to use just the limited jsp: tag library
• Hoping that others would develop more sophisticated uses, Sun provided some base classes that could be used to define own tag classes 35
36
6
13/05/2014
Your own custom action elements
Your own actions (tags)
• An action element (tag) appears in a JSP as something like
• You have to define your “alib” tag library (~ Java package of tag classes)
• You have to define classes that do whatever special processing your require.
<alib:thing1 parameters, more parameters>
Block of text
</alib:thing1>
• This block is mapped into code in the generated servlet that is (conceptually) along the lines –
import alib.*;
…
alib.Thing1 t001 = new alib.Thing1(params);
t001.getStarted();
t001.handleBodyText(“Block of text”);
t001.finishUp();
In practice, the generated code is a lot more sophisticated and complex.
37
– These classes must extend various base tag classes that are provided as part of the JSP system.
• Typically, processing occurs mostly at end tag, there generate block of HTML text derived from information in parameters and body data. Later release of servlet technology included a way of creating custom tags using a
declarative style rather than by coding Java classes. (Translator creates the class
from the supplied declarations.) Supposedly, this style amenable to “web designers”
with no programming experience.
Deployment of own tags
38
Classes
• Two base classes in initial release (others added later)
• Moderately complex
– Tag
– Build your tag library with your tag classes
– Create a descriptive deployment document
• You simply want to have a block of code executed with parameter data passed in from the JSP page
• Associates tags with classes
• Specifies the parameters they take (and whether these are mandatory)
– Place descriptive document in appropriate sub‐
directory of WEB‐INF
– Add taglib page directives to JSPs
– BodyTag
• This was for constructing things like loops using makup tags
– Tag start – “I have this collection of records retrieved from a database, process them one by one”
– Body – “Here is what I want you to do with each one: compose a row in a HTML table inserting data members from record like this”
– End tag – “All done, go ahead and output the table”
• Coding of a BodyTag was a little elaborate
– You had to manipulate a temporary output buffer that your code filled in (e.g. a buffer to hold text of that HTML table)
– At end tag, you had to arrange for text to be copied from your buffer into JSP page
39
My simple example : DateStamper
40
My simple example : DateStamper
• I’ve decided that it would be useful to have a tag that could add a date stamp to a generated page.
• It should appear in JSP as a tag that contains a comment
• It should generate text for the final HTML page
41
This version is using “SimpleTagSupport” as a base class; this was introduced later
and slightly simplifies the coding compared with original “Tag” base class.
42
7
13/05/2014
Taglib descriptor
mytag.tld
• The deployment component that translates JSPs
into servlets must somehow discover the relation between
<mytag:DateStamper
and the class that I defined in some package.
• It must also discover the names of the parameters (like my “comment” parameter) and whether these are mandatory or optional (“comment” is mandatory)
• This information supplied in a XML deployment file – the “tag library descriptor” file
This is the mytag library and
here are its tags (only one –
DateStamper).
The DateStamper class is
defined in package mytags;
it doesn’t process any body
text; it does have one required
parameter of type String named comment.
43
NetBeans assists
44
Referencing your taglibrary
• Your JSP requires a taglib directive to load a tag library (equivalent to a include directive for a bean class)
• You used to have to compose the tag library descriptor.
• Now NetBeans offers “TagHandler” as one of the file types that you can add to a web app
– It is just a Java class, but NetBeans will set the base class and add the appropriate markup to the tld file.
the project has to have the correct arrangement of files and directories
45
46
Sun’s approach maybe not the best
But tags do evolve to something useful
• jsp: tag library
• Best of breed competition amongst tag libraries • “struts” from the Apache group –
– Too limited
• Others developers create useful libraries
– But lots of rival incompatible tag libraries each attempting to do similar work
• Manipulate “beans”
• Handle selection and iteration
– E.g. when printing a HTML table presentation of a collection of data items
• SQL
– Do your data persistence using markup tags! ? !
– Bizarre and highly specialized coding skills for writing tag library classes
47
– First really good, widely accepted tag library ~2000
• “Java Standard Tag Library” (JSTL) ~2003
– Through Java community process
– Combine experience from struts and other good tag libraries
– Define a new standard (much superior to jsp: library) – the tag library that should have been in first release!
48
8
13/05/2014
Microsoft did it better
• Microsoft reviewed JSP and its early tag libraries when developing ideas for dot‐Net
• Followed the same basic idea
– Use XML like tags to define components with associated code within conventional HTML
OK, time to get more technical
• Did it better
– GUI editor style development of pages
Things your find in JSP pages
Beans
Scopes for Beans
Sessions
etc etc
• “Component framework”
– Add a HTML <select> in a page; code generator creates instance of a .NET Selection class that has a collection of Option objects and a (set of) integer(s) identifying selected options
– Wizards creating much of the code
• C#/Visual Basic classes auto‐generated with stub functions where you insert any application specific code
49
50
Page contents
•
•
•
•
A JSP page
Directives
Action elements
Scripting elements
Template text
<%@ page language="java" contentType="text/html" session="false" %>
<jsp:useBean scope="request" id="userInfo" class="SubscriberRecord">
<jsp:setProperty name="userInfo" property="*" />
</jsp:useBean>
<% if(! userInfo.isValid()) { %>
<jsp:forward page="badInput.jsp" />
<% } %>
<% if(userInfo.createInDatabase() < 1) { %>
<jsp:forward page="NoDB.html" />
<% } %>
<html><head><title>Thank you for registering</title></head><body>
<h1>Thank you</h1>
<p>Your membership number is
<jsp:getProperty name="userInfo" property="id" />
</body></html>
Directive
Action tag
Scriptlet
Template
text
51
52
Directives
Action elements
• Essentially, these provide information to the component that generates the servlet from the JSP page.
• These are the XML‐like tags that can appear.
• There is a standard set of action elements – provided via the jsp tags
• These standard tags support – page attributes
•
•
•
•
Is a Session to be used for state maintenance?
How are output data buffered?
Is there a page that can be invoked if an exception occurs?
…
– common actions on “beans” – some actions on the servlet request, and response objects.
– Control collaboration with other jsp pages and/or servlets
– includes
• Standard action elements include:
• Fragments of prepared text from other files
– taglib
• Specify library containing custom action elements that supplement the standard JSP tags
53
–
–
–
–
<jsp:useBean>
<jsp:getProperty>, <jsp:setProperty>
<jsp:include>, <jsp:forward>
<jsp:param>
54
9
13/05/2014
Standard libraries of actions
Scripting elements
• Scriptlet
• JSTL will be illustrated through later examples
<% some Java code
• A JSP using JSTL will simply need a couple of page directives that specify which parts of JSTL are required (it’s a big library, usually don’t need it all)
%>
The code is dropped into the generated servlet.
Can include variable declarations – they are defined as local variables of the “service” function.
• Expression
<%= Java expression %>
• JSTL library code needs to be added to project but no special configuration data needed
gets translated into “out.print(Java expression )”
• Declarations
–…
55
56
Scripting elements contd.
Scripting elements contd.
• Declarations appear as
• Declarations –
– You can declare instance data members and member functions for the generated servlet.
– What might you want?
<%!
• Suppose that you decided that the servlet should own a database connection, and that this would be opened at initialization time and closed and destroy time
• Then you would define
– java.sql.Connection dbConnection;
– public void _jspInit() { /* connect to database */ … }
– public void _jspDestroy() { /* close that connection */ … }
java.sql.Connection dbConnection;
public void jspInit() {
…
}
// etc
%>
57
Template text
58
A JSP page
• All the standard HTML and content text fragments in the JSP page are referred to as “template text”.
• These text fragments are simply packed into a large number of output statements in the generated service function.
out.print(bit more html); out.print( bit more content text);
out.print( more html);
out.print( and still more html);
<%@ page language="java" contentType="text/html" session="false" %>
<jsp:useBean scope="request" id="userInfo" class="SubscriberRecord">
<jsp:setProperty name="userInfo" property="*" />
</jsp:useBean>
<% if(! userInfo.isValid()) { %>
<jsp:forward page="badInput.jsp" />
<% } %>
<% if(userInfo.createInDatabase() < 1) { %>
<jsp:forward page="NoDB.html" />
<% } %>
<html><head><title>Thank you for registering</title></head><body>
<h1>Thank you</h1>
<p>Your membership number is
<jsp:getProperty name="userInfo" property="id" />
</body></html>
59
Directive
Action tag
Scriptlet
Template
text
60
10
13/05/2014
Directives
Page directive
• <%@ directiveName attr1=“value” attr2=“value” %>
• <%@ page … %>
– include
– Lots of attributes!
– Can use more than one page directive.
• Attributes (some less important ones first):
• URI for file to include
– Can include chunks of HTML/content text from other files
– language
– taglib
• Defaults to Java, and for most systems there is only Java; some JSP implementations allow Javascript code fragments instead
• Prefix
– extends
– Group name for the tags, equivalent to “jsp:”
• You can define your own servlet base class, a refinement of HttpJspPage; but it would be unusual to want to do this
• URI for tag library
– Tag library should be in the WEB‐INF directory and should be described more in the web.xml file
– info
• Text describing your JSP page (for use in sophisticated development environment)
– isThreadSafe
• Set to false if really want a "single thread model" servlet
61
62
Page directive
Page directive
• Still more attributes
• More attributes of a page directive …
– errorPage
– isErrorPage (true/false)
• URL of JSP error page
• Error page has "Exception" object defined, script reports errors as encoded in this object
– autoflush (true/false)
– buffer (buffer=nkb, default 8kb)
– contentType
• Used to set content type ("text/html", or if you are ambitious "img/gif")
– import
• Reference java package used in code in page
– session (true/false)
• Default is JSP pages are parts of session, with cookie used to carry session id
63
64
Page buffering
Session
• Output from JSP normally buffered before being sent to client
• Allows you to start generating output, then maybe modify a header (can't change http headers if output • Default is for JSP pages to check for session, and start a session if none defined.
• Session relies on cookie based session identifier,
you should explicitly encode session identifier into all URLs in order to cater for clients who don't like cookies.
"committed" by some of it being written to back to web‐
server and thence to client)
• By default, output buffers flush and then can be refilled,
can change so that buffer full causes an error exception (device to prevent generation of excessive output)
65
•
Turn off sessions if not really needed (many informational pages don't need session support)
Most examples that you will see assume that clients have cookies enabled and don’t bother with the messy extras of modifying all links to hold session ids for
cookieless customers.
66
11
13/05/2014
jsp: actions,
useBean
jsp:useBean
• Parameters
• <jsp:useBean … />
• Or
• <jsp:useBean …> …body … </jsp:useBean>
– class
• String with fully qualified name for bean class (if bean is class defined in WEB‐INF/classes, then no package name qualification needed)
– id
• Variable name for the object that is being created (for use in scriptlet code etc)
• Basically, instantiate bean; parameters set properties.
Body code would be related initialization steps – scope
– Scriptlet style
– Invocation of other action tags
– (Can have some template text, just becomes more outputs to response output stream)
• Page, request, session, application
– Also
• beanName
• type
Bean scope is important,
more shortly!
67
68
useBean
jsp:getProperty
• Checks scope specified for instance of specified class associated with identifier
• <jsp:getPropety name=“…” property=“…”>
• Parameters
– If already exists, return reference
– Else create object
– name
• Object’s name, as specified in <jsp:useBean id=“..”
• (Object could exist – something bound to session could have been set by any other servlet/jsp‐page involved in same session)
– property
• Property name, remembering rules regarding capitalization, matching “get” function etc
69
jsp:setProperty
70
jsp:setProperty
• <jsp:setProperty name=… property=…
param=… value=… />
• Parameters
• setXXX(XType …)
– Usually will have a String value from form parameter, so need String to XType converstion
– name, property object identifier and property;
– param value
• Boolean.valueOf(String)
• Integer.valueOf(String)
• …
• Alternative ways of specifying value; – param
data comes from a HttpRequest parameter, either use param=“…” to specify parameter or follow defaults of matching names
– value
data comes from a bit of scriptlet code
71
72
12
13/05/2014
jsp:forward
jsp:include
Bean scope
• <jsp:forward page=“…”>
– Discard any buffered partial response and bounce request to specified page
• <jsp:include page=“…”>
• Bean is just an object instantiated from specified class.
• How is bean object defined?
– ‘Local variable’ of “doService()” function of generated servlet,
this is page scope and is the default
• Actually, it is a bit more complex, explanation later.
– Variable added to session object using session’s setAttribute function,
this is session scope;
variable can be retrieved from session by other servlets or jsp’s in related group
– Variable added to HttpRequest object using its setAttribute function,
this is request scope,
gets passed with request if JSP forwards or includes other servlets
– Variable added to servlet context object using its setAttribute function
this is application scope.
– Flush buffer with partial response (committing and sending headers)
– Invoke other page, letting it output some data
– Resume processing
73
74
Bean scope
Bean scope
• A mechanism for specifying whether a shared data struct (bean instance) was:
– Attached to the HttpRequest object
• Code generated in the servlet for using a bean would be along lines
– Find container
• Used when creating a bean in one servlet/jsp and forwarding it to another
• If scope is request then container= httprequest else if scope=session then container= httpsession else if scope=…
– Stored in the current HttpSession object
• The ubiquitous “shopping cart”
– Stored in the webapp wide context data
• Data like the rates table from Acme Employees example
– Or just something belonging to this page
– Container has hash map of name/object pairs –
setAttribute/getAttribute (as seen when coding servlets)
ask container for required bean
mybean=(typecast) container.getAttribute(beanname)
75
76
Page scope
• For consistency, jsp beans that are “page scoped” cannot be simple variable of the service method,
they must be added to a “Page Context” object (setAttribute) and accessed through this
jsp:usebean
Create the object
Using JSPs alone
Add reference in
PageContext
JSP (+ application specific entity classes)
Scriptlet code and action tags
77
78
13
13/05/2014
JSPs alone
“Member form” example
• Initial hope for JSPs was that they would suffice for application development.
• Simple example built to illustrate approach
– Fill in a form (static HTML) with personal details
– Submit to a JSP
• WebApp
• Takes data from form and sets values in a “bean” (this bean is actually an Entity class for a database)
• Validate bean
• If invalid, divert to error JSP
• If valid write to database
– JSP using application defined business classes
– Coding
• A mix of scriptlet and action tags as needed
– As tag libraries evolved, the amount of scriptlet code decreased
• Still a valid approach for tiny webapps and for prototyping
• Example built in stages to illustrate JSP features
79
Static HTML form
80
The table
81
82
Instead:
A simple “entity” class manually constructed
Persistence
• Define a class with just private data members
• Not using JPA here because:
– Had several issues in trying to use EntityManagers etc from a member function of a JSP
• Cannot use resource injection to get transaction and entity manager factory (resource injection not supported by JSP);
alternatives (JNDI lookup of resources such as java:comp/UserTransaction) should work
• Let NetBeans add constructors
– Need one that initializes everything apart from id field (which has to be determined by database) and another no argument constructor.
– Main problem, never resolved:
• Transaction writing a new record “successfully completed” without exceptions –
but no new data in the database!
83
84
14
13/05/2014
Add getters and setters
Simple version of web app
• First version of JSP page will simply read data from form and set fields in an instance of members class;
then prints acknowledgement page
– This uses just jsp: tag library
85
86
The JSP processing page
Use of jsp:
• useBean
– Default is page scope
• getProperty
– Return individual property value
• setProperty
– Could set a specific property, specifying that value came from a parameter
– But setProperty( property=“*”) is more automated
87
<jsp:setProperty name="memberdata" property="*" />
88
Plusses
• Iterate through the list of name=value pairs in the input
– For each name, X, check for a function setX() in the class of the object whose properties are being set
• Now wasn’t that much neater than old servlet code with its:
String gnstr = request.getParameter(“givenname”);
…
Members datastruct = new Members();
datastruct.setGivenname(gnstr);
• If no such function exists, ignore that input
– If find a setX function, check the argument type
• If not String, use appropriate Java function to convert string from form into required type (e.g. use Integer.parseInt(str) if need an int)
– Invoke setX function with argument
89
90
15
13/05/2014
Troubles
“error” page
• If there are invalid data, there may be troubles
– You really don’t want to send that kind of exception report to a user!
Integer.parseInt()
won’t like this
• JSPs have a standardized scheme for dealing with any unhandled exceptions in the generated servlet.
• A JSP can specify another JSP as an “error” page
– If an exception does occur, the app‐engine (glassfish or other) will return this error page rather than a “HTTP 500 server side error” report
– The exception handling JSP is passed the exception so that it can report what went wrong
91
Adding an errors JSP
92
Working with an error page
This page, which isn’t an
errors handling page, is linked to an errors handling
page at exceptions.jsp
This page is an errors
handling page;
it prints the exception
93
Errors page
94
Going beyond jsp:
• By default, a JSP is NOT an errors page so there is no need to have isErrorPage=“false” in all page directives.
• There is no need for the errors page to actually print out the exception – users will not understand such reports.
• If you want your JSP to actually do some work, you need more than just the jsp: tag library
• Choices:
– Find a tag library that has a processing option that exactly matches your needs
• There are lots of tag libraries – some even do moderately useful processing like submit a SQL select query and put the data from the result set into a HTML table
– Write your own highly specialized tag class
– Use scriptlets
• Ugly but easy
95
96
16
13/05/2014
Members web app ‐ validation
Members.java
• Next version
– Static HTML form – enter data
– Members.jsp
An extra data member that will hold a list of errors if validation failed:
• Fill in instance of Members record
• Ask members record whether it is valid (scriptlet)
– If not valid, forward the invalid record to a JSP that will report why it is invalid
• Display data entered
• Since Members record may now be used by other JSPs, change the jsp:useBean tag to create the record attached to the request object (rather than have it page scope as before)
97
Simple validation
98
Member.isValid()
• Fields like givenname must not be null.
• Birth year – well apply some restrictions; don’t want persons claiming they were born in 1890 or 2022 etc
• Email – do some form of regex check
– Sun, in one of the Java examples, supplies a regex
pattern that is meant to match emails
• Sun’s pattern excludes upper case letters
99
Members.jsp
Bean attached to HttpRequest object;
not PageContext
100
Scriptlet code : ugly
• You can see why Sun wasn’t happy with scriptlet
coding
– Look at this
Scriptlet code
– Every good (SISAT) IT graduate working as a web designer will instantly remove this extraneous guff that you the programmer put in – just trash littering her/his pretty page
Scriptlet code
• Of course, there will then be a compilation error when the deployment process tries to compile the generated servlet code – and it will be your fault
101
102
17
13/05/2014
myerrorreport.jsp
OK data entered
Pick up the Members record that will have been forwarded attached as
an attribute of the request;
print its error message string
103
104
Invalid data
Persisting data • Need a datasource connection to MySQL
• Need a function to save the record
– Open connection
– Prepare statement
– Bind data
– Execute
– Run another statement to get record number
105
106
Declaring code in JSP
JSP declaration
• Need:
– Data member for datasource
– Overridden _jspInit
– Own saveRecord function
• Also
– A large number of import statements
Declaration <%! … %>
107
108
18
13/05/2014
Save function
JSP scriptlet code
109
110
It does work
Model 2
• JSPs introduced ~1998
• Action tags and scriptlets
• Doing all the work in the JSP
– Initial adopters tried doing all the work of a web app in JSP
• By 2000, verdict in
– JSPs maybe better than servlets for formatting HTML (you don’t need all those annoying out.print statements)
– But they aren’t that hot for doing the real work of a web app
• Yes it works
• So new model
• But ugly
– Do the work in a servlet
– Use the JSP for final output
111
Model 2
112
The new Model2Members Project
• In Model 2 JSP
– Essentially no use of scriptlet code
– Use new tag libraries (from Apache and others) that have action tags that are useful for conditional data display, iteration etc
• Many competing libraries
• Best features combined into JSTL ~2003
113
114
19
13/05/2014
Model 2 Members
Members web app
• Form
• Still have Members form
– Will for this example keep the static HTML forms
– Forms post data to servlet
– Report is just the membership number so not interesting
• Servlet
– Use JPA for data persistence
– Do work of web‐app
• Have a separate “list members” request
– This will illustrate “iterative” action tag
• Or, generally better, just control sequencing of work done by application specific classes that embody business logic
– Collect data that should be displayed as response
– Forward to JSP
• JSP
– Display data, using JSTL tag libraries
115
The new Model2Members Project
• Java code
116
The new Model2Members Project
• JSPs
– class Members:
– Index.jsp
• Entity from database (JPA) class
– class MembersServlet
• Welcome page with links to forms
• Accepts form input
• Creates Members record, sets its fields
• Asks it if valid
– addmemberreport.jsp
• Reports successful addition of a record
– If not, send reason why data not acceptable to an error report JSP
• If looks valid, save it to database (getting details of member number automatically)
• Forward to another reporting JSP
– class ListingServlet
– listreport.jsp
• List of records in HTML table
– myerrorreport.jsp
• Accept form input
• Run JPA request
• Forward result to JSP
• Report on errors in processing
117
The new Model2Members Project
118
The (auto‐generated) Entity class
• Static HTML
– ListForm.html
– MembersForm.html
Of course these could be as JSPs
119
120
20
13/05/2014
Validation framework
Validation framework
• JPA 2 links into a validation framework
• Note that there is a NotNull annotation on the id member
• But the id is for an auto‐increment field handled by MySQL – and it should be NULL!
• Best remove that annotation.
– Note how the data members in the generated class are tagged with annotations relating to checks;
there are checks for not null, checks on length of a string etc.
– These will be applied when an entity is persisted!
• So you can get validation exceptions
– The exception has a member data structure which is a set of descriptions for all the constraints that were violated
• In this example though, we want to do our own validation and report problems rather than pick up exceptions.
121
Own validation
122
Members.java
• You can add extra data members to an Entity class but must mark them as Transient (otherwise the persistence mechanism will get confused when trying to store records)
• Will continue to do our own validation (though auto validation will apply as well)
• Add a validation function to the JPA class
– Call function
• It returns true or false
• If false, the class has a String data member that will contain an error report
– This member is not “persistent”!
123
Own validation
124
MembersServlet
125
126
21
13/05/2014
MembersServlet.doPost
MemberServlet.doPost
• First stage:
– Get parameters
– Create and set members of entity
– Ask if valid
• If not –
– Get string describing problem
– Attach it to request object
– Forward to error reporting JSP
127
Report JSP
128
addmemberreport.jsp
• Servlet adds completed Members object to request and forwards to JSP for display.
– jsp: library will suffice
129
Error reporting JSP
130
Own error checking
• Pick up string with error message from request, and print it
jsp: library will suffice here – just want to pick up data passed with request (simple
String data) and print it
131
132
22
13/05/2014
Triggering a JPA Validation error
ListingServlet
• Entered too long a name in the name field (browser’s maxlength check removed first)
133
134
Listing servlet results
listreport.jsp
• Listing servlet creates a list of Member objects satisfying required constraints
• List is added to request
• Request forwarded to JSP
• JSP processing:
– If collection is empty, report this (simple <p>…</p> output)
– If collection has members, create a HTML table listing their data
• Here need conditional tests and iteration provided as tags
– Use JSTL library
• “if … then … else …”
– Actually, the syntax is
choose … when … otherwise
• “foreach”
– (syntax is “foreach”!)
135
listreport.jsp
136
listreport.jsp
• Data were attached to forwarded request – so are a member “results” of the “requestScope” object ‐‐‐
requestScope.results
– Naming style is similar to Javascript
• JSTL has a built in test function that can apply to a collecton ‐‐‐ “empty”
– empty requestScope.results
• Were we passed an empty collection?
137
138
23
13/05/2014
listreport.jsp
listreport.jsp
• JSTL foreach
– Working variable and collection
• var=“member” items=
– Within foreach can access “member” object, again Javascript style access its individual fields –
• member.id, member.givenname, …
139
140
JSTL
JSTL
• Classes implementing JSTL tags may be part of the servlet container’s library – no need for extra “.jar” files in application.
If needed (as with our Glassfish Appserver) add JSTL libraries to project
• Refer to Java tutorial for details
• for a complete list of the JSTL tags and their attributes.
• Core:
– Variable definition and manipulation
– Flow control
– URL related
• SQL
– Connections and queries
• Internationalization
– Number and date formatting, message strings
• “XML”
Ominous – Oracle seems to have let the online links to the documentation go bad.
141
142
JSTL core
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
…
<c:set var="foo" scope="session" value="..."/>
…
<c:forEach var=“Item" begin="0" items=“…">… </c:forEach>
…
<c:if test="${!empty param.CustomerName}"> … </c:if>
143
144
24
13/05/2014
JSTL
Expression language
• Previously could have fragments of scriptlet code used in tags – e.g. code to access data member of some “bean” attached to request, or code to get an iterator for the struts logic:iterate tag library:
• Intent is that “standard” tags will replace use of in‐
house and 3rd‐party tag libraries for routine operations.
• SQL tags – intended to quick prototyping, advice is not to use them in real applications
<logic:iterate id="sg" collection="<%= theLeague.games() %>" >
• Expression language – alternative, supposedly simpler scripting language that can be used for such purposes (claim is EL is easier for “web designers” to use than scriptlet code)
<sql:query var="books" dataSource="${applicationScope.bookDS}">
select * from PUBLIC.books where id = ?
<sql:param value="${bid}" />
</sql:query>
<c:if test="${sessionScope.cart.numberOfItems > 0}">
...
</c:if>
145
146
Expression Language
EL
• ${ EL code }
• Code accessing data members of objects, performing relational tests etc; many implicit objects
• Supposedly identical to Javascript on those parts that overlap.
– servletContext, session, request, response, param, …
• One common use – accessing parameters with form data
147
148
EL ‐ examples
JSTL : SQL
<c:set var="bid" value="${param.bookId}"/>
• Picks up form input field bookId and places value in “bid”
• Uhm …
<sql:query var="books“ dataSource="${applicationScope.bookDS}">
select * from PUBLIC.books where id = ?
<sql:param value="${bid}" />
</sql:query>
<c:forEach var="bookRow" begin="0“ items="${books.rowsByIndex}">
…
• Running SQL query then processing results within JSP page
149
150
25
13/05/2014
I tried, as have others
It works
• Poor documentation effort!
• But all I got was exceptions – no suitable driver found
– Considering that people have been posting problems on web for 10+ years you would have thought that Sun/Oracle would have clarified things a little.
– The datasource was being used successfully in servlets
• I am not alone
– Dozens of complaints on Google over many years
• Datasource name in tag is not interpreted as the actual datasource name
– It’s simply a name for a datasource used by this program
• Applying to different servlet containers – it’s not a glassfish issue
151
So where is the data source
152
Another example
• The real data source has to be identified in the configuration files.
• A JSP page using SQL tags:
– Web.xml
• Include a reference entry for the datasource as named in the SQL tag
– Sun‐web.xml or glassfish‐web.xml
• (For us – glassfish‐web.xml)
• This has an entry mapping the datasource name as used in the SQL tag to the real JNDI name of the deployed data source
153
Some config files – web.xml
154
My real and application datasource names are identical, but I must state this in the mapping file
More config files – glassfish‐web.xml
155
156
26
13/05/2014
It runs
… but anyway …
• In all the discussions that Google finds concerning such problems (and generally “fixes” that don’t fix the problems), someone will inject
“You shouldn’t access persistence storage from the display level”
• Quite so
– I guess it isn’t a bug, the exception about not finding the driver is a “feature” added to discourage naïve developers from using inappropriate designs.
157
158
Two struts
• Apache.org says:
The Apache Struts Project offers two major versions of the the Apache Struts web framework. struts
Struts 1 is recognized as the most popular web application framework for Java. Struts 1 is the best choice for teams who value proven solutions to common problems. A (very brief) introduction to “struts 1” – the model‐view‐control framework for servlets
(~2000)
Struts 2 was originally known as WebWork 2. The 2.x framework is the best choice for teams who value elegant solutions to difficult problems.
159
Web application?
160
Well, you could use EJB (~1998)
• By ~2000, Java web applications could be built using servlets and application beans to do the work, and JSPs to display results.
• Web application?
– There was no coherent application
– What you had was a set of servlets (and beans) that implemented individual use‐cases
Same set of problems as discussed when introducing Zend framework – PHP’s
somewhat later variant on building a coherent web application with a Model‐View‐Control architecture
Some differences summarized at http://www.java‐samples.com/showtutorial.php?tutorialid=200
• Now it was possible to use a 4‐tier architecture:
– Client, web‐server, ejb‐engine (application‐server), database
rather than a 3‐tier (client, web, database) architecture
• The 4‐tier architecture allowed you to build a “session bean” that had all the business logic that was otherwise scattered over different servlets and application beans.
• But 4‐tier architectures didn’t appeal to all
– (A few of you may learn something about them in CSCI398)
161
162
27
13/05/2014
Building a real “web application”
A model‐view‐control architecture?
• Servlet containers did do a little of the work
• JSPs are fine for a “view” component.
• Control –
– Authentication and authorization managed centrally
– Life cycle management
– (Later, resource management like pooled database connections)
• Can one replace a set of servlets by a single application?
– There will have to be – It would be “nice” if one could have a single dispatcher that read configuration data describing an application
• Elements that handle the various distinct use cases
• Some centralized “dispatcher” that determines what work is to be done
• Action required, persistent data manipulated
• Conditional control transfer description
– Do this next if action succeeded
– Do this next if action failed
– JSPs can handle the final display –
• just need to package dynamic data in structs and forward to the JSPs
163
164
Birth of struts
NetBeans view of struts
• Apache’s struts project was an attempt (successful) to build such an architecture on top of servlets.
• struts has as a core element a class ActionServlet
– This is its dispatcher, or in design pattern terminology its “FrontController”
• Servlets had been created with that “servlet‐mapping” web‐xml feature that specified how a URL in a request got mapped to a servlet handler.
• This servlet‐mapping provided the routing mechanism for struts
– All URLs used in struts generated pages will identify the actions requested with names that end with .do
– The servlet‐mapping rule *.do maps all such requests into the ActionServlet
165
166
ActionServlet
ActionServlet
1. Get and Post requests will arrive at the ActionServlet
2. The ActionServlet can inspect the actual request pathname
– This will be used to key into a data structure that it has built from information in a configuration file
– The configuration data will identify a bean class for the data and a class that performs the process
3. The ActionServlet will copy parameter data into an instance of the appropriate bean structure (using reflection as with JSP’s jsp:setproperty bean property value)
–
“ActionForm” … kind of a base class for these beans
4. The ActionServlet will (usually) instantiate an Action (instance of a sub‐class of framework Action class) that will perform business logic operations on the bean (ActionForm)
5. Processing results in a ActionForward object that identifies the next processing step
–
Usually, this will simply identify either a “success report JSP” or a fail report JSP.
6. Appropriate data forward to JSP (as attributes of request), JSP presents results
4. The ActionServlet …
167
168
28
13/05/2014
NetBeans view of struts
Similar to Zend Framework?
• Well, kind of.
– Different organisation
• ActionForms – possibly correspond to Zend‐Form class
• Action –
– Zend Framework has “Controllers” that have multiple action member functions
– Here have many different Action classes
• But at the next step struts gets more sophisticated and more complex (and has an even higher learning curve barrier).
– Much of struts is based on “declarative” styles of development
• Creating applications defined in terms of complex XML documents that are interpreted by the ActionServlet
169
Try for a “hello world” example
170
NetBeans – struts project starter
• How about listing member names chosen by gender – shouldn’t be too complex.
• So create a new NetBeans Java web‐app specifying use of struts … • NetBeans creates a project that is a working web application
(At least it didn’t just say “Hello World”)
• Let us see what it consists of … 171
A few XML files with
data defining the
application
172
index.jsp
• Start with something easy – index.jsp should be a good place to start
A couple of JSPs
A “.properties” file – same role
as Zend Framework’s
application.ini
Just a few libraries that
make up the struts
framework
• WTF
• Oh ok, it’s just redirecting us to “Welcome.do”
– As that is a .do URL, it will go to the the ActionServlet
• As can be seen from the web.xml file :
173
174
29
13/05/2014
struts‐config.xml
welcomeStruts.jsp
• So what is the ActionServlet to do with this request for “welcome.do” • It will determine the Action from data originally in the “struts‐config.xml” file
– This will have been parsed and built into a run‐time data structure when this web‐
app first starts; struts doesn’t expensively reparse the XML on each request.
• There isn’t much in the default struts‐config.xml file – but there is a an “action‐mapping” for welcome
– So here it is simple:
• No need to create any bean structure, no need to run any validation of data, no need to do any processing
• Simply forward to welcomeStruts.jsp
175
welcomeStruts.jsp
176
welcomeStruts.jsp
• Import struts’ own tag libraries
• logic:notPresent
– tags‐beans: • Things that jsp: library could do plus a few more operations
– tags‐html:
• ? Wait and see
– Conditional test
– Here checking whether there is a message for this action in applicationScope
We have seen the code run and it didn’t report an
error so obviously the message data was found.
– tags‐logic:
• Conditional operations and iteration, precursor to JSTL “core” library
177
178
Who put the message data into application scope?
welcomeStruts.jsp
• That was done when the web‐app was initially loaded –
– The ActionServlet would have loaded the data from the ApplicationResource.properties file
• bean:message
– Somewhat similar to JSTL c:out; find some data to print as a String
– Here, the data should be found in applicationScope with a key as specified.
welcome.message
179
Remember, servlets remain in memory once loaded; it is OK to do a lot of work at initial load time,
it will save time later.
180
30
13/05/2014
Can edit the properties file
Making a respectable application
• How about another version of the “members” application.
• A new message
– Can convert the struts 1 welcome framework into a real application by adding JSPs and Java classes and configuration data.
• This version of “members” will simply have a form to enter gender required in listing, and the code to go from there to a list of member names. 181
StrutsMembers1
182
<html:tags …> for form
• Start with the vanilla “isn’t she beaut” struts project
• Create the form using struts <html: tags
1. Edit that strutsWelcome.jsp
2. Change some messages in the properties file
3. Add a new JSP for a search form
183
Using “members” class
Create a page that can show results
• ShowResults.jsp
• Application uses that simple Members class illustrated earlier
– Data will be in a bean
– Use struts logic iterate etc to display content
Note an oddity here. The ShowResults.jsp is placed in the WEB‐INF folder, below the
normal WebPages folder. This can be done in any Java Web app, not just struts.
Why? Servlet containers will not return such pages for a GET request with a URL; this
eliminates chance of inquisitive user reaching pages they shouldn’t get to directly.
184
– Successful action will attach an ArrayList<Members> to the request
185
186
31
13/05/2014
A page for error reports
ActionForm class
• struts provides for ActionMessages (ActionErrors) that can be used to report problems – they get attached to the request object.
• Can forward to an error presentation page.
• Special <html:errors /> tag – becomes code to iterate through error message collection.
• Next, need a class that will hold the data submitted in the form
– The struts framework will all fill its data fields from form parameters (much like jsp:setProperty did)
• Netbeans has a “struts” category in its new files menu – want “struts action bean” 187
Usual auto‐generated place holders
188
Create own members and validation
• Generated class has auto‐generated int and String members –
just to remind you how they are done.
• Replace these by members that correspond to the fields in the input form (and which have appropriate names for the bean‐style conventions)
189
190
An action
Action
Identify data bean that it works with
• Next, add an Action subclass
– This can work with the form bean – validating it, then in Action.execute() processing the data.
• Action class has to have lots of configuration data in the XML
– Fortunately, NetBeans handles most of the work setting this up
Action path to match entry
in the html:form tag of the
SearchForm.jsp
Bit oddly named, the “input resource”
is the errors page if the form bean fails
to validate.
(I’m using one errors page for all types of error.)
191
192
32
13/05/2014
An action added
Execution
• A stub class generated, an XML deployment statement added
• Go to the database, retrieve the records
193
Execution
194
Search code
• Use DataSource (configured into glassfish in earlier example)
• Pick up parameters from the (now validated) form bean:
– Run query
– Collect results manually crafting Members objects • Returned data will be list of members
• try { … } catch { … } finally {remember always close db connection}
– If exceptions, create an error report, add it to systems errors, and “failure” return
• Error reports can be parameterized.
195
On exceptions
196
Define “forward” relations in XML
197
198
33
13/05/2014
It works!
Can trigger error handling
• Change validation code so that “OTHER” not allowed and pick “Other” in form:
• Make an error in SQL
199
Validation
200
Validation ‐ NetBeans
• struts has mechanisms for data entry validation that are as sophisticated as the later Zend framework versions,
but which are configured very differently.
• As with Zend, there are effectively a number of pre‐defined validator classes;
you can define new classes and fit them into this framework;
or you can let the struts framework do its own validation using its classes and then supplement the checks in a validate() method that is custom designed for your form data.
• In struts validation is defined largely through XML deployment descriptors
– (Bit more sophisticated than Zend’s in‐line code invoking operations of instances of Zend
validtor classes)
• NetBeans includes validator‐rules.xml and validation.xml in the struts projects that it builds
– validator‐rules.xml
• Definitions of validation tests such as “required”, “date”, “email”, “match” (you supply regex), …
• You would only change this if defining your own validator
classes
– validation.xml
• You edit this to describe the fields in your form and the validation checks that are to apply
– It contains two example form specifications, you can remove these
201
202
Validation NetBeans
struts validation example
• You have to use a different base class for your form class – there is a “super class” option in the dialog for creating a Form Action Bean
• Example – a form for data entry of another member: • Add to struts project the components necessary to handle record creation:
Updated config
AddResult.jsp – report successful
creation of record
addForm.jsp – the form page for data entry
using struts HTML tags
Checking
requirements
AddAction.java – the Action class whose
execute method saves the record to MySQL
AddForm.java – the Action Form bean class
203
204
34
13/05/2014
addForm.jsp
AddForm subclass of ValidatorForm
<html:errors /> div : explained shortly
Form markup using struts
html tags
Validation?
Do what parent class does.
Could add application
specific tests here if needed.
206
205
AddAction
AddAction
Pick up data from the validated ValidationForm bean.
207
AddAction
208
AddResult.jsp
Insert data into MySQL, then
pick up record number (which is
inserted into an extra member number
field in the form bean)
Limited report page – just showing that things do work
209
210
35
13/05/2014
Demo
Bad data?
Get back the form submission page with
data as entered and
error messages!
211
Magic happened
212
Properties
• It’s all in the configuration data
• Lots of modifications of existing error messages and additions of more messages
– Properties file:
• Lots of customized error messages
– struts‐config.xml
Changed prefix style to
enhance error messages
• New elements
– Element for the add form has different error handlers for validation errors and action errors
» Validation errors go back to data entry form
» Action errors to the error page illustrated before
– validation.xml
• Definition of the form listing the validation tests that apply to each field
Added messages that
get referenced in
the validation tests.
213
struts‐config.xml
214
Validation requests
Two form beans
are identified
Test “givenname” data entered:
it’s required, it has a “mask” (regex)
test that says it must consist only of
letters
Add action:
on validation error go back to addForm.jsp (“input”)
on success go to AddResult.jsp
215
on action error, use same errors page as search action
216
36
13/05/2014
Validation requests
Validation requests
Test “familyname” data entered:
it’s required, it has a “mask” (regex)
test that says it must consist only of
letters, hyphens, and apostrophes
Test “birthyear” data entered:
it must have a value in range 1920
to 200
Test “email” data entered:
it must match struts own regex
for valid emails
Test “gender” data entered:
it’s required, it has a “mask” (regex)
test that says it must be the string
MALE or the string FEMALE
217
struts
218
struts
• As sophisticated (and complex) as Zend
• Different in detail, but overall the same style
– Model View Control
– Front Controller
– Form objects that get loaded with data from input
– Supplied validation classes
– Routing to different template response pages according to success/failure of validation and subsequent actions.
219
220
Declarative v. inline‐code
• Major style difference is struts is to a significant degree “declarative”
– Specify what you want in XML template files
… and there is yet another way …
• Zend relied much more on in‐line coding
– Get the form
– Grab data from field
– Create validator
– Apply validator to data
– ….
Brief (!) introduction to
Java Server Faces
a “component based framework”
221
222
37
13/05/2014
Java Server Faces: Cautions
Java Server Faces
• Java Server Faces has versions 1 & 2 with substantial differences
– Make sure that the on‐line tutorial that you are following is intended for your version! (Almost always should be using JSF 2 now).
• JSF 2:
– Uhm – in many places there are two different ways of accomplishing a task (e.g. “injection” of a resource)
• A different kind of framework.
– An attempt to create something more similar to a Java Swing/AWT application
• Components like text boxes, lists, tables
• A more traditional way, similar to JSF 1, and working with a variety of application engines
• A new approach, “CDI”, only on more modern app servers
– Generally simpler for the developer to use
– JSF pages use almost the same “expression language” as JSPs but there are differences such as the time at which an expression is actually evaluated
– JSF used to use JSPs for all the presentation layer – but now mainly use “facelets”, a newer technology for building up pages
– Rendered on the screen – though in very different ways
» Swing/AWT rendering is through Graphics and drawing operations
» JSF components rendered down to HTML!
• Components can have event listeners waiting for actions by the user
• So you are likely to be quite confused by the very varied examples that you will encounter
223
– But the action handler code is in the server (whereas with Swing/AWT display code and event handler code are part of the same program)
– “Code” in a page may appear to make direct use of objects that must exist in the server
Some conceptual similarities to Microsoft’s “Web Forms” (ASP.Net) that preceded JSF 1 by ~3 years 224
The adventures first,
explanations take too much time
The Guru
A better class of
“Hello World”
Program
225
Aphorism server
Do you think that you may have seen this before?
Wait till you get to CSCI398.
226
The Guru code
• A web page, and a bean class –
Nothing special – just the odd @Named annotation
– And not an awful lot of configuration data
Another tag library in use
jsf/html tags.
.xhtml – well, kind of; supposed to be almost
XML compliant
227
228
38
13/05/2014
Deployment XML
More deployment XML
Pretty simple, agreed?
Really nothing there apart
from an indication that
another of those “FrontController” objects
is involved – something
called “Faces Servlet”
Pretty simple, agreed?
229
230
So, all magic again
First, implement a more sophisticated Guru
• But it doesn’t seem that much different from JSP
• This Guru can be told to move through its collection of knowledge
– Ok, we didn’t have to say we were going to use an instance of our Guru class (no jsp:usebean),
we just used it
– Have also chosen to give it an explicit name “theguru” and to say explicitly that we want it in sessionScope
• implements Serializable?
• Obviously the JSF framework does something sensible like look for an existing instance (in some default context, probably JSP’s “sessionScope) and if it doesn’t find one it creates one.
– Just a requirement for a session scope variable – I’ll reveal more in CSCI398
• Maybe you aren’t too impressed.
– Then just wait, there’s more!
231
A more sophisticated Guru
232
A more elaborate index.xhtml page
233
234
39
13/05/2014
But look what happens when you press the buttons!
Impossible!
• You are pressing buttons in the browser and the state of an object in the server changes!
• That is impossible.
“‐1” = 110
0
• It must be magic.
1
0
1
2
3
2
235
Magic? Too much Harry Potter in your past
236
Page source
• It’s not magic.
• It’s just HTML (and sometimes, at least with Microsoft’s version, some Javascript)
• Look at the source of the HTML page:
Those buttons – they are <input type=‘submit’ … />
237
How did it work? 1
238
How did it work? 2
• Each time a button was pressed, the form was submitted
– Hidden data fields:
• These hold information that lets the “FacesServlet” identify the object that is to be manipulated.
– Named submit buttons
• The FacesServlet invoked the move() operation of the “theguru” object in sessionScope.
• The FacesServlet than had to re‐compose the response page
– So it again invoked the getEnlightenment() method of the guru object – getting a new choice of aphorism
• The FacesServlet will still have the information that maps these to the action functions (#{theguru.move()}
– EL using $ gets evaluated just once as page is composed into code – as when a JSP is “compiled” into a servlet
– EL using # gets preserved and re‐evaluated every time the expressions are needed
239
• The complete page was returned for display in the browser
240
40
13/05/2014
Interaction by complete page replacement
Complete page replacement?!
• The default operations of JSF (and Microsoft’s • A costly strategy
• Actions in the browser trigger “post” operations of form data
• It’s actually quite reasonable for an “in‐house” application working over an intra‐net
– Entire page being replaced
ASP.Net which was the original realization of this approach) involves complete page replacement.
– Lots of hidden data fields in the form contain data that allow server side to (re)create objects, or find existing objects, and establish the correct “view state”
• Server handles post request, and returns the updated page as a response.
• Costly?
• (My Guru consultation page is quite simple, but imagine this on a real page with a complex structure).
– Allows for the creation of interactive applications that work in conventional browsers – easier for people such as clerks to learn as so similar to other web‐usage.
• It isn’t a good idea for an application that runs over the Internet
– (Obviously, AJAX could be, and sometime is, used for the interactions rather than complete page replacement – but AJAX is a later addition to these frameworks)
241
242
Illustration of operations : “welcome page”
You want something more than “hello world” (or guru)
• OK
– You are to develop a web app that is to allow a user to select a faculty getting a view of the subjects offered by that faculty, and then select a subject to get full details.
• Subject data are stored in a MySQL table:
Select a faculty
243
Illustration of operations : “faculty selected”
244
Illustration of operations : “subject selected”
Pick a subject
245
246
41
13/05/2014
NetBean’s project
Java code
• As you might expect, there is a required structure for JSF
• Subject
– Things like css style sheets, Javascript files etc, have to be located in sub‐directories (JSF uses the term “libraries”) of a “resources” directory in with the web pages.
– A little “struct” holding subject code and other data
• SubjectData
– A JSF Managed bean class
• Responsible for getting the data (a collection of Subject objects) from the database and making them available to the JSF page
247
248
Subject.java
SubjectData.java
Should have been possible to
use resource injection to set
up the data source. It failed.
I couldn’t be bothered to search on Google for likely cause.
So the data source is set up using
explicit JNDI lookups.
Data members made available to
JSF:
faculties – list of faculty names
chosen – name of currently selected faculty
facultyofferings – collection of
Subject instances
chosenSubject – selected instance
249
250
SubjectData.java
SubjectData.java
• Constructor
• Access and state functions:
– Get data source
– Use data source to get a connection and use this to retrieve names of faculties and store these in an ArrayList<String>
– Set subject data to null
– State?
– Has a faculty been picked?
– Has a specific subject been selected?
• These are needed to control selective display of elements in the page.
– Access
• When faculty is selected in web page:
•
•
•
•
– Again get connection from data source
– Use this to create a collection of Subject objects
251
Give me a collection of faculty names
Give me the current chosen faculty
Give me the subjects offered by that faculty
Give me the subject record for a chosen subject
252
42
13/05/2014
SubjectData.java
SubjectData.java
Get faculty names …
select distinct faculty from subject
• “state”
– Has a faculty been selected?
– Has a subject been selected?
Initialization
253
254
SubjectData.java
SubjectData.java
• Choosing a faculty in form page
• “access”
1. Mutator – setChosen
– Get selected subject, subjects offered by a faculty, list of faculties, chosen faculty
•
Nothing special about this
2. Event
•
Also specify a change event
–
–
•
Work to be done if there is a change of chosen faculty (in this case load subjects for another faculty)
Operation is distinct from simply setting the data member “chosen”
Event style:
–
–
Well I think it was originally Microsoft’s idea (I saw it first in .Net stuff)
It makes web programming very similar to writing an interactive native application (WebForms~WinForms, JSF~Java+swing)
255
SubjectData.java
256
JSF page
• “change event”
• Conceptually equivalent to a more conventional page with three <div> sections and (CSS) control over which <div>s are displayed.
– Run SQL query to retrieve the subjects offered by faculty
– Always show <select> with choice of faculties
– If a faculty has been selected, show a table with subject codes and titles
• Codes “are links” to get details of subject
– If a subject has been selected, show lecturer and description
257
Not actual HTML <div> sections and control over display done in server and only
selected parts sent in response page
258
43
13/05/2014
JSF page
“<div>” for faculty
selection form
“<div>” for faculty
details – name and
table of subjects
offered; only shown
if faculty selected.
“<div>” for subject;
only shown
(“rendered”) if a
subject has been
260
selected.
259
JSF page
JSF page
JSF form:
h:selectOneMenu – maps into HTML menu (~select, just always size=1);
f:selectItems – JSF “core” tags, takes a collection, generates set of HTML
<select> items – can specify value as well as label;
h:outputText – rendered if facultyChosen() method of managed bean returns true; it
shows text with string from getChosen() method of managed bean.
onchange action – don’t have an explicit “submit” button in this form; if
the value of the HTML <select> is changed, the browser will execute
standard submit; value specifies that the setChosen() method of the managed
bean will get called with the new chosen faculty name
valueChangeListener – function that is also to be called for this “change event”
261
CSS
h:datatable – generates HTML table that will display data in collection retrieved by
getFacultyOfferings; uses some CSS styles;
table defined by the h:column entries that specify “facets” (like header titles for
column) and data to be displayed in column;
the entries in the subject code column are “commandLink” (i.e. submit buttons)
262
Are you impressed?
• That was probably the most succinct, neatest bit of web crudding that you have ever seen.
– A sleek JSF page
– Just a very simple managed bean and a struct
• But probably won’t have much appeal to your SISAT graduate colleagues who are “designing the company’s web presence”
– They aren’t going to make much of those truly weird h: and f: tags
263
264
44
13/05/2014
Why no visual page builder?!!
Component frameworks
• When we look at Microsoft’s version, we will see a page that is created using a GUI style point‐and‐
click editor with a palette of tools (e.g. insert table)
– Pick tool, add element, up pops dialog asking for parameters (e.g. what collection? Any rendering control?)
• There used to be a similar system in NetBeans
but netbeans.org apologises – they simply don’t have the resources to maintain it
– Also there are a number of still more specialised extensions to JSF that are competing and which would require varied editors
• Components?
– They are those user interface elements like the table, the action buttons etc.
– It is a lot clearer with the Microsoft scheme where you can actually use the same visual editor to create either a WinForms application (equivalent to a Java application using swing) or a WebForms applications (browser as renderer, events sent to server side application – just as with JSF)
– Tags entered as text in a JSF page?
• Doesn’t really seem like defining an interactive event source component (as in a Java swing program)
– But it is doing just that
Eclipse does have a visual designer module for JSF
265
There are only 2 web apps
266
Look ma – no hands!
• Remember that there are only two web applications
• Members again – but this time try in truly automated style
1. Retrieve some data
2. Add new data
• Have demonstrated web‐app 1, so how about a JSF version of a data entry form that adds data to persistent storage
– NetBeans – new Java web project, and yes it uses JSF
– First step create an Entity class from database (will be using JPA for this example) and a persistence unit.
267
Almost what is wanted
268
Next – one button create all code!
• This is for a MySQL database
• New JSF pages from entity class
– Auto‐increment primary key
– Insert records with a null value for the primary key
• Best fix the generated code that says it must not be null
269
270
45
13/05/2014
Your application delivered:
It runs:
• CRUD application on demand:
Paginated display of member data
271
We can edit
272
We can delete
Remove Re Test;
273
But we cannot quite create (yet)
274
Best look at the generated code
• Only Create.xhtml
Create form generated has a field for
id, but for this table the id is an auto‐
increment integer and shouldn’t be
set by the user.
Also, there is only limited validation
done on data entry – we have a business
constraint that the birth year be in the
range 1920 to 1993;
we would also like checks on email and
names,
and finally would prefer that the
Gender field be a select box.
275
276
46
13/05/2014
Create.xhtml
Messages?
• Just a set of h:inputText components with accompanying h:outputLabel tags arranged in a h:panelGrid
• A properties file with messages was generated along with the rest of the code
– Can modify to make more relevant and add own
– The input fields are all tagged required=“true”, and have requiredMessage attributes
• E.g. requiredMessage=“#{bundle.CreateMembersRequiredMessage_e
mail}”
• A little editing is needed
277
Modifying Create.xhtml
278
Create.xhtml
• Remove the field for the id
• Edit other records to add “validators”
– Of course JSF has pre‐defined validator classes:
• Check numbers
• Check against a regex
• …
– So define a few validators on the input fields
– Also change the gender entry to selectOneMenu
with a couple of item facets
279
Create.xhmtl
f:validateRegex facets added to the given name and family name inputs,
validatorMessage attributes added referencing error messages (MyErrors_xxx)
added to the messages bundle file.
280
h:selectOneMenu with two f:selectItem entries for the gender input
It works!
Year of birth entry field gets an integer range check, email field gets a regex
check with a fairly simple version of email regex
The JPA class also has its own checks, so if the names are too long we will get a
persistence error. It has an optional email check – one that doesn’t allow
capital letters in email addresses.
281
282
47
13/05/2014
It reports any input errors
Like magic!
• Now that was easy wasn’t it.
• A complete crudy application with just a couple of mouse clicks and some minor editing to add validation tests.
• Now you ask
Why didn’t you just show us JSF instead of dragging us through Zend Framework, servlets, JSPs, and struts?
283
You aren’t IS/IT students
284
“Backing Components”
• Students in Information Sciences/Information Technology degrees can be allowed to believe in magic
– They can be shown just JSF (or, far more likely, the Microsoft version) and told that all that is required to create a web application is a couple of mouse clicks and maybe some minor editing.
• You are CS students.
• You are supposed to understand how things actually work
• If you delve further into JSF you can learn about “Backing Components”
– These are classes that you define to model in your Java application a part of, or maybe the entirety of a data input form.
– The Java code will work with UIInput objects that can represent input elements in the form.
• Gives you more sophisticated control over the handling of input data – but it’s relatively rare to really need such classes.
285
JSF – lots to learn
286
JSF extensions
• JSF
– It’s big
• 6 tag libraries
– Core, HTML, Facelets (user interface elements), composite components, (parts of) JSTL, and JSTL functions
– And that’s without the AJAX extensions
287
288
48
13/05/2014
Java web apps
Java web apps
• Diverse!
• Three or four tier:
• 3‐tier extension technologies:
– Struts 1 and 2
– JSF and its extensions
– Others
– 4‐tier (CSCI398) (browser, web container, application engine, database)
• Servlet and JSP in the web container
• Business logic in EJB session beans in the application engine
• Automated data persistence (JPA)
• Tapestry, wicket, …
• JRuby
• Google web toolkit
– 3‐tier (browser, web container, database)
• Basics:
– Servlet, JSP, JPA
• Advanced – using various extension technologies
– Component framework using AJAX rather than page postback
• …
– Numerous!
289
Company chooses technology
290
Most efficient web technology?
• Probably one of the Java variants
• If you become a Java web developer you will not meet them all
– “Persistence” of server components and pre‐compiled code
• In Java, server side components are created at deployment time or at first‐use time
– Someone in company will have chosen the technology stack that is to be employed
– You will have to specialize in that
– Don’t have to recreate objects as you do with the scripting technologies like PHP and, at least to some degree, with Microsoft
• Java will have been compiled to .class files before or at deployment time; “compiler” not needed at run‐time (whereas scripting technologies recompile)
• Server side Java compilation will convert more heavily used code to actual machine code rather than byte code
– Kicks in only after a burn in time to identify heavily used code – can make measurement of Java performance tricky as gets faster as you run it
– My guess: a 4‐tier version with Enterprise Java for the business logic
291
292
49