- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
JavaServer Pages, (JSPs)
In this part of the Java EE 5 tutorials, we will work with JavaServer Pages (JSPs).
JavaServer Pages is a technology that enables to create HTML dynamically. JSPs are compiled into servlets by a JSP compiler. A JSP page is a text-based document. It can contain two types of text: static data and JSP elements, which determine how the page constructs dynamic content.
JavaServer pages is an integral part of the Java EE platform. Huge enterprise applications are layered. The JSP pages represent the presentation layer of the application. In the MVC (Model, View, Controller) pattern, this is the View part. The data is processed by the business logic of the application. The model loads the data from the database. The data is sent by the controller to the appropriate JSP page for displaying.
The JavaServer Pages consists of several key features:
- Scripting elements
- Standard directives
- Standard actions
- Tag extensions
JSP pages go through two phases. Translation phase and execution phase. The JSP page is translated once per page. The JSP page is executed once per request. Internally, the JSP page is transformed into servlet, which is then compiled.
The JSP pages have a .jsp extension.
Scripting elements
We have declarations, expressions and scriptlets. Scripting elements are used to manipulate objects and perform calculations. Scripting in done in the Java language. Each of them is put inside specific tags.
<%! declaration %> <% scriptlet %> <%= expression %>
A declaration is used to declare variables and methods in a JSP page. A scriptlet is a piece of Java code. It performs some dynamic action within a JSP page. It can manipulate objects or print some text or HTML data. An expression outputs data, which is displayed in a browser.
Celsius to Fahrenheit
In the following example, we use all three elements. We will convert Celsius temperature to Fahrenheit.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Fahrenheit</title> <style> * { font-size: 12px; font-family: Verdana } </style> </head> <body> <h2>Fahrenheit</h2> <%! double fahr1, fahr2, fahr3; int cels1 = 20; int cels2 = 36; int cels3 = 45; double calculate(int cels) { return cels * 9 / 5.0 + 32; } %> <% fahr1 = calculate(cels1); fahr2 = calculate(cels2); fahr3 = calculate(cels3); %> <p> <%= cels1 %> Celsius is <%= fahr1 %> Fahrenheit<br> <%= cels2 %> Celsius is <%= fahr2 %> Fahrenheit<br> <%= cels3 %> Celsius is <%= fahr3 %> Fahrenheit<br> </p> </body> </html>
<%! double fahr1, fahr2, fahr3; int cels1 = 20; int cels2 = 36; int cels3 = 45; double calculate(int cels) { return cels * 9 / 5.0 + 32; } %>
In this declaration, we declare six variables and one function.
<% fahr1 = calculate(cels1); fahr2 = calculate(cels2); fahr3 = calculate(cels3); %>
In the scriptlet, we perform the computation.
<p> <%= cels1 %> Celsius is <%= fahr1 %> Fahrenheit<br> <%= cels2 %> Celsius is <%= fahr2 %> Fahrenheit<br> <%= cels3 %> Celsius is <%= fahr3 %> Fahrenheit<br> </p>
In the expression, we output the variables.

From JSP to a servlet
Next we will show, how a container transforms a JSP page to a servlet.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <style> * { font-size: 12px; font-family: Verdana } </style> <title>SimpleJSP</title> </head> <body> <%= "Simple JSP page" %> </body> </html>
We will have this simple JSP page. All it does is print some text. We will look, how a container transforms the page into a servlet.
index_jsp.java
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.Vector _jspx_dependants; private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector; public Object getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("X-Powered-By", "JSP/2.1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <style>\n"); out.write(" * { font-size: 12px; font-family: Verdana } \n"); out.write(" </style>\n"); out.write(" <title>SimpleJSP</title>\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write(" \n"); out.write(" "); out.print( "Simple JSP page" ); out.write("\n"); out.write(" \n"); out.write(" </body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
This is the code generated by the Glassfish. Note that different containers will generate different code. To see the servlet code in Netbeans IDE, we run the application first. Then we right click on the JSP page in the Projects window and select option View Servlet.

Directives
Directives are messages to the JSP container. There are three main directives.
- page
- include
- taglib
The page
directive defines several properties for a JSP page.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <style> * { font-size: 12px; font-family: Verdana } </style> <title>Партизанская</title> </head> <body> <h3>По долинам и по взгорьям</h3> <pre> По долинам и по взгорьям Шла дивизия вперед, Чтобы с бою взять Приморье - Белой армии оплот. Наливалися знамена кумачом последних ран, Шли лихие эскадроны Приамурских партизан. Этих лет не смолкнет слава, Не померкнет никогда, Партизанские отряды Занимали города. И останутся как в сказке, Как манящие огни, Штурмовые ночи Спасска, Волочаевские дни. Разгромили атаманов, Разогнали воевод, И на Тихом океане Свой закончили поход. </pre> </body> </html>
The example illustrates the pageEncoding
attribute of the page directive. We display text of a song in russian language.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
The directive sets the encoding to UTF-8. It covers also the russian language. If we would not set this encoding, the JSP page would use the default ISO-8859-1 encoding. The page would not display the text correctly.

The contentType
attribute defines the MIME type. It tells the browser, how to interprete the data. The default contentType is text/html. In this case, the client browser interpretes all the HTML code. The <br> is a new line, <p></p> a paragraph etc.
index.jsp
<%@page contentType="text/plain" pageEncoding="UTF-8"%> <html> <head> <style> * { font-size: 12px; font-family: Verdana } </style> <title>ContentType</title> </head> <body> <b>Plain text content type</b> </body> </html>
If we set the contentType to text/plain, we tell the browser to interprete all textual data as simple text. So the HTML tags are not interpreted and are simply displayed.

Error page
We can use the errorPage
attribute to handle exceptions in the JSP page.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@page errorPage="errorPage.jsp" %> <html> <head> <title>JSP Page</title> </head> <body> <% int num = 77 / 0; %> </body> </html>
An exception occurs in this JSP page. Our exception will raise, when we try to divide by zero.
<%@page errorPage="errorPage.jsp" %>
With the errorPage
attribure, we tell the container to show the errorPage.jsp
if there is some exception.
errorPage.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@page isErrorPage="true" %> <html> <head> <title>Error occured</title> <style> * { font-size: 12px; font-family: Verdana } </style> </head> <body> <h2>Error</h2> <%= exception.getMessage() %> </body> </html>
Here we process the exception.
<%@page isErrorPage="true" %>
With the isErrorPage
attribute, we make the exception
object available to this JSP page.
<%= exception.getMessage() %>
We display the error message.

If we do not provide an error page, we get an error message from the container.

The include
directive enables us to organize the code effectively. All websites have repeating code. An example is the common copyright notice or navigation menu. If the website grows larger, it gets time consuming to correct the code in all files. When the year changes, we should change the copyright notice in all files. This is not possible with simple HTML.
style.css
.left { position: absolute; left:10px; top:55px; width:200px; height:200px; border:1px solid #4B8699; } .center { position: relative; top:1px; margin-left: 210px; margin-right:210px; border:1px solid #4B8699; height:200px; } .right { position: absolute; right:10px; top:55px; width:200px; height:200px; border:1px solid #4B8699; } .banner { border:1px solid #4B8699; height:44px; } .footer { margin-top:3px; border: 1px solid #4B8699; height:35px; text-align:center; padding-top:9px; } * { font-size: 12px; font-family: Verdana }
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Include</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <div class="banner"> </div> <div class="left"> </div> <div class="center"> </div> <div class="right"> </div> <div class="footer"> <%@ include file="WEB-INF/jspf/footer.jspf" %> </div> </body> </html>
We divide our page into five parts. We use include directive to include the copyright notice into the footer.
<%@ include file="WEB-INF/jspf/footer.jspf" %>
Here we include the footer. The included code fragments have a .jspf
ending.
footer.jspf
<%@ page pageEncoding="UTF-8" %> <div><b>ZetCode</b> @ 2007 - 2008 Jan Bodnar</div>
If we use include files, we need to update the text only once.

The taglib
directive defines a tag library and prefix for the custom tags used in the JSP page. We will use this directive later in our Java EE 5 tutorials. When we will work with custom JSP tags.
Deploying a web application
We will deploy our first web application, using the Resin application server.
index.jsp
<html> <head> <title>Date</title> </head> <body> <p> Date: <%= new java.util.Date() %> </p> </body> </html>
The simple JSP file consists of HTML code and Java code. Here we use a JSP expression which will output the current date.
$ ls index.jsp
In our working directory, we have only one file named index.jsp
. And now, we need to deploy it to the server.
Deployment of web applications is similar to installing classical programs on desktop. These are steps needed to run the web application.
In Java EE a web application is called a web module. It is the simplest deployable unit.
$ ./httpd.sh start Resin/3.1.3 started -server ''.
First, we start the Resin server. The httpd.sh
script is located in the bin directory.
$ jar -cvf date.war * added manifest adding: index.jsp(in = 110) (out= 85)(deflated 22%)
We create a web archive.
$ ls date.war index.jsp
We have created a war file.
$ mv date.war /home/vronskij/bin/resin/webapps/
We move the war file to the Resin AS webapps subdirectory. Here you must provide your own path to the directory depending on where you have installed the Resin server. By moving the war file to the webapps directory, the application is deployed and we can test it. Note that it is possible to deploy a web application, while the server is running.
Our JSP file displays current date. We write http://localhost:8080/date/
to our web browser to test the outcome. The localhost:8080
means that we test our application on our local machine and the Resin server listens on 8080 port. The date path is called the context path. It is the context root or path to our application. We can have several applications deployed at one time. The context path can be specified in configuration files. When it is not, than it is equal to the WAR file name.

In this chapter, we have covered Java Server Pages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论