Lets make the page a little more interesting by adding some dynamic content.  First copy the contents of hello.html to a new file called hello.jsp.

.jsp is the extention for Java Server Pages. These are pages with dynamic content.

Now add the following code :

<html>

<head>

</head>

<body>

<%

String name = “Michael”;

%>

<h3>Hello <%=  name %></h3>

</body>

</html>

Request this page with a URL like:

http://localhost/my_webapp/hello.jsp

You should see a page like:

tc5

If however you see a page like:

tc6

Then the JSP page has failed to compile and you will have to adjust it to fix the errors.

The tags <% %> and  <%= %> and <%! %> are what is called scriptlets. They give us the ability to run java code within a jsp file.

The tags <% and %> allow you to insert java code into the page that will be run as the page is written out.

Eg once tomcat has written out the <body> opening tag it will run the java code

String name = “Michael”;

Then it will continue to write the next part of the page.

The tags <%= and %> effectively write out what is contained within them.  In this case we are writing out the variable name.

<h3>Hello <%=  name %></h3>

will write out:

<h3>Hello Michael</h3>

The final scriptlet tags <%! %> allow us to include member fields and methods in the page. Eg. We could have written the previous page as

<html>

<head>

</head>

<body>

<h3>Hello <%= getName() %></h3>

</body>

</html>

<%!

private String getName()

{

return “michael”;

}

%>

Have a go at using these tags.

See if you can write a page that outputs the current time.

If you want to be adventurous you can put input fields on your page and then read in what the user entered in those fields. Eg.

<html>

<head>

</head>

<body>

<%

String username = request.getParameter(“username”);

if(username != null)

{

%>

<h3>Hello <%= username %></h3>

<%

}

else

{

%>

<form>

<input type=”text” name=”username”/>

<input type=”submit” />

</form>

<%

}

%>

</body>

</html>

See what else you can make.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s