Invoking Java code with JSP

Download Report

Transcript Invoking Java code with JSP

INVOKING JAVA CODE
WITH JSP SCRIPTING
ELEMENTS
Creating Template Text
• A large percentage of your JSP document consists of
static text (usually HTML), known as template text.
• HTML look normal, and it simply “passed through” to the
client by the servlet created to handle the page.
• There are 2 minor exceptions to the “template text is
passed straight through” rule
• First, if you want to have <% or %> in the output, you
need to put <\% or %\> in the template text
• Second, if you want a comment to appear in the JSP
page but not in the resultant document, use
<%-- JSP Comment --%>
• HTML comments of the form
<!-- HTML Comment -->
are passed through to the client normally.
Invoking Java Code from JSP
There are a number of different ways to generate dynamic content
from JSP,(Simple application or small development team To
Complex application or large development team)
• Call Java code directly. Place all Java code in JSP page. Appropriate
only for very small amounts of code.
• Call Java code indirectly. Develop separate utility classes. Insert
into JSP page only the Java code needed to invoke the utility
classes.
• Use beans. Develop separate utility classes structured as beans.
Use jsp:useBean, jsp:getProperty, and jsp:setProperty to invoke
the code.
• Use the MVC architecture. Have a servlet respond to original
request, look up data, and store results in beans. Forward to a JSP
page to present results. JSP page uses beans.
• Use the JSP expression language. Use shorthand syntax to access
and output object properties. Usually used in conjunction with
beans and MVC.
• Use custom tags. Develop tag handler classes. Invoke the tag
handlers with XML-like custom tags.
Limiting the Amount of Java Code in JSP Pages
You have two options
– Put 25 lines of Java code directly in the JSP page
– Put those 25 lines in a separate Java class and put 1 line
in the JSP page that invokes it
• Why is the second option much better?
– Development. You write the separate class in a Java
environment (editor or IDE), not an HTML environment
– Compilation. You can press the Build button in IDE to compile
a regular java class
- Debugging. If you have syntax errors, you see them
immediately at compile time. Simple print statements can
be seen.
– Testing. You can write a test routine with a loop that does
10,000 tests and reapply it after each change.
– Reuse. You can use the same class from multiple pages.
Types of JSP Scripting Elements
JSP scripting elements let you insert Java code into
the servlet that will be generated from the JSP
page.
There are three forms:
1. Expressions of the form <%= Java Expression
%>, which are evaluated and inserted into the
servlet’s output.
2. Scriptlets of the form <% Java Code %>, which
are inserted into the servlet’s _jspService method
(called by service).
3. Declarations of the form <%! Field/Method
Declaration %>, which are inserted into the body
of the servlet class, outside any existing methods.
Using JSP Expressions
• A JSP expression is used to insert values directly
into the output. It has the following form:
<%= Java Expression %>
• The expression is evaluated, converted to a
string, and inserted in the page.
• This evaluation is performed at runtime (when
the page is requested) and thus has full access to
information about the request.
• For example, the following shows the date/time
that the page was requested.
Current time: <%= new java.util.Date() %>
Predefined Variables
To simplify the expressions, you can use a number of predefined
variables (or “implicit objects”).
The system simply tells you what names it will use for the local
variables in _jspService (the method that replaces doGet in
servlets that result from JSP pages).
• request, the HttpServletRequest.
• response, the HttpServletResponse.
• session, the HttpSession associated with the request (unless
disabled with the session attribute of the page directive)
• out, the Writer (a buffered version of type JspWriter) used to
send output to the client.
• application, the ServletContext. This is a data structure shared
by all servlets and JSP pages in the Web application and is
good for storing shared data.
Here is an example:
Your hostname: <%= request.getRemoteHost() %>
JSP/Servlet Correspondence
JSP expressions basically become print (or write) statements in the servlet
that results from the JSP page. Whereas regular HTML becomes print
statements with double quotes around the text, JSP expressions become
print statements with no double quotes. Instead of being placed in the
doGet method, these print statements are placed in a new method called
_jspService that is called by service for both GET and POST requests.
• Original JSP
<H1>A Random Number</H1>
<%= Math.random() %>
• Representative resulting servlet code
public void _jspService(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("<H1>A Random Number</H1>");
out.println(Math.random());
...
}
XML Syntax for Expressions
• XML authors can use the following alternative syntax
for JSP expressions:
<jsp:expression> Java Expression </jsp:expression>
• Don’t mix the XML version and the standard JSP
version (<%= ... %>) in the same page.
• To use the XML version, you must use XML syntax in
the entire page. This requirement means that you have
to enclose the entire page in a jsp:root element.
• Most developers use this XML version when they are
either generating XML documents or when the JSP
page is itself the output of some XML process
• Note that XML elements, unlike HTML ones, are case
sensitive. So, be sure to use jsp:expression in lower
case.
Example: JSP Expressions
<HTML>
<HEAD><TITLE>JSP Expressions</TITLE>
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Server: <%= application.getServerInfo() %>
<LI>Session ID: <%= session.getId() %>
<LI>The testParam form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY></HTML>
Comparing Servlets to JSP Pages : Reading Three
Params (Servlet)
• JSP works best when the structure of the HTML page is fixed but
the values at various places need to be computed dynamically.
• If the structure of the page is dynamic, JSP is less beneficial.
Sometimes servlets are better in such a case.
• If the page consists of binary data or has little static content,
servlets are clearly superior.
• Sometimes neither servlets nor JSP alone, but rather a
combination of the two. (Integrating Servlets and JSP: The Model
View Controller (MVC) Architecture).
ThreeParams.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY >”+
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: “+ request.getParameter("param1") +
" <LI><B>param2</B>: “+ request.getParameter("param2") +
" <LI><B>param3</B>: “+ request.getParameter("param3") +
"</UL>\n" +
"</BODY></HTML>");
}
}
ThreeParams.jsp
<HTML>
<HEAD>
<TITLE>Reading Three Request Parameters</TITLE>
</HEAD>
<BODY>
<H1>Reading Three Request Parameters</H1>
<UL>
<LI><B>param1</B>: <%= request.getParameter("param1") %>
<LI><B>param2</B>: <%= request.getParameter("param2") %>
<LI><B>param3</B>: <%= request.getParameter("param3") %>
</UL>
</BODY></HTML>
•
•
The three parameters example of a servlet outputs the values of three
designated form parameters. JSP is also producing the same result for three
parameters.
But the JSP version is clearly superior: shorter, simpler, and easier to maintain.
Writing Scriptlets
•
JSP scriptlets let you insert arbitrary code into the servlet’s
_jspService method (which is called by service).
• Scriptlets have the following form:
<% Java Code %>
• If you want to explicitly send output to the resultant page, you
could use the out variable, as in the following example.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
• you can accomplished the same effect more easily by using a
combination of a scriptlet and a JSP expression, as below.
<% String queryData = request.getQueryString(); %>
Attached GET data: <%= queryData %>
• Or, you can use a single JSP expression, as here.
Attached GET data: <%= request.getQueryString() %>
• The following snippet specifies that the current
page is sent to the client as Microsoft Word, not as
HTML (which is the default).
<%
response.setContentType("application/msword");
%>
• Note: Remember that JSP expressions contain Java
values (which do not end in semicolons), whereas
most JSP scriptlets contain Java statements (which
are terminated by semicolons).
JSP/Servlet Correspondence
It is easy to understand how JSP scriptlets correspond to servlet code: the scriptlet
code is just directly inserted into the _jspService method: no strings, no print
statements, no changes whatsoever.
• Original JSP
<H2>foo</H2>
<%= bar() %>
<% baz(); %>
• Representative resulting servlet code
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("<H2>foo</H2>");
out.println(bar());
baz();
...
}
XML Syntax for Scriptlets
• The XML equivalent of <% Java Code %> is
<jsp:scriptlet>Java Code</jsp:scriptlet>
• If you use the XML version you must use XML syntax
consistently for the entire page.
• Remember that XML elements are case sensitive; be
sure to use jsp:scriptlet in lower case.
Scriptlet Example
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor = request.getParameter("bgColor");
if ((bgColor == null) || (bgColor.trim().equals("")))
{
bgColor = "WHITE";
}
%>
<BODY BGCOLOR="<%= bgColor %>" >
<H2 ALIGN="CENTER">Testing a Background of "<%= bgColor %>"</H2>
</BODY></HTML>
Using Scriptlets to Make Parts of the JSP Page
Conditional
Another use of scriptlets is to conditionally output HTML
or other content that is not within any JSP tag.
Key to this approach are the facts that
(a) code inside a scriptlet gets inserted into the resultant
servlet’s _jspService method (called by service)exactly
as written and
(b) that any static HTML (template text) before or after a
scriptlet gets converted to print statements.
• Example
<HTML>
<HEAD><TITLE>Wish for the Day</TITLE></HEAD>
<BODY>
<% if (Math.random() < 0.5) { %>
<H1>Have a <I>nice</I> day!</H1>
<% } else { %>
<H1>Have a <I>lousy</I> day!</H1>
<% } %>
</BODY></HTML>
• Representative result
– if (Math.random() < 0.5) {
out.println(“<H1>Have a <I>nice</I> day!</H1>");
} else {
out.println(“<H1>Have a <I>lousy</I> day!</H1>");
}
Using Declarations
• A JSP declaration lets you define methods or fields
that get inserted into the main body of the servlet
class (outside the _jspService method that is called by
service to process the request).
• A declaration has the following form:
<%! Field or Method Definition %>
• Since declarations do not generate output, they are
normally used in conjunction with JSP expressions or
scriptlets.
• In principle, JSP declarations can contain field
(instance variable) definitions, method definitions,
inner class definitions, or even static initializer blocks
JSP/Servlet Correspondence
JSP declarations result in code that is placed inside the
servlet class definition but outside the _jspService method.
Since fields and methods can be declared in any order, it
does not matter whether the code from declarations goes
at the top or bottom of the servlet.
• Original JSP
<H1>Some Heading</H1>
<%!
private String randomHeading() {
return(“<H2>" + Math.random() + "</H2>");
}
%>
<%= randomHeading() %>
• Possible resulting servlet code
public class xxxx implements HttpJspPage {
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("<H1>Some Heading</H1>");
out.println(randomHeading());
...
} ...
XML Syntax for Declarations
• The XML equivalent of <%! Field or Method Definition %>
is
<jsp:declaration>Field or Method definition</jsp:declaration>
• Servers are required to support this syntax as long as
authors don’t mix the XML version
(<jsp:declaration> ... </jsp:declaration>) and the
standard ASP-like version (<%! ... %>) in the same
page.
• The entire page must follow XML syntax if you are
going to use the XML form
• Remember that XML elements are case sensitive; be
sure to use jsp:declaration in lower case
Declaration Example
<HTML>
<HEAD>
<TITLE>JSP Declarations</TITLE>
</HEAD>
<BODY>
<H1>JSP Declarations</H1>
<%! private int accessCount = 0; %>
<H2>Accesses to page since server reboot:
<%= ++accessCount %></H2>
</BODY></HTML>
Implicit Objects (Predefined variables)
• JSP Implicit Objects are the Java objects that
the JSP Container makes available to
developers in each page and developer can
call them directly without being explicitly
declared. JSP Implicit Objects are also called
pre-defined variables
• JSP supports nine Implicit Objects which are
listed below:
• request: This is the HttpServletRequest object associated
with the request.
• response: This is the HttpServletResponse object associated
with the response to the client.
• out: This is the PrintWriter object used to send output to the
client.
• session: This is the HttpSession object associated with the
request.
• application: This is the ServletContext object associated
with application context.
• config:This is the ServletConfig object associated with the
page.
• pageContext: This encapsulates use of server-specific
features like higher performance JspWriters.
• page: This is simply a synonym for this, and is used to call
the methods defined by the translated servlet class.
• exception: The Exception object allows the exception data
to be accessed by designated JSP.
• request
This variable is the HttpServletRequest associated
with the request; it gives you access to the request
parameters, the request type (e.g., GET or POST), and
the incoming HTTP request headers (e.g., cookies).
<%=request.getHeader(“user-agent”)%>
• response
This variable is the HttpServletResponse associated
with the response to the client. The response object
also defines the interfaces that deal with creating new
HTTP headers. Through this object the JSP programmer
can add new cookies , HTTP status codes etc.
<% response.setContentType(“application/msword”);%>
• out
This variable is the Writer used to send output to
the client. out is object of JspWriter. The out
variable is used almost exclusively in scriptlets
since JSP expressions are automatically placed in
the output stream
<% out.println(“Hello World”); %>
session
This variable is the HttpSession object associated
with the request. The session object is used to
track client session between client requests.
<%=session.getId() %>
• application
This variable is the ServletContext as obtained by
getServletContext. Servlets and JSP pages can store
persistent data in the ServletContext object rather than
in instance variables. The difference between storing
data in instance variables and storing it in the
ServletContext is that the ServletContext is shared by all
servlets and JSP pages in the Web application, whereas
instance variables are available only to the same servlet
that stored the data.
<%= application.getInitParameter(“user”) %>
• config
This variable is the ServletConfig object for this page.
In principle, you can use it to read initialization
parameters, but, in practice, initialization parameters are
read from jspInit, not from _jspService.
<%= config.getInitParameter(“user”) %>
• pageContext
JSP introduced a class called PageContext to give a single point of
access to many of the page attributes. The PageContext class has
methods getRequest, getResponse, getOut, getSession, and so forth.
The pageContext variable stores the value of the PageContext object
associated with the current page. Passing pageContext is easier If a
method or constructor needs access to multiple page-related objects
<% pagecontext.setAttribute(“user”, name); %>
• page
This variable is simply a synonym for this and it is object of Object
class. This object is an actual reference to the instance of the page
<%= page.getClass().getName() %>
• exception :
This is an object of Throwable class. The exception object is a
wrapper containing the exception thrown from the previous page. It
is typically used to generate an appropriate response to the error
condition.
<%= exception %>
• Problem with implicit objects
– The predefined variables (request, response, out,
session, etc.) are local to the _jspService method. Thus,
they are not available to methods defined by JSP
declarations or to methods in helper classes.
What can you do about this?
• Solution: pass them as arguments. E.g.
public class SomeClass {
public static void someMethod(HttpSession s) {
doSomethingWith(s);
}
}
…
<% somePackage.SomeClass.someMethod(session); %>