|
Beginner’s Guide to Web Development – HTML and JSP Combined
This part of the tutorial covers using JSP and HTML together on the same page. To start off, let's take a look at the following example
of a JSP page that uses HTML. Type the following in your text editor (If copying this, make sure the quotation marks copy correctly):
<html>
<head>
<title> JSP and HTML Working Together</title>
<style>
.talign{text-align:center}
</style>
</head>
<body>
<table border="10" width="400">
<%
for (int x = 0; x < 10; x++)
{
%>
<tr>
<td width="200" class="talign">A</td>
<td width="200" class="talign">B</td>
</tr>
<%
}
%>
</body>
</html>
Save this file as interact.jsp in the following directory:
C:\tomcat\webapps\examples\jsp\work\
Start up Tomcat if you haven't already done so.
Type the following URL in your browser:
http://localhost:8080/examples/jsp/work/interact.jsp
The above is an example of how JSP can be used to generate HTML. Let’s go over some of the specifics. First of all, look at the HTML code.
We used a style class called "talign" and applied it to the cells of our table. This caused our text to
be aligned in the center of the cells. We could also use "left" or "right" for the text-align value in the class. Take a
look at HTML Tag Reference for more information.
That should be the only piece of the HTML code you have yet to see. Notice the placement of the JSP tags, i.e. <% %>.
The text inside these tags should be JSP code only. Thus, there is no HTML code contained within the tags.
One very important thing to note about the JSP page is that all the code between the loop brackets was executed, not just
the JSP code located within the <% and %> tags. Thus, you can put HTML code inside of your JSP loops - as long as they
are not inside the <% and %> tags but are inside the curly brackets - and the HTML code will execute however many times your loop executes.
This is a powerful concept and used often in JSP programming. This is why you see 10 rows of A’s and B’s.
The ability to generate HTML code based on the logic contained in your JSP tags is a powerful feature of JSP. This is what makes
JSP much more powerful than HTML alone. With just HTML, you would have needed to type the above table row and column data 10 times
for it to display 10 times on the screen. With JSP, you type it once and loop through it.
The above code shows how you can use HTML and JSP together to create a web page. The next step we want to cover is the communication between
JSP pages. In other words, how do we pass information from one page to the next. One way to do this is to use a built in feature of HTML – HTML forms.
Forms are a powerful feature of HTML that we will cover in the next section of this tutorial.
|