A JSP to Replace fruitServlet.java
An inside-out servlet that look like HTML files
A JSP script may be described as an inside-out servlet. While servlets are programs that contain lines of code that output HTML onto the browser, JSPs look like HTML files with embedded Java code. The web server uses the .jsp extension to recognize a JSP file. The file is compiled, all the embedded commands are executed, and the result is sent to the web browser.
The embedded Java commands are enclosed between <% and %> tags. JSPs are stored in the main directory of the application and not the classes subfolder. They remain as text files that are compiled upon invocation. JSPs have a unique syntax. The showFruits.jsp file replicates the functions of the fruitServlet class. Save this file in the <Tomcat 5.5 Program Directory>\webapps\ShowFruits\ directory and open the following URL: http://localhost:8080/ShowFruits/showFruits.jsp in the Internet Browser. You will see output identical to that of the showFruits servlet. Open the file using NetBeans and take a look at it.
<%@page import="java.sql.SQLException"%> <%@page import="java.sql.Statement"%> <%@page import="java.sql.Connection"%> <%@page import="java.sql.DriverManager"%> <%@page import="java.sql.ResultSet"%>
The 'page import' syntax is used to import packages into a JSP file. The HTTP oriented classes are already available to the JSP. Note that all commands are enclosed between <% and %> tags. The following lines achieve the same result as the 'out.println' lines in the fruitServlet class. Note the directive <%= someVariable%>. This is a convenient shorthand (equivalent to out.println(someVariable) to specify that the specified variable should be substituted within the markup at the given point.
<% while (rs.next())
{ %>
<tr>
<td><%= String.valueOf(rs.getInt("id"))%></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("color") %></td>
<td><img alt="Fruit Image"
src='images/<%= rs.getString("image") %>'></td>
<td><%= String.valueOf(rs.getInt("calories")) %></td>
</tr>
<%
}
%>
Exercise: Use the showFruits.jsp file and the showFruits servlet Java code to create JSP replicas of the showFruitInfo and ShowFruitServlet classes.