Java - JavaServer Pages (JSP)

> Procedural Languages > Java

1 - About

JavaServer Pages technology lets you put:

directly into a text-based document.

A JSP page is a text-based document that contains two types of text:

  • static template data, which can be expressed in any text-based format such as HTML, WML, and XML,
  • and JSP elements, which determine how the page constructs dynamic content.

The jsp extension notifies the Web server that the page should be processed by a JSP container. The JSP container interprets the JSP tags and scriptlets, generates the content required, and sends the results back to the client as an HTML or XML page.

JSP technology is considered to be a deprecated presentation technology for JavaServer Faces.

Jsp files are converted into Java files at runtime, just before they are compiled by javac.

Advertising

3 - Element

Jsp Element:

3.1 - Tags

JSP tags are used for tasks such as

  • initializing Java classes, JavaBean
  • forwarding the user to either the same or another page in the application.

Example:

  • jsp:useBean. It identifies and initializes the class that holds the methods that run in the page.
  • jsp:forward. This tag is used to forward the user to a specified page.

3.2 - Scriptlets

Scriptlets are used to run the Java methods that operate on the database and to perform other processing in JSP pages.

You use scriplets for a variety of tasks.

For example:

  • to call a method that returns a ResultSet object and use it to display that data.
  • to iterate through a same ResultSet object and display each item in a row of a table.
Advertising

4 - Example

<jsp:useBean id="empsbean" class="hr.DataHandler" scope="session"/>
 
 
<%
ResultSet rset;
String query = request.getParameter("query");
if (query != null && query != null) {
    rset = empsbean.getEmployeesByName(query);
} else {
    rset = empsbean.getAllEmployees();
}
%>
<table cellspacing="2" cellpadding="3" border="1" width="100%">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Job</th>
        <th>Phone</th>
        <th>Salary</th>
    </tr>
 
<%
while (rset.next ())
{
out.println("<tr>");
out.println("<td>" + 
rset.getString("first_name") + "</td><td> " + 
rset.getString("last_name") + "</td><td> " + 
rset.getString("email") + "</td><td> " + 
rset.getString("job_id") + "</td><td>" + 
rset.getString("phone_number") + "</td><td>" + 
rset.getDouble("salary") + "</td><td> <a href=\"edit.jsp?empid=" 
+ rset.getInt(1) + "\">Edit</a></td>");
out.println("</tr>");
}
 
empsbean.closeAll();
%>
</table>

5 - Documentation / Reference

lang/java/jsp.txt · Last modified: 2017/05/24 20:37 by gerardnico