Introduction to JSPsJavaServer Pages, commonly known as JSPs, are a simple but powerful technology used to generate dynamic HTML on the server side. They allow Web developers and designers to develop and maintain platform-independent, information-rich, dynamic Web pages that support existing business systems. JSP pages help to achieve the design objective of seperating view and content. The user interface is seperated from content generation, enabling designers to change the overall page layout without altering the underlying dynamic content. JavaServer Pages make use of XML-like tags and scriptlets written in Java to generate dynamic content. The JSP engine receives requests made by a client to a JSP page, then generates responses from the JSP page back to the client. Before going any further, let us consider the most simple 'Hello World' example as written by a servlet.
Hello World Example
Source: hello.jsp Deployment of JSP pages is considerably easier than for servlets - simply copy the SOURCE JSP file to your web content section of your application and then reference the file in the browser as normal. You do not need to precompile the JSP page in any way. So for example, if you wished to put your jsp pages inside a 'myjsps' directory (not required though) then you would copy your .jsp file to your student/myjsps directory and then use the following link:http://localhost/student/myjsps/HelloWorld.jsp. The output from this jsp example can be seen below. Obviously, in this example it would have been easier just to type 'Hello World!' into a plain html file, but we are providing it as an example before we introduce dynamic content, which can not be handled by plain html files.
Figure 5.1. HelloWorld JSP Output
Behind the ScenesA JSP page is executed by a JSP engine, which is installed in a Web Server or Servlet/JSP Container such as Tomcat. In reality, the JSP engine is typically just another servlet that is mapped to the extension *.jsp. The JSP engine receives requests made by a client to a JSP page, then generates responses from the JSP page back to the client. When the server encounters a request for a JSP document, it recognises the *.jsp extension and realizes that special handling is required. The first time the file is requested, it is compiled into a servlet object and stored in memory, and the output is sent back to the requesting client. Storing the compiled servlet in the server cache increases the speed of response to subsequent calls to that page. After the first request, the server checks to see whether the *.jsp file has changed. If it has not changed, the server invokes the previously compiled servlet object. This process is described in the Figure below:
Figure 5.2. JSP Process Diagram If you ran the above example on your own Tomcat deployment, you may have noticed that it takes a short time to respond. This is the time necessary for the server to create and compile the background servlet. Subsequent requests should be as fast as ever because the server can reuse the servlet. The obvious exception to this is the case where the .jsp file changes - the server will notice the change and recompile a new background servlet to reflect the changes. If an error is made to the .jsp file, the server will report the problem, typically within the page returned to the client. For example, if we simply remove the trailing bracket at the end of the out.println() method above, we would see the following output: Figure 5.3. JSP Error Example The JSP Specification is the product of industry-wide collaboration, led by Sun Microsystems. JSP pages share the "Write Once, Run Anywhere"characteristic of Java technology. Like servlets, JSP pages are typically packaged and combined with an XML descriptor file in a Web Application Archive (WAR) file. These WAR applications can be uploaded into a variesty of vendor application servers and accessed by browser-based clients. Considering again our Web Application structure:
Figure 5.4. Web Application Structure JSP files are placed within the same directory level as HTML files, but can naturally be placed in 'other directories', subdirectories of the application root directory. They should not however be placed within the WEB-INF directory, or subdirectories of WEB-INF.
Features of JSP PagesJSP pages make for efficient use of server-side Java. Their development can be shared among various developers while still promoting consistency and standards for development. We list some of the features of JSPs below:
JavaBeansIn the Java Servlets section we introduced JavaBeans for the first time, when we used a User.java bean to represent the entity concept of a user of our system. In general in web development beans are used to store the state and methods for a particular real-world entity. Similar to servlets, we can use JavaBeans from within JSP code. For this example we simply provide a short and extremely simple example of a JavaBean, which we will include using JSP tags. SimpleBean.java
Source: SimpleBean.java Note: This class file should be copied to a subdirectory of your classes directory called mybeans (feel free to rename it, but make sure the package corresponds). This simple bean (literally!) just defines two methods, one which sets the message variable, and the second which returns the message variable. You will notice that in comparison to a typical Java application there is no main method implemented, as this JavaBean is not expected to be directly executed. So in order to utilize this JavaBean, we can use it inside the following JSP.
Source: bean.jsp
Figure 5.5. SimpleBean.jsp Output using SimpleBean JavaBean JSP SyntaxIn this section, we briefly introduce some of the more common syntaxes used in JSPs:Comments
JSP DirectivesJSP Directives are used to define and set attributes that apply to the entire JSP page and the resulting servlet. A directive affects the overall structure of the servlet class. The syntax os a directive is: <%@ directive attr_name=value %> . Multiple attributes can be set as follows:
There are three types of JSP directives:
include DirectiveThe include directive is used to instruct the JSP container to insert text into a JSP page at translation time. The included file can be an HTML file, a JSP file, a text file, or a code file written in the Java programming language. The syntax for an include directive is as follows:
As an example, let us write a JSP which just prints out the current date/time in large text HTML:
Source JSP File: DateTime.jsp
Now we can write a second JSP which "include"s the first:
Source JSP File: JSPInclude.jsp
The output from this second JSP is as follows: Figure 5.6. JSP Include Example Output
page DirectiveA JSP page has attributes that describe its runtime behaviour. The page directive is used to define one of more attributes for the whole JSP page. No matter where the page directive is placed within the JSP file (or included file), it applies to the entire translational unit. There are quite a number of seperate page directive attributes - we will just cover a few of the more popular ones:
import specifies in a comma-seperated list, the Java packages that the JSP file should import.
session="true|false" the session attribute can be set to true if the client must join a session in order to use the JSP page. If the value is false, the session variable isn't available to scripting elements in your page. The default value is true.
contentType defines the MIME type for the response. You can use any MIME type or character sets that are valid for the JSP container. This defaults to text/html.
extends - the fully qualified name of the superclass of the Java class file this JSP file will be compiled to.
language="Scripting Language" - multiple scripting languages may be used in JSP files (assuming supported). The default value is java.
taglib DirectiveThe taglib directive, was not supported in JSP Version 1.0, but was implemented since JSP Version 1.1. The purpose of the taglib directive is to allow JSP authors to define their own tags. The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix. The taglib directive introduces an additional library of tags. We will not be covering the taglib directive in further detail in this module. Scripting ElementsJSP scripting elements allow Java code to be inserted into the servlet that will be generated from the defined JSP page. Script elements can be categorized into three types:
DeclarationsA JSP declaration allows you to define methods or variables that get inserted into the main body of the servlet class. The declared variables and methods have class scope and are available throughout the JSP page. You must declare variables or methods before you use them in your JSP file. Variable declarations and method definitions are embedded within a special set of tags: <%! and %>. The declaration of a variable and defintion of a method can be performed at any point in a JSP page. The syntax for a declaration is as follows:
ScriptletsScriptlets provide the ability to directly insert code into an HTML document. Scriptlets can contain any code that is valid based on the language specified in the language directive. This course will concentrate exclusively on Java code. A scriptlet is a block of Java code embedded in the service() method of the compiled servlet. Thus, the code is executed on every client's request. Any number of scriptlets can appear within a JSP page.The syntax of a JSP scriptlet is listed as follows:
The XML equivalent can also be used:
So this could appear in the following JSP:
Figure 5.7. JSP Scriptlet Output There are four implicit variables automatically available to a JSP file.
It is for this reason, that we are able to use the "request" in the example above, even though it is not defined within the jsp file. Using the "request" (ie. the HttpServletRequest object) we can handle forms simply - consider the following example:
Source JSP File: SimpleForm.jsp If this JSP file were set as the target of a HTML Form (either GET or POST) it would display the values entered in the form. Rather than write a form for this purpose (you should be able to write these forms yourself!) you can test this by simply passing the parameters in the URL. So for example, you might use: http://localhost/student/jsp/SimpleForm.jsp?a=test&b=test2 The output from this request to this jsp would appear as follows: Figure 5.8 - JSP Form Handler Output Excercise: Try writing your own HTML form using the POST method and two fields a and b, and set the target of the form to be the above JSP.
ExpressionsAn expression element contains an expression that is valid in the scripting language used in the JSP page. They are like single-line scriptlets - you can think of an expression as a tag that will be replaced by the value of the evaluated expression. This is a shortcut notation for inserting values directly into the output. The value is evaluated, converted to a string, and inserted where the expression appears in your JSP file. The syntax for an expression is:
|
Course Content >