| ★ wanayoo — archive 1999 http://java.oreilly.com/bite-size/java_0100.html | Nouvelle recherche | Portail wanayoo |
|
|||||
|
|
Java Server Pages (JSP) is a curious amalgam of HTML and Java. You can embed Java code directly in an HTML page. Why would you want to do this? The primary motivation for JSP comes from the world of Java Servlets, which I talked about last month. Servlets are great for dynamically generating web pages. Most people's web pages, however, remain largely the same, with only small pieces that change. Servlets are usually only needed to generate a small, dynamic part of a large, static page. While this can be done using Servlets and Server-Side Includes, JSP is a more powerful and more convenient solution. One of the reasons servlet programming can be tricky is that you have to write code in two different places: the servlet itself, and the HTML page. With JSP, you can actually combine HTML and Java. We'll work through some examples so you can see how this works. Start SimpleOur first example prints out the type of browser that connects to it. This information is part of the request that the browser sends to its server. Here's the source code for the servlet:
<HTML> As you can see, this file is a combination of HTML and Java. The Java parts are surrounded by the special tags <% and %>. Save the file as BrowserSnoop.jsp. All it does is find out the browser name by querying the User-Agent field of the request header. Although we haven't declared the request variable anywhere, it is automatically available to us and represents the browser's query to the server. You've just written your first JSP. Now let's see how to deploy and run it. Deploying the JSPDeploying the JSP is as easy as dropping in the right subdirectory of your web server. This directory depends on your server and your server configuration, so you'll have to check the documentation to find out the proper place. For this column, I used Sun's JavaServer Web Development Kit (JSWDK). To deploy the JSP, place it in the examples/jsp subdirectory underneath the JSWDK base directory.
To run the example, point your browser at the server and indicate the
path to the JSP. On my machine, I use the loopback IP address in the
following URL: http://127.0.0.1:8080/examples/jsp/BrowserSnoop.jsp.
The server chugs away for a little while and spits back an answer:
Behind the scenes, here's what happens the first time you request a JSP:
A Side Note: the Convergence of Apache and JavaActually, the JSWDK is not the definitive platform for developing JSPs. The official reference platform for servlets and JSPs is called Tomcat, part of the Jakarta Project. Basically, it's an implementation for servlets and JSPs running under the Apache web server. If you want the official reference platform, and especially if you're already running Apache, you should consider using this platform for development.Stuff for FreeLet's get back to JSPs. Four variables are automatically available to your Java code in a JSP:request This variable is an instance of HttpServletRequest. It contains all the information passed from the browser to the server, including header fields and parameters.response Use this variable to control the response that's sent to the browser. It's an instance of HttpServletResponse.in This variable is the input stream from the browser, a BufferedReader.out Use this variable to send results back to the browser. It's a PrintWriter.In the BrowserSnoop example, we used request to find the browser type and out to print it back to the user. ExpressionsInstead of explicitly using out, we could have used something called a JSP expression instead. Here's what it looks like:
<HTML> Save this JSP as BrowserSnoopExpression.jsp; deploy and run it as before. It should do exactly the same thing as BrowserSnoop.jsp. All we've really done is clean up the syntax a little. As you might guess, an expression is simply some Java expression that evaluates to a string. Anything inside the <%= and %> tags is evaluated and sent back to the browser. Importing PackagesLet's write a slightly more complicated JSP, something that displays the current date and time. This involves the java.text.DateFormat class and the java.util.Date class. In a Java application, you'd probably just import the java.text and java.util packages. In a JSP, it's a little different:
<%@ page import = "java.text.*, java.util.*" %>
We've used something called a directive to import the packages we
need. The first line of this example shows how it works. The rest of the
JSP should be familiar; we just use a DateFormat to print the
current time. The dynamically generated part of the page is shown in red.
Save, deploy, and run this example; you should see something like this:
As you've probably realized, this is pretty neat stuff. It's syntactically cleaner than writing a servlet, and it's easier to edit one JSP file than using multiple source files for server-side includes. Let's jazz up the date example to interpret a parameter:
<%@ page import = "java.text.*, java.util.*" %>
String country = request.getParameter("country");
Locale locale = null;
DateFormat df = DateFormat.getDateTimeInstance(
%> This JSP examines the "country" parameter and adjust the date display accordingly. For example, using this URL: http://127.0.0.1:8080/examples/jsp/InternationalDate.jsp?country=italygave me these results:
BeansWe've really only had a snack here; JSP technology offers a lot more too. For complicated pages, you can modularize things by using a JavaBean. That is, instead of keeping all your Java code in the JSP, you can move some of it into a JavaBean and reference the Bean from the JSP.Let's see how this works with a tiny example. First, here's a JavaBean called simple.SimpleBean:
package simple;
public class SimpleBean { You'll need to place it in a special location in your web server's hierarchy. For the JWSDK, I saved this file as examples/Web-inf/jsp/beans/simple/SimpleBean.java. Remember to compile the Bean; after all, it's the .class file that matters, not the .java source code. Now let's write a JSP that uses this Bean. All you really need to do is tell the JSP what class you want to use and what variable name you want.
<HTML>
When you deploy and run this example, you should see the following page:
If SimpleBean is in the wrong directory, or if anything else goes wrong, you'll see an error message in your browser window, usually 500 or above. Check the server console for details. SummaryBy now you should have a good idea how to write and deploy a JSP. JSPs are an interesting blend of HTML and Java; if you're proficient in both languages you can quickly build a front end for an enterprise application. Using the power of the Java APIs, you can easily connect to Enterprise JavaBeans, SQL databases (via JDBC), CORBA objects, or almost anything else, right from inside an HTML page.For more information, see Sun's JSP page. Download the source code.
Jonathan Knudsen is an author and developer at O'Reilly & Associates. He is the author of Java Cryptography, Java 2D Graphics, and LEGO® MINDSTORMS Robots.
O'Reilly Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts International | About O'Reilly | Affiliated Companies © 1999, O'Reilly & Associates, Inc. |
||||