Hiển thị các bài đăng có nhãn 02. Java Server Pages. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn 02. Java Server Pages. Hiển thị tất cả bài đăng

Thứ Hai, 25 tháng 2, 2013

33. JSP Quick Guide

What is JavaServer Pages?

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 %>.
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?

JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files.
  • JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • 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, JNDI, 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.
Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.

Setting up JSP Environment

This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately.
You can downloaded SDK from Oracle's Java site: Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat

A number of Web Servers that support JavaServer Pages and Servlets development are available in the market. Some web servers are freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine:
  • Download latest version of Tomcat from http://tomcat.apache.org/.
  • Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
Tomcat can be started by executing the following commands on windows machine:
 %CATALINA_HOME%\bin\startup.bat
 
 or
 
 C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh
 
or
 
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:
Tomcat Home page
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org

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:
JSP Processing

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 %>
You can write XML equivalent of the above syntax as follows:
<jsp:scriptlet>
   code fragment
</jsp:scriptlet>
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("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per environment setup tutorial.
Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat-7.0.2\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:
Hello World

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; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
   code fragment
</jsp:declaration>
Following is the simple example for JSP Comments:
<%! int i = 0; %> 
<%! int a, b, c; %> 
<%! Circle a = new Circle(2.0); %> 

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 %>
You can write XML equivalent of the above syntax as follows:
<jsp:expression>
   expression
</jsp:expression>
Following is the simple example for JSP Expression:
<html> 
<head><title>A Comment Test</title></head> 
<body>
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html> 
This would generate following result:
Today's date: 11-Sep-2010 21:24:25

JSP Comments:

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Following is the simple example for JSP Comments:
<html> 
<head><title>A Comment Test</title></head> 
<body> 
<h2>A Test of Comments</h2> 
<%-- This comment will not be visible in the page source --%> 
</body> 
</html> 
This would generate following result:

A Test of Comments

There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%-- comment --%>A JSP comment. Ignored by the JSP engine.
<!-- comment -->An HTML comment. Ignored by the browser.
<\%Represents static <% literal.
%\>Represents static %> literal.
\'A single quote in an attribute that uses single quotes.
\"A double quote in an attribute that uses double quotes.

JSP Directives:

A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
There are three types of directive tag:
Directive Description
<%@ page ... %>Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>Includes a file during the translation phase.
<%@ taglib ... %>Declares a tag library, containing custom actions, used in the page
We would explain JSP directive in separate chapter JSP - Directives

JSP Actions:

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Purpose
jsp:includeIncludes a file at the time the page is requested
jsp:includeIncludes a file at the time the page is requested
jsp:useBeanFinds or instantiates a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyInserts the property of a JavaBean into the output
jsp:forwardForwards the requester to a new page
jsp:pluginGenerates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements dynamically.
jsp:attributeDefines dynamically defined XML element's attribute.
jsp:bodyDefines dynamically defined XML element's body.
jsp:textUse to write template text in JSP pages and documents.
We would explain JSP actions in separate chapter JSP - Actions

JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects. These variables are:
Objects Description
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.

Control-Flow Statements:

JSP provides full power of Java to be embeded in your web application. You can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc.

Decision-Making Statements:

The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between Scriptlet tags.
<%! int day = 3; %> 
<html> 
<head><title>IF...ELSE Example</title></head> 
<body>
<% if (day == 1 | day == 7) { %>
      <p> Today is weekend</p>
<% } else { %>
      <p> Today is not weekend</p>
<% } %>
</body> 
</html> 
This would produce following result:
Today is not weekend
Now look at the following switch...case block which has been written a bit differentlty using out.println() and inside Scriptletas:
<%! int day = 3; %> 
<html> 
<head><title>SWITCH...CASE Example</title></head> 
<body>
<% 
switch(day) {
case 0:
   out.println("It\'s Sunday.");
   break;
case 1:
   out.println("It\'s Monday.");
   break;
case 2:
   out.println("It\'s Tuesday.");
   break;
case 3:
   out.println("It\'s Wednesday.");
   break;
case 4:
   out.println("It\'s Thursday.");
   break;
case 5:
   out.println("It\'s Friday.");
   break;
default:
   out.println("It's Saturday.");
}
%>
</body> 
</html> 
This would produce following result:
It's Wednesday.

Loop Statements:

You can also use three basic types of looping blocks in Java: for, while,and do.while blocks in your JSP programming.
Let us look at the following for loop example:
<%! int fontSize; %> 
<html> 
<head><title>FOR LOOP Example</title></head> 
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%}%>
</body> 
</html> 
This would produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial
Above example can be written using while loop as follows:
<%! int fontSize; %> 
<html> 
<head><title>WHILE LOOP Example</title></head> 
<body>
<%while ( fontSize <= 3){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%fontSize++;%>
<%}%>
</body> 
</html> 
This would also produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial

