18.1 Using JavaServer Pages

Java Servlet Programming, 2nd Edition > 18. JavaServer Pages > 18.1 Using JavaServer Pages

 
< BACKCONTINUE >

18.1 Using JavaServer Pages

At its most basic, JSP allows for the direct insertion of servlet code into an otherwise static HTML file.[1]

[1] Before we start, it's worth pointing out that putting Java code within a JSP page is considered by many to be poor style. We cover more advanced uses of JSP later that are commonly considered better style.

Each block of servlet code (called a scriptlet ) is surrounded by a leading <% tag and a closing %> tag. For convenience, a scriptlet can use a number of predefined variables. The six most frequently used variables are:

HttpServletRequest request

The servlet request.

HttpServletResponse response

The servlet response.

javax.servlet.jsp.JspWriter out

The output writer, used like a PrintWriter but it has different buffering characteristics.

HttpSession session

The user's session.

ServletContext application

The web application.

javax.servlet.jsp.PageContext pageContext

An object primarily used to abstract the implementation of the server but sometimes used directly to share variables between JSP pages and supporting beans and tags.

You'll notice that core JSP classes reside under the javax.servlet.jsp package.

Example 18-1 shows a simple JSP page that says a personalized "Hello" using the predefined request and out variables. If you have a server that supports Java-Server Pages and want to test this page, you should place the file under the server's document root and save it with a .jsp extension. Assuming you have saved the page as hello1.jsp, you can then access it at the URL http://server:port/hello1.jsp, or if you put the file in a context path of jsp, then the URL would be http://server:port/jsp/hello1.jsp.

Example 18-1. Saying "Hello" with JSP
<HTML> <HEAD><TITLE>Hello</TITLE></HEAD> <BODY> <H1> <% if (request.getParameter("name") == null) {    out.println("Hello World"); } else {   out.println("Hello, " + request.getParameter("name")); } %> </H1> </BODY></HTML>

A screen shot is shown in Figure 18-1.

Figure 18-1. Saying Hello using JavaServer Pages


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net