Web technologies/2014-2015/Laboratory 8
JSP
editJava Server Pages (JSPs) technology allows the programmer to mix static HTML pages with dynamically generated ones.
JSPs have some advantages over other related technologies:
- vs pure servlets - it is more convenient to write regular HTML files written in JSP rather to have lots and lots of println statemenents that generate your code. Also by separating the content from the look you can divide your work: designers working on the GUI, programmers working on the Java code, database administrators working on the databases, etc.
- vs ASP - ASP is a Microsoft technology, making it platform dependent
- vs PHP - data types, Java technology, etc.
- vs static HTML - regular HTML, cannot contain dynamic information
JSPs are often used when we want to mix static and dynamic content in a web page. The question is how do we accomplish that? The answer is pretty straightforward: the static HTML code is written using the usual tags, and the dynamic part is enclosed in special tags - the opening tag: <%, and the corresponding closing tag: %> - .
The files are usually saved with the .jsp extension and placed where all the other HTML files are located.
To simplify the code, the programmer is given 8 automatically defined variables, sometimes called implicit objects
- request - this variables represents the HttpServletRequest associated with the request. It lets you look at the request parameters, the request type and the HTTP headers
- response - this variable represents the HttpServletResponse associated with the response to the client. Despite the fact that it is illegal to set the HTTP status code and response headers once the output has been sent to the client, by using response this is ok, since the output stream is buffered
- out - this represents the PrintWriter used to send output to the client. Since we want to make the response object useful, this is a buffered version of the PrintWriter, called JspWriter
- session - this is the HttpSession object associated with the request. Since the sessions are created automatically, this variable is bound even if there was no incoming session reference. However if you use the session attribute of the page directive to turn sessions off, any attempt to reference the session variable will cause errors at the time the JSP page is translated into a servlet
- application - this represents the ServletContext as obtained using getServletConfig().getContext()
- config - the ServletConfig object for this page
- pageContext - the PageContext class was introduced to encapsulate the use of server-specific features
- page - simply a synonym for this
NOTE: JSP 1.1. introduced a method for extending JSP tags, called tag libraries. Through the use of this one can add similar tags to jsp:include or jsp:forward but with prefixes other than jsp. Each custom tag library will have its own specific documentation.
JSPs introduce 3 main types of constructs that can be embeded in a web page: scripting elements, directives and actions:
You can find a simple example here.
Scripting elements
editScripting elements let you specify Java code that will become part of the resultant servlet. The programmer has access to a number of predefined variables such as request :
[...]
Thank you for logging in:
<b><%= request.getParameter(“name”) %></b>
[...]
By using scripting elements you can insert Java code into the servlet that will be generated from the current JSP page:
- Expressions:
Your hostname: <%= request.getRemoteHost() %>
NOTE It should be remembered when using the XML syntax, that the elements are case sensitive.
- Scriptlets: Let you insert arbitrary code into the servlet method:
<%
String name = request.getParameter(“name”);
out.println(“Thank you for logging in: <b>” + name + “</b>”);
%>
The code will be inserted exactly as written, and any static HTML text used before or after the scriplet will be converted to a print statement:
<%
if (existsInDataBase(request.getParameter(“name”))){
%>
Welcome back!
<%
}
else{
%>
Welcome new user!
<%
insertIntoDataBase();
%>
Would be equivalent to the following servlet code:
if (existsInDataBase(request.getParameter(“name”))) {
out.println(“Welcome back!”);
}
else{
out.println(“Welcome new user!”);
insertIntoDataBase();
}
NOTE: Remember that if you want to use the %> characters inside the scriplet you should enter %\> instead.
- Declarations: Let you insert code in the body of the servlet class. They are generally used in association with JSP expressions and scriplets.
<%! Private int accessCount = 0; %>
You accessed the page <%= ++accessCount %> times
Directives
editAllow the control of the overall servlet structure.
There are 2 main types of directives:
- page – allows one to import classes, customise the servlet superclass, etc:
<jsp:directive.page att="val"\>
// or:
<%@file att="val"%>
Several attributes are valid:
- import=”package.class”
- contentType=”MIME-type”
- isThreadSafe=”true|false”
- session=”true|false”
- buffer=”sizekb|none”
- autoflush=”true|false”
- extends=”package.class”
- info=”message”
- errorPage=”url”
- isErrorPage=”true|false”
- language=”java”
- include - lets one insert a file (located on the local file system) into the servlet class at the time the JSP is translated into a servlet.
<jsp:directive.include file="url"\>
// or:
<%@include file="url"%>
Actions
editAllow the specification of existing components that should be used, and/or control the behaviour of the JSP engine.
Actions allow the programmer to dynamically insert a file, reuse JavaBeans components, forward the user to another page, generate HTML for a Java plugin. JSP provides the following actions:
- jsp:include - lets you insert a file at the time the page is requested. This behaviour is different from the include directive which inserts a file at the time the JSP page is translated into a servlet.
For example you can have a site that displays the same menu on all the pages:
<html>
<head>
[...]
</head>
<body>
<jsp:include page="menu.html" flush="true"/>
[...]
</body>
</html>
- jsp:useBean - lets you exploit the re-usability of Java classes. The simplest use of it can be: <jsp:useBean id="name" class="package.class"/>. In other words, this means: instantiate an object of the class specified by the class attribute, and bind it to the variable specified by id.
- jsp:setProperty - used to give values to the properties of the beans. It can be used either outside of a jsp:useBean element, or inside one. In the first case setProperty is executed regardless of whether a new bean was instantiated or an existing one was found. In the second case, setProperty is executed only if a new bean is instantiated. This action has 4 possible attributes:
- name: the bean whose property will be set (required)
- property: the property you want to set. If * is used instead all request parameters whose names match the bean property will be passed to the appropriate setter methods (required)
- value: the value for the property. String values are automatically converted to numbers, boolean, byte, char and their correspondent classes, via the standard valueOf method (optional)
- param: designates the request parameter from which the property should be derived. If the current request has no parameters, nothing is done. In this case the system will not pass null to the setter method of the property. Thus you can let the bean supply default values in the case no request parameters exist.
- jsp:getProperty - used to get the property values from beans. It retrieves the value, converts it to a string, and inserts it into the output. There are 2 required attributes: name and property. They are described exactly as for jsp:setProperty.
- jsp:forward - lets you forward the request to another page. It has a single attribute called page. This attribute should contain a relative URL, which can be either static or computed at request time.
- jsp:plugin - lets you insert the browser specific OBJECT or EMBEDED element.
Exercises
edit- The same exercise as in Laboratory 7 but with JSPs instead of servlets.
Gabriel Iuhasz, 2019-11-25, iuhasz.gabriel@e-uvt.ro