Sie sind auf Seite 1von 13

JSP Overview

JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>. JSP is a specification and not a product. Hence developers can develop variety of applications and add up to performance and quality of software products.It is essential component of J2EE. A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands. Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.

Why Use JSP?


Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself. JSP allows to separate the presentation logic and business logic .JSP are always compiled before it's processed by the server JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, EJB, JAXP etc. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

Problems On Servlets
Servlets need a special "servlet container" to run servlets. Servlets need a Java Runtime Environment on the server to run servlets. For developing Servlet based application, knowledge of java as well as HTML code is necessary.

The servlet has to do various tasks such as acceptance of request, processing of request, handling of business logic and generation of response. Advantages in JSP In JSP we can directly embed java code into html code but in servlet is not possible. JSP page is automatically compiled but servlet will manually redeploy. In jsp implicit objects are presents which is we can implement directly into jsp pages but in servlet there are no implicit objects.

Anatomy Of JSP Page


JSP page is simply a web page which contains JSP elements and Template text. The below figure is a example of JSP page with JSP elements and Template text

Template text can be any text like HTML, WML, XML, or even plain text. When a JSP page request is processed, the template text and dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.

JSP Architecture
The web server needs a JSP engine ie. Container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has

built-in JSP container to support JSP pages development. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Following diagram shows the position of JSP container and JSP files in a Web Application

JSP Processing
The following steps explain how the web server creates the web page using JSP: As with a normal page, your browser sends an HTTP request to the web server. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response. The web server forwards the HTTP response to your browser in terms of static HTML content. Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.

All the above mentioned steps can be shown below in the following diagram:

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster. So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.

JSP Life Cycle


A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. The following are the paths followed by a JSP 1) Compilation 2) Initialization 3) Execution 4) Cleanup The three major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:

1. JSP Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps: 1. Parsing the JSP. 2. Turning the JSP into a servlet. 3. Compiling the servlet. 2. JSP Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method:

public void jspInit() { // Initialization code... }

Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

2. JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:

void _jspService(HttpServletReques request HttpServletResponse response) { // Service handling code... } The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc. 3. JSP Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files. The jspDestroy() method has the following form:

public void jspDestroy() { // Your cleanup code goes here. }

JSP Application Design with MVC


MVC was first described by Xerox in a number of papers published in the late 1980s. The key point of using MVC is to separate logic into three seperate units: the Model, the View, and the Controller. In a server application we can classify the parts of the application as business logic, presentation, and request processing.

Business logic is used for the manipulation of an application's data, such as customer, product, and order information. Presentation refers to how the application data is displayed to the user, for example, position, font, and size. Request processing is what ties the business logic and presentation parts together. In MVC terms, the Model corresponds to business logic and data, the View to the presentation, and the Controller to the request processing. A common example of why presentation should be separated from the business logic is that you may want to present the data in different languages to internal and external users. Access to the data through new types of devices, such as cell phones and personal digital assistants (PDAs) etc. Each client requires its own presentation format. So separating business logic from the presentation which makes easier to evolve an application as the requirements change.Thus new presentation interfaces can be developed without touching the business logic.

Setting up the jsp environment & Installation of JDK Java


Download JDK or JRE from sun website http://java.sun.com/javase/downloads/index.jsp Sun provides different executable file for Windows and Linux operating system version. Sun provide JDK for Linux in .bin or tar.gz format, and for Windows .exe format. After downloading file from sun, install JDK simple double click or through command prompt .

Default installation directory for java in Windows is Program file Java, and Linux /opt. Tomcat 5.5.17 version requires at least java1.5 version. When

When jdk is installed in default location, need to configuration the environment variable

Environment Variable Setting


Environment variable is next to set java home in system environment. This will help to know others application where is java is installed and where java file have to compile. JAVA_HOME variable name needs to set in environment variable as variable name and variable value as the java home directory c:\ jdk1.5.0.Step to do this setting, go to my computer icon and right click and go to properties

My computer->right click->properties->

Advance tab->environment variables ->

User variables > New

Click on new button and new pop up will open. In variable value, enter your java path where java is installed in system.

Tomcat installation and testing tomcat


Tomcat installation is of two types. Apache provides self installer for tomcat installation.This tomcat is in executable binary file. Download,and install, self installer do all work automatically.Second is source code extractor. This tomcat installation is also easy as self installer. Before tomcat installation, check all jvm, java, and environment path set properly. Apache tomcat is freely available from apache jakarta site http://archive.apache.org/dist/tomcat/tomcat-5/ Tomcat is downloaded in form of binaries or source code.We are using zipped pack for windows installation. Download zipped binaries code latest one from this site.Unzip this code and c:\ drive and anywhere desired directory After unzipped directory system will like that

This is means that tomcat is installed properly and ready to run web server. Open bin directory and double click on startup.bat file. Startup.bat will open in dos command prompt

After starting tomcat, check tomcat in web browser by typing localhost:8080 in address bar http://localhost:8080/

This page shows Tomcat is running properly in your system.

JSP Application Development


Java Server Pages (JSP) is a Java API in J2EE which allows dynamic creation of web pages using Java. It has the same purpose as other existing technologies like CGI or PHP. In this unit we will learn about Lifecycle of JSP pages, Dynamic content generation, Invoking Java code using JSP scripting elements, JavaBeans for JSP and Error Handling.The main difference between servlets and JSPs is that servlets are Java classes and JSPs are not (they are embedded in HTML pages

1. JSP Syntax
1.1 The Scriptlet: A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Following is the syntax of Scriptlet: <% code fragment %> Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:

<html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Welcome to JSP); %> </body> </html> 1.2 JSP Declarations: A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Following is the syntax of JSP Declarations:

<%! declaration; [ declaration; ]+ ... %> Following is the simple example for JSP Declarations: <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %> <%! public void jspInit() { }% 1.3 JSP Expression: A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file. The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. Following is the syntax of JSP Expression:

<%= expression %> Example: <body> Todays Date: <% = new java.util.Date() %> </body> Which would generate the following output Todays Date: 07-July-2011 14:45:55

1.4 JSP Directives: A JSP directive affects the overall structure of the servlet class. It usually has the following form: <%@ directive attribute="value" %>

Das könnte Ihnen auch gefallen