JSP Operators:

JSP supports all the logical and arithmatic operators supported by Java. Following table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedenace operators will be evaluated first.
Category  Operator  Associativity 
Postfix  () [] . (dot operator) Left to right 
Unary  ++ - - ! ~ Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   >> >>> <<   Left to right 
Relational   > >= < <=   Left to right 
Equality   == !=  Left to right 
Bitwise AND  Left to right 
Bitwise XOR  Left to right 
Bitwise OR  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 
Comma  Left to right 

JSP Literals:

The JSP expression language defines the following literals:
  • Boolean: true and false
  • Integer: as in Java
  • Floating point: as in Java
  • String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
  • Null: null

32. JSP Internationalization

Before we proceed, let me explain three important terms:
  • Internationalization (i18n): This means enabling a web site to provide different versions of content translated into the visitor's language or nationality.
  • Localization (l10n): This means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.
  • locale: This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example "en_US" represents english locale for US.
There are number of items which should be taken care while building up a global website. This tutorial would not give you complete detail on this but it would give you a good example on how you can offer your web page in different languages to internet community by differentiating their location ie. locale.
A JSP can pickup appropriate version of the site based on the requester's locale and provide appropriate site version according to the local language, culture and requirements. Following is the method of request object which returns Locale object.
java.util.Locale request.getLocale() 

Detecting Locale:

Following are the important locale methods which you can use to detect requester's location, language and of course locale. All the below methods display country name and language name set in requester's browser.
S.N.Method & Description
1String getCountry()
This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format.
2String getDisplayCountry()
This method returns a name for the locale's country that is appropriate for display to the user.
3String getLanguage()
This method returns the language code in lower case for this locale in ISO 639 format.
4String getDisplayLanguage()
This method returns a name for the locale's language that is appropriate for display to the user.
5String getISO3Country()
This method returns a three-letter abbreviation for this locale's country.
6String getISO3Language()
This method returns a three-letter abbreviation for this locale's language.

Example:

This example shows how you display a language and associated country for a request in a JSP:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%
   //Get the client's Locale
   Locale locale = request.getLocale();
   String language = locale.getLanguage();
   String country = locale.getCountry();
%>
<html>
<head>
<title>Detecting Locale</title>
</head>
<body>
<center>
<h1>Detecting Locale</h1>
</center>
<p align="center">
<% 
   out.println("Language : " + language  + "<br />");
   out.println("Country  : " + country   + "<br />");
%>
</p>
</body>
</html>

Languages Setting:

A JSP can output a page written in a Western European language such as English, Spanish, German, French, Italian, Dutch etc. Here it is important to set Content-Language header to display all the characters properly.
Second point is to display all the special characters using HTML entities, For example, "&#241;" represents "ñ", and "&#161;" represents "¡" as follows:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%
    // Set response content type
    response.setContentType("text/html");
    // Set spanish language code.
    response.setHeader("Content-Language", "es");
    String title = "En Español";

%>
<html>
<head>
<title><%  out.print(title); %></title>
</head>
<body>
<center>
<h1><%  out.print(title); %></h1>
</center>
<div align="center">
<p>En Español</p>
<p>¡Hola Mundo!</p>
</div>
</body>
</html>

Locale Specific Dates:

You can use the java.text.DateFormat class and its static getDateTimeInstance( ) method to format date and time specific to locale. Following is the example which shows how to format dates specific to a given locale:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%@ page import="java.text.DateFormat,java.util.Date" %>

<%
    String title = "Locale Specific Dates";
    //Get the client's Locale
    Locale locale = request.getLocale( );
    String date = DateFormat.getDateTimeInstance(
                                  DateFormat.FULL, 
                                  DateFormat.SHORT, 
                                  locale).format(new Date( ));
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>Local Date: <%  out.print(date); %></p>
</div>
</body>
</html>

Locale Specific Currency

You can use the java.txt.NumberFormat class and its static getCurrencyInstance( ) method to format a number, such as a long or double type, in a locale specific curreny. Following is the example which shows how to format currency specific to a given locale:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%@ page import="java.text.NumberFormat,java.util.Date" %>

<%
    String title = "Locale Specific Currency";
    //Get the client's Locale
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
    String formattedCurr = nft.format(1000000);
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>Formatted Currency: <%  out.print(formattedCurr); %></p>
</div>
</body>
</html>

Locale Specific Percentage

You can use the java.txt.NumberFormat class and its static getPercentInstance( ) method to get locale specific percentage. Following is the example which shows how to format percentage specific to a given locale:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%@ page import="java.text.NumberFormat,java.util.Date" %>

<%
    String title = "Locale Specific Percentage";
    //Get the client's Locale
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getPercentInstance(locale);
    String formattedPerc = nft.format(0.51);
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>Formatted Percentage: <%  out.print(formattedPerc); %></p>
</div>
</body>
</html>

31. JSP Security

JavaServer Pages and servlets make several mechanisms available to Web developers to secure applications. Resources are protected declaratively by identifying them in the application deployment descriptor and assigning a role to them.
Several levels of authentication are available, ranging from basic authentication using identifiers and passwords to sophisticated authentication using certificates.

Role Based Authentication:

The authentication mechanism in the servlet specification uses a technique called role-based security. The idea is that rather than restricting resources at the user level, you create roles and restrict the resources by role.
You can define different roles in file tomcat-users.xml, which is located off of Tomcat's home directory in conf. An example of this file is shown below:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="admin" password="secret" roles="admin,manager"/>
</tomcat-users>
This file defines a simple mapping between user name, password, and role. Notice that a given user may have multiple roles, for example, user name="both" is in the "tomcat" role and the "role1" role.
Once you identified and defined different roles, a role-based security restrictions can be placed on different Web Application resources by using the <security-constraint> element in web.xml file available in WEB-INF directory.
Following is a sample entry in web.xml:
<web-app>
...
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>
               SecuredBookSite
            </web-resource-name>
            <url-pattern>/secured/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>
            Let only managers use this app
            </description>
            <role-name>manager</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role>
      <role-name>manager</role-name>
    </security-role>
    <login-config>
      <auth-method>BASIC</auth-method>
    </login-config>
...
</web-app>
Above entries would mean:
  • Any HTTP GET or POST request to a URL matched by /secured/* would be subject to the security restriction.
  • A person with manager role is given access to the secured resources.
  • Last, the login-config element is used to describe the BASIC form of authentication.
Now if you try browsing to any URL including the /security directory, it would display a dialogue box asking for user name and password. If you provide a user "admin" and password "secrer" then only you would have access on URL matched by /secured/* because above we have defined user admin with manager role who is allowed to access this resource.

Form Based Authentication:

When you use the FORM authentication method, you must supply a login form to prompt the user for a username and password. Following is a simple code of login.jsp to create a form for the same purpose:
<html>
<body bgcolor="#ffffff">
   <form method="POST" action="j_security_check">
      <table border="0">
      <tr>
      <td>Login</td>
      <td><input type="text" name="j_username"></td>
      </tr>
      <tr>
      <td>Password</td>
      <td><input type="password" name="j_password"></td>
      </tr>
      </table>
      <input type="submit" value="Login!">
      </center>
   </form>
</body>
</html>
 
Here you have to make sure that the login form must contain form elements named j_username and j_password. The action in the <form> tag must be j_security_check. POST must be used as the form method. Same time you would have to modify <login-config> tag to specify auth-method as FORM:
<web-app>
...
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>
               SecuredBookSite
            </web-resource-name>
            <url-pattern>/secured/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>
            Let only managers use this app
            </description>
            <role-name>manager</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role>
      <role-name>manager</role-name>
    </security-role>
    <login-config>
      <auth-method>FORM</auth-method>
      <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
      </form-login-config>
    </login-config>
...
</web-app>
Now when you try to access any resource with URL /secured/*, it would display above form asking for user id and password. When the container sees the "j_security_check" action, it uses some internal mechanism to authenticate the caller.
If the login succeeds and the caller is authorized to access the secured resource, then the container uses a session-id to identify a login session for the caller from that point on. The container maintains the login session with a cookie containing the session-id. The server sends the cookie back to the client, and as long as the caller presents this cookie with subsequent requests, then the container will know who the caller is.
If the login fails, then the server sends back the page identified by the form-error-page setting
Here j_security_check is the action that applications using form based login have to specify for the login form. In the same form you should also have a text input control called j_username and a password input control called j_password. When you see this it means that the information contained in the form will be submitted to the server, which will check name and password. How this is done is server specific.
Check Standard Realm Implementations to understand how j_security_check works for Tomcat container.

Programmatic Security in a Servlet/JSP:

The HttpServletRequest object provides the following methods, which can be used to mine security information at runtime:
SNMethod and Description
1String getAuthType()
The getAuthType() method returns a String object that represents the name of the authentication scheme used to protect the Servlet.
2boolean isUserInRole(java.lang.String role)
The isUserInRole() method returns a boolean value: true if the user is in the given role or false if they are not.
3String getProtocol()
The getProtocol() method returns a String object representing the protocol that was used to send the request. This value can be checked to determine if a secure protocol was used.
4boolean isSecure()
The isSecure() method returns a boolean value representing if the request was made using HTTPS. A value of true means it was and the connection is secure. A value of false means the request was not.
5Principle getUserPrinciple()
The getUserPrinciple() method returns a java.security.Principle object that contains the name of the current authenticated user.
For example, a JavaServer Page that links to pages for managers, you might have the following code:
<% if (request.isUserInRole("manager")) { %>
<a href="managers/mgrreport.jsp">Manager Report</a>
<a href="managers/personnel.jsp">Personnel Records</a>
<% } %>
By checking the user's role in a JSP or servlet, you can customize the Web page to show the user only the items she can access. If you need the user's name as it was entered in the authentication form, you can call getRemoteUser method in the request object.

30. JSP Debugging

It is always difficult to testing/debugging a JSP and servlets. JSP and Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce.
Here are a few hints and suggestions that may aid you in your debugging.

Using System.out.println():

System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Additionally:
  • Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications.
  • Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial.
Following is the syntax to use System.out.println():
System.out.println("Debugging message");
Following is a simple example of using System.out.print():
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>System.out.println</title></head>
<body>
<c:forEach var="counter" begin="1" end="10" step="1" >
   <c:out value="${counter-5}"/></br>
   <% System.out.println( "counter= " + 
                     pageContext.findAttribute("counter") ); %>
</c:forEach>
</body>
</html>
Now if you will try to access above JSP, it will produce following result at browser:
-4
-3
-2
-1
0
1
2
3
4
5
If you are using Tomcat, you will also find these lines appended to the end of stdout.log in the logs directory.
counter=1
counter=2
counter=3
counter=4
counter=5
counter=6
counter=7
counter=8
counter=9
counter=10
This way you can pring variables and other information into system log which can be analyzed to find out the root cause of the problem or for various other reasons.

Using the JDB Logger:

The J2SE logging framework is designed to provide logging services for any class running in the JVM. So we can make use of this framework to log any information.
Let us re-write above example using JDK logger API:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="java.util.logging.Logger" %>

<html>
<head><title>Logger.info</title></head>
<body>
<% Logger logger=Logger.getLogger(this.getClass().getName());%>

<c:forEach var="counter" begin="1" end="10" step="1" >
   <c:set var="myCount" value="${counter-5}" />
   <c:out value="${myCount}"/></br>
   <% String message = "counter="
                  + pageContext.findAttribute("counter")
                  + " myCount="
                  + pageContext.findAttribute("myCount");
                  logger.info( message );
   %>
</c:forEach>
</body>
</html>
This would generate similar result at the browser and in stdout.log, but you will have additional information in stdout.log. Here we are using info method of the logger because we are logging message just for informational purpose. Here is a snapshot of stdout.log file:
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=1 myCount=-4
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=2 myCount=-3
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=3 myCount=-2
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=4 myCount=-1
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=5 myCount=0
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=6 myCount=1
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=7 myCount=2
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=8 myCount=3
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=9 myCount=4
24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService
INFO: counter=10 myCount=5
Messages can be sent at various levels by using the convenience functions severe(), warning(), info(), config(), fine(), finer(), and finest(). Here finest() method can be used to log finest information and severe() method can be used to log severe information.
You can use Log4J Framework to log messages in different files based on their severity levels and importance.

Debugging Tools:

NetBeans is a free and open-source Java Integrated Development Environment that supports the development of standalone Java applications and Web applications supporting the JSP and servlet specifications and includes a JSP debugger as well.
NetBeans supports the following basic debugging functionalities:
  • Breakpoints
  • Stepping through code
  • Watchpoints
You can refere to NteBeans documentation to understand above debugging functionalities.

Using JDB Debugger:

You can debug JSP and servlets with the same jdb commands you use to debug an applet or an application.
To debug a JSP or servlet, you can debug sun.servlet.http.HttpServer, then watch as HttpServer executing JSP/servlets in response to HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer.
Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for JSP, you have to help your debugger by doing the following:
  • Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes.
  • Set your debugger's classpath so that it can also find your JSP and support classes, typically ROOT\WEB-INF\classes.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever JSP you're interested in debugging, then use a web browser to make a request to the HttpServer for the given JSP (http://localhost:8080/JSPToDebug). You should see execution stop at your breakpoints.

Using Comments:

Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process.
The JSP uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem.

Client and Server Headers:

Sometimes when a JSP doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you're familiar with the structure of HTTP, you can read the request and response and see exactly what exactly is going with those headers.

Important Debugging Tips:

Here is a list of some more debugging tips on JSP debugging:
  • Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu.
  • Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.

29. JSP Exception Handling

When you are writing JSP code, a programmer may leave a coding errors which can occur at any part of the code. You can have following type of errors in your JSP code:
  • Checked exceptions: Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
This tutorial will give you few simple and elegant ways to handle run time exception/error occuring in your JSP code.

Using Exception Object:

The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException) and is only available in error pages. Following is the list of important medthods available in the Throwable class.
SNMethods with Description
1public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3public String toString()
Returns the name of the class concatenated with the result of getMessage()
4public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP container automatically invokes the error page.
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage="xxx" %> directive.
<%@ page errorPage="ShowError.jsp" %>

<html>
<head>
   <title>Error Handling Example</title>
</head>
<body>
<%
   // Throw an exception to invoke the error page
   int x = 1;
   if (x == 1)
   {
      throw new RuntimeException("Error condition!!!");
   }
%>
</body>
</html>
Now you would have to write one Error Handling JSP ShowError.jsp, which is given below. Notice that the error-handling page includes the directive <%@ page isErrorPage="true" %>. This directive causes the JSP compiler to generate the exception instance variable.
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>
Now try to access main.jsp, it should generate something as follows:
java.lang.RuntimeException: Error condition!!!
......

Opps...
Sorry, an error occurred.

Here is the exception stack trace:

Using JSTL tags for Error Page:

You can make use of JSTL tags to write an error page ShowError.jsp. This page has almost same logic which we have used in above example, but it has better structure and it provides more information:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<table width="100%" border="1">
<tr valign="top">
<td width="40%"><b>Error:</b></td>
<td>${pageContext.exception}</td>
</tr>
<tr valign="top">
<td><b>URI:</b></td>
<td>${pageContext.errorData.requestURI}</td>
</tr>
<tr valign="top">
<td><b>Status code:</b></td>
<td>${pageContext.errorData.statusCode}</td>
</tr>
<tr valign="top">
<td><b>Stack trace:</b></td>
<td>
<c:forEach var="trace" 
         items="${pageContext.exception.stackTrace}">
<p>${trace}</p>
</c:forEach>
</td>
</tr>
</table>
</body>
</html>
Now try to access main.jsp, it should generate something as follows:

Opps...

Error: java.lang.RuntimeException: Error condition!!!
URI: /main.jsp
Status code: 500
Stack trace: org.apache.jsp.main_jsp._jspService(main_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
...................

Using Try...Catch Block:

If you want to handle errors with in the same page and want to take some action instead of firing an error page, you can make use of try....catch block.
Following is a simple example which shows how to use try...catch block. Let us put following code in main.jsp:
<html>
<head>
   <title>Try...Catch Example</title>
</head>
<body>
<%
   try{
      int i = 1;
      i = i / 0;
      out.println("The answer is " + i);
   }
   catch (Exception e){
      out.println("An exception occurred: " + e.getMessage());
   }
%>
</body>
</html>
Now try to access main.jsp, it should generate something as follows:
An exception occurred: / by zero