Tutorial: Get started with JSP (Page 2 of 2)

Article by SemTeK (238 pts ) , published Nov 17, 2008

What just happened?

Okay, in the first example I showed you this code:

<%= "Hello, World" %>

Whenever you see <% [some code] %>, you'll know it's JSP or Java code and so does the application server. What happened in the example was a little different. Because we just wanted to show some text, we added = to the JSP code start. This is a shorthand version of the following:

<% out.print("Hello, World"); %>

This does the exact same thing. "out" is a variable that represents your output stream to the web browser and "print" is one of its many methods. This is in fact, ordinary Java code. Between <% and %> you can place any Java code you like. Let me show you another example:

<%

Integer x = 0;

Integer y = 0;

for (int i = 0; i < 10; i++) {

x = x + 1;

y = y + x;

out.print(y);

}

%>

You see, ordinary Java code, this example prints a bunch of numbers ("135812172330384757" in fact). The point is that inside my JSP file, anything that is between <% and %> is Java, the rest is HTML.

Beyond your first step

If you already know Java, you know that you can use a lot of libraries with existing code. Because JSP is really just Java, all these libraries can be used. I'll give you a small example:

<%= new Date() %>

This uses the Date object in the java.util package (package is just the word Java uses for libraries). If I try to run this, it will fail and an error message will show up in my browser. That's because I have to tell my application server to import the java.util package. This is done by placing the following line in the top of the JSP file:

<%@ page import="java.util.*" %>

This is what is known as a page directive, it tells the application server to do something for this page. In this case, import the java.util package. You can recognize a page directive by the @ sign.

Conclusion

Now you know the absolute basics of JSP, you can agree that it really isn't very difficult to get into. However, because you can use the entire Java language, it's extremely powerful. If, at this point you were to brush up your knowledge of Java, you'll be able to build really nice web applications.

But believe me when I say these are just the absolute basics of JSP. The language has much more to offer and when used correctly, you can use JSP to build the most complex and powerful applications.

 
Subscribe to Web Development
RSS
Get free weekly updates, directly to your inbox.
Browse Web Development