ARTICLE
  Home> Articles > >
 
 
 


 
 
Spring is compared to EJB 3.0  
 

EJB3.0 improvements:

• Continue Standard approach to application server vendor independence (open source and commercial)
• Test Entity Beans outside the container.
• Backwards compatibility with EJB 2.0 components
• EJB remote and home interfaces are no longer required so even Entity beans can be simple POJO (Plain Old Java Bean) Interfaces.
• Standardised Object Relational mapping
• EJB 3.0 now supports the Dependency Injection Design Pattern
• Annotations are used as an alternative to deployment descriptors.

 
 
Beans scopes in JSP  
 

JavaBeans are reusable components. It represents a simple Java class with some properties. The bean properties are accessed by Getter and Setter method. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class. The JSP specification provides three basic tags for working with Beans :-

jsp:useBean id="bean name" class="bean class" scope = "page | request | session |application "/>

  • <jsp:setProperty name = "bean name" property = "someProperty" value = "someValue" />
  • <jsp:getProperty name = "bean name" property = "someProperty" />

Where bean name = the name that refers to the bean.
Bean class = name of the java class that defines the bean.
property = name of the property to be passed to the bean.
value = value of that particular property.

The following is the explanation for the different scopes of a bean object in jsp:

  1. Page scope:- This scope helps to keep the data available while the page is loading. Any object whose scope is defined as page scope will disappear as soon as the response is sent to the browser. The object with a page scope may be modified as often as desired within the particular page but the changes are lost as soon as the user moves away from the page. By default all beans have page scope.
  2. Request scope:- Any object created in the request scope will be available as long as the request object is valid. For example if the JSP page uses a <jsp:forward> tag, then the bean will be accessed in the forwarded page and if redirect is used then the bean is destroyed.
  3. The Session scope:- In JSP terms, the data associated with the user has session scope. A session does not correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site. Typically, this period is defined as all the hits a user makes to a website between starting and exiting his browser.
  4. Application Scope:- The bean associated with the application scope will be accessible to all the users and all the pages in the application.

     

 
 
JSP Bean scope examples  
 

The following example will demonstrate the various bean scopes for the JSP application. All the examples will use the Counter bean which has only one property counter of type int .

(1) Page Scope

Note:- This is the default scope for the bean object. So in the following JSP example "bean1" is accessed only in this page and not anywhere else.


<HTML>
<BODY>
<H1>
Using Beans and Page Scope
</H1>
<jsp:useBean
id="bean1" class="com.visualbuilder.Counter" scope="page
" />
    <%
bean1.setCounter(bean1.getCounter() + 1);
%>
    The counter value is: <jsp:getProperty name="bean1" property="counter
" />
</BODY>
</HTML>

(1) Request Scope

index.jsp

<jsp:useBean id="counter" scope="request" class="com.visualbuilder.Counter" />
<html>
<head>
  <title>
Request Bean Example
</title>
</head>
<body>
<%
   
counter.setCounter(10
);
%>
<jsp:forward
page="request.jsp
" />
</body>
</html>

request.jsp

<jsp:useBean id="counter" scope="request" class="com.visualbuilder.Counter
" />

<html>
<body>
  <H3>
Request Bean Example
</H3>
  <center><b>
The current count for the counter bean is:
</b>
  <%=
counter.getCounter
() %></center>
</body>
</html>

(3) Session Scope

Example for Session Scope.

<HTML>
<BODY>
  <jsp:useBean
id="bean1" class="com.visualbuilder.Counter" scope="session" />
  <%bean1.
setCounter(bean1.getCounter() + 1
);%>
  The counter value is:

  <jsp:getProperty
name="bean1" property="counter" />
</BODY>
</HTML>


(3) Application Scope

<jsp:useBean id="counter" scope="application" class="com.visualbuilder.Counter" />

<html>
<body>
<center>
&nbsp;&nbsp;<b>
The current count for the counter bean is: </b> <%=counter.getCounter()
%>
</center>
</body>
</html>

 

 
 
Uploading Application in JSP.  
 

The request object is used to send the raw data in form of key/value pair to the server from the browser. What if, we want to send the multipart data i.e. images, files and binary data to the server. The below example will demonstrate the multiple type data send to the server.

<%@ page import="java.io.*"%>
<%

    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                DataInputStream in = new DataInputStream(request.getInputStream());
                int formDataLength = request.getContentLength();

                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
              while (totalBytesRead < formDataLength) {
                  byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                     totalBytesRead += byteRead;
                }
                String file = new String(dataBytes);
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
              saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
              saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1,contentType.length());
                int pos;
             pos = file.indexOf("filename=\"");
             pos = file.indexOf("\n", pos) + 1;
             pos = file.indexOf("\n", pos) + 1;
             pos = file.indexOf("\n", pos) + 1;
               int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
                String filepath=session.getServletContext().getRealPath("/")+saveFile;
                FileOutputStream fileOut = new FileOutputStream(filepath);
    
            fileOut.write(dataBytes, startPos, (endPos - startPos));
            fileOut.flush();
            fileOut.close();
            out.println("File saved as " +saveFile);
    }
%>

<!-- Starts Here -->
<form method="post" ACTION="upload.jsp" name="uploadForm" ENCTYPE='multipart/form-data'>
<input type="file" name="uploadfile" />
<p>
    <input
type="submit" name="Submit" value="Submit">
    <input type="reset" name="Reset" value="Reset">
    <input type="hidden" name="action" value="upload">
</p>
</form>

<!-- Ends Here -->

Output:-

 
 
Modularization in JSP  
 

These days, users expect feature rich online applications and companies need flexible application design to deal with complex business rules. The day of having a single code file with all the application are gone. Modularization is the splitting up of complex code into separate modules of code. The following are the advantages of the modularization:-

  1. Coding and debugging both are very easy as compared to single file.
  2. The code is reused if required in the multiple pages.
  3. If any logic becomes obsolete then it can be replaced without disturbing other components in the application. The following tags are used to add the multiple JSP pages into one:-
    a. <jsp:include>:- The <jsp:include> includes the given file on runtime. When container encounters this tag, it checks for the JSP file and compile that given JSP file. The output is then included in the page at runtime. As a result response time increases to some extent. It is always better to use <jsp:include> when the JSP page content are dynamically changes and the restarts of the servers are not done periodically.
    b. <%@include%>:- This tag includes the contents of the given file during the compilation of the JSP file. When the container encounter this tag it will generate the servlet and include all the contents of the included file to the servlet. Now if we change the included file then it would not reflect to its parent page until or unless it is reloaded to the container or the server gets a restart. So it is always better to use <%@include%> for the static type of the pages.

Example:-

The below is given the use of the <jsp:include> and also the <%@include%> tag.

<jsp:include page="coretaglib1.jsp"/><br>
<%@include file="coretaglib2.jsp"%>

Output

 
 
Exception Handling in JSP-1  
 

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. There are two ways to handle the exceptions in the JSP world. First- is the conventional try/catch/finally block in the scriptlet. In this way you have to handle the flow of the program.

The following example will demonstrate the conventional way of error handling.

Example:-

<%
try{
    String str="11a";
    int i = Integer.parseInt(str);
    }catch(Exception e){
        out.println("Error Occured");
    }
%>


Output:-

The above example will print the "Error occurred" as output. The page is throwing a NumberFormatException while converting string to integer. As a result, the control is transferred to the catch block of the program.

 

 
 
Exception Handling in JSP-2  
 

The second way is to define the error page in the page directive as "<%@ page errorPage="errorpage.jsp" %>" and creating the error page. When any exception or error occurs while processing the JSP page then the container automatically calls the error page and redirects the flow to it. Any page can be used to show the errors.Users have to set the ErrorPage="true" property on the page directive for example:-<%@ page isErrorPage="true" %> for error pages. While processing an error page an implicit object named "exception" automatically created  for the page, which is used to display the error messages.

The below example will demonstrate the exception handling in the JSP and use of exception implicit object.

Exceptionhandling.jsp

<%@ page errorPage="errorpage.jsp" %>
<% 

String s=null;
s.toString();

%>

errorpage.jsp

<%@ page isErrorPage="true" %>

This is the Error page.The following error occurs:- <br>
<%=
exception.
toString() %>

Output:-

 
 
Session Tracking in JSP  
 

In any web application, a user moves from one page to another. So, it is necessary to track the user's data and objects throughout the application. As we know that the session keeps the data particular to a user, so sessions are used to hold the user's data. For sessions JSP provide an implicit object "session", which can be use to save the data specific to the particular user into the session scope.

There are mainly 4 ways for session Tracking as follows:

1. Cookies:-
You can use HTTP cookies to store information about a session. The cookies are small text files stored in the client side. This is an excellent most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled, while working with cookies.

2. URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do.


3. Hidden form fields:
HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

4. Using session object in the JSP.

The implicit object represents the session. The information can be stored in the session for the current session by setAttribute() and then retrieve by getAttribute() method, whenever needed. The session objects stores at the server so it is advisable not to put heavy information in the session object.

To understand a session let us take a very simple example of getting the name from the user and saving it in the session, we will retrieve this name from session on next page and display on the page. For this, we will need 2 JSP pages.

 

Example:- 

 

Sessiontracking1.jsp


<% String action= request.getParameter("action");
if(action != null && action.equals("submit")){
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    if(username != null && password != null && username.equals("visualbuilder") && password.equals("test"))
    {    
        session.setAttribute("username",username);
        response.sendRedirect("sessiontracking2.jsp");
    }else{
        out.println("<h3>Wrong password!!!!</h3>");
    }
    }else{
%>

<html>
<form
action="sessiontracking1.jsp" method="post
">
<input
type="hidden" name="action" value="submit
">
   
Enter the user name :- <input type="text" name="username
" ><br>
   
Enter the password :- <input type="password" name="password
" ><br>
    <input
type="submit" name="submit" value="submit
">
</form>
</html>

<%}%>

 

Sessiontracking2.jsp

    <h3>Welcome <%= session.getAttribute("username")%> To the Site</h3>

 

Output:-

 
 
Security in JSP -1  
 

Security is defined as the condition of being protected against danger or loss. The security is very important in any web application as the web applications are mostly exposed to all the people in the world. The levels of security can be

  • Transport Level security using HTTPS.
  • Authentication and Authorization
  • Role Based Access Control
  • Container-managed Security
  • Application-managed Security.

The web application can be configured to use any level of security as per the requirement and criticality of the site.

Application Managed Vs Container Managed Security

Container Managed
Application Managed
  • Authentication and Authorization are specified in web.xml.
  • It uses multiple authentication schemes, such as Password Authentication Form-based Authentication Client side Digital Certificates etc..
  • Redirects are handled automatically.
  • User data can be provided by a variety of stores xml file or flat files. In tomcat the Data is provided in TOMCAT_HOME/conf/tomcat-users.xml
  • Using the Username and Password forms..
  • Cookies
  • Using Servlet Filters.
  • Using SSLEXT with Struts to enable HTTPS.

The following is the Example to implement the Container Specific Security in Tomcat.

(1) tomcat-user.xml File

<?xml version =' 1.0 ' encoding =' utf-8 '?>
<tomcat-users>
     <role
rolename =" tomcat
"/>
     <role rolename ="
role1
"/>
     <role rolename ="
admin
"/>
     <user
username =" tomcat " password =" tomcat" roles =" tomcat
"/>
     <user username ="
both " password =" tomcat" roles =" tomcat,role1
"/>
     <user username ="
role1 " password =" tomcat" roles =" role1
"/>
     <user username ="
visualbuilder " password =" test " roles =" admin
"/>
</tomcat-users>

(2) Web.xml file

<?xml version =" 1.0 " encoding =" UTF-8 "?>
<web-app version =" 2.4 " xmlns =" http://java.sun.com/xml/ns/j2ee " xmlns:xsi =" http://www.w3.org/2001/XMLSchema-instance " xsi:schemaLocation =" http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
<security-constraint>
     <web-resource-collection>
         <web-resource-name>
application
</web-resource-name>
         <url-pattern>
/security.jsp
</url-pattern>
     </web-resource-collection>
     <auth-constraint>
         <role-name>
admin
</role-name>
     </auth-constraint>
</security-constraint>
<login-config>
     <auth-method>
BASIC
</auth-method>
     <realm-name>
securityapp
</realm-name>
</login-config>
<security-role>
     <description>
Testing the Application Security
</description>
     <role-name>
admin
</role-name>
</security-role>
</web-app>

Output:-

The following screen appears when you try to run the application. It will ask for username and password and once you enter "visualbuilder" as username and "test" as password then only it will display the pages of the application.

 
 
Security in JSP -2  
 

The user can also use the html forms to accept the username and password. This helps to establish the application level or module level security in web world. All sites follow the different security policies and standards. It is always better to use the application managed security for better results. Also, when the application is moved to some other servers then it hardly impacts the application managed security. The following example will demonstrate a form and shows the welcome message if user enters the correct username and password.

Example:-

<% String action= request.getParameter("action");
if(action != null && action.equals("submit")){
    String username=request.getParameter("username");
    String password=request.getParameter("password");
if(username != null && password != null && username.equals("visualbuilder") && password.equals("test"))
{
  out.println("<h3>welcome to the page</h3>");
}else{
  out.println("<h3>Wrong password!!!!</h3>");
}
}else{
%>

<html>
<form
action="formsecurity.jsp" method="post">
  <input type="hidden" name="action" value="submit">
  Enter the user name :- <input type="text" name="username" ><br>
  Enter the password :- <input type="password" name="password" ><br>
  <input type="submit" name="submit" value="submit">
</form>
</html>
<%
}%>

Output:-

 
 
Internationalization in JSP application  
 

Few years back, the sites were developed using a single language and the developer used to create the sites to their specific languages. As the globalization occured, many frameworks have developed to support the multiple languages at a time. Now this can be achieved by having the multi language text in key/value pair and at runtime the text is read from the key as per the language required. This multilingual support is known as Internationalization. Internationalization is defined as the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

The following classes are used to implement Internationalization to any site.

  • Locale - The fundamental Java class that supports internationalization is Locale . Each Locale represents a particular choice of country and language, and also a set of formatting assumptions for things like numbers and dates.
  • ResourceBundle - The java.util.ResourceBundle class provides the fundamental tools for supporting messages in multiple languages.
  • PropertyResourceBundle - One of the standard implementations of Resource Bundle allows you to define resources using the same "name=value" syntax used to initialize properties files. This is very convenient for preparing resource bundles with messages that are used in a web application, because these messages are generally text oriented.

Note:- The fmt is the jstl tag library used to implement the internationalization in JSP. The below example will tell you "how to use the fmt taglib in the application". The example displays the text coming from the different properties files. The properties file lables.properties is created with different locale suffix example en is for english, de for Germany etc. We have hello key in both the files. hello=This is german File in de file and hello=This is english File in english file.

Example JSP file Internationalization.jsp file .

<%@ taglib prefix="fmt" uri="/WEB-INF/fmt.tld"%>
<fmt:setLocale
value="de" scope="session
"/>
<fmt:bundle
basename="com.visualbuilder.labels
">
    <fmt:message>
    hello

    </fmt:message>
</fmt:bundle>

Output:-

The file will display "This is german File" and if the locale is changed to en then it will display the "This is english file."

 
 
Internationalization in JSP application  
 

Few years back, the sites were developed using a single language and the developer used to create the sites to their specific languages. As the globalization occured, many frameworks have developed to support the multiple languages at a time. Now this can be achieved by having the multi language text in key/value pair and at runtime the text is read from the key as per the language required. This multilingual support is known as Internationalization. Internationalization is defined as the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

The following classes are used to implement Internationalization to any site.

  • Locale - The fundamental Java class that supports internationalization is Locale . Each Locale represents a particular choice of country and language, and also a set of formatting assumptions for things like numbers and dates.
  • ResourceBundle - The java.util.ResourceBundle class provides the fundamental tools for supporting messages in multiple languages.
  • PropertyResourceBundle - One of the standard implementations of Resource Bundle allows you to define resources using the same "name=value" syntax used to initialize properties files. This is very convenient for preparing resource bundles with messages that are used in a web application, because these messages are generally text oriented.

Note:- The fmt is the jstl tag library used to implement the internationalization in JSP. The below example will tell you "how to use the fmt taglib in the application". The example displays the text coming from the different properties files. The properties file lables.properties is created with different locale suffix example en is for english, de for Germany etc. We have hello key in both the files. hello=This is german File in de file and hello=This is english File in english file.

Example JSP file Internationalization.jsp file .

<%@ taglib prefix="fmt" uri="/WEB-INF/fmt.tld"%>
<fmt:setLocale
value="de" scope="session
"/>
<fmt:bundle
basename="com.visualbuilder.labels
">
    <fmt:message>
    hello

    </fmt:message>
</fmt:bundle>

Output:-

The file will display "This is german File" and if the locale is changed to en then it will display the "This is english file."

 
 
Introduction To Expression Language.  
 

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. As the EL is introduced in JSP 2.0, we can also use the page attribute isELIgnored to ignore the EL for a page.

 

<%@ page isELIgnored ="true|false" %>

 

The following is the EL operator table which can be used with the EL language.

 

Note:- and,eq,gt,true,instanceof,or,ne,le,false,empty, not,lt,ge,null,div and mod are reserved words in the EL so user cannot use these words for the identifiers.

 

 

ExpressionResult
\${3+2-1}
${3+2-1} <%-- Addition/Subtraction --%>
\${"1"+2}
${"1"+2} <%-- String conversion --%>
\${1 + 2*3 + 3/4}
${1 + 2*3 + 3/4} <%-- Mult/Div --%>
\${3%2}
${3%2} <%-- Modulo --%>
\${(8 div 2) mod 3}
${(8 div 2) mod 3} <%-- Compares with "equals" but returns false for null --%>
\${1<2}
${1<2} <%-- Numerical comparison --%>
\${"a"<"b"}
${"a"<"b"} <%-- Lexical comparison --%>
\${2/3 >= 3/2}
${2/3 >= 3/2} <%-- >= --%>
\${3/4 == 0.75}
${3/4 == 0.75} <%-- Numeric = --%>
\${null == "test"}
${null == "test"}
\${(1<2) && (4<3)}
${(1<2) && (4<3)} <%--AND--%>
\${(1<2) || (4<3)}
${(1<2) || (4<3)} <%--OR--%>
\${!(1<2)}
${!(1<2)} <%-- NOT -%> <%-- Handles null or empty string in request param --%>
\${empty ""}
${empty ""} <%-- Empty string --%>
\${empty null}
${empty null} <%-- null --%>
 
 
Introduction to Tag libraries  
 

JSTL is a component technology within the Java 2 Enterprise Edition (J2EE) specification and is controlled by Sun Microsystems. JSTL is nothing more than a set of simple and standard tag libraries that encapsulates the core functionality commonly needed when writing dynamic JSP pages. The following are the problems with the JSPs:-

  1. Java code embedded within scriptlet tags is ugly and obtrusive.
  2. It is very difficult to modify the java code embedded in the JSP files if the file is large.
  3. Java code within JSP scriptlets cannot be reused by other JSP pages.
  4. Retrieving objects out of the HTTP request and session is cumbersome and type casting to the object's class is required.

The JSTL tags are basically categorized into four libraries:

  • core:- Basic scripting functions such as loops, conditionals, and input/output.
  • fmt:- Internationalization and formatting of values such as currency and dates.
  • xml:- XML processing
  • sql:- Database access.

Advantages of using JSTL:-

  • JSTL tags are XML based tags which are cleanly and uniformly blend into a page's HTML markup tags.
  • The four JSTL tag libraries include most functionality that would be needed in a JSP page. JSTL tags are easier for non-programmers and inexperienced programmers, because they do not require any knowledge of Java programming.
  • JSTL tags encapsulate reusable logic such as formatting dates and numbers.
  • JSTL tags can reference objects in the request and session without knowing the object's type and no casting is required.
  • JSP's EL (Expression Language) makes it easy to call getter and setter methods on Java objects. This is not possible in JSP 1.2, but became available in JSP 2.0. EL is used extensively in JSTL.

JSTL Drawbacks:

  • JSTL can add processing overhead to the server. Both Java scriptlet code and tag libraries are compiled into a resulting servlet, which is then executed by the servlet container. Java code embedded in scriptlet tags is directly copied into the resulting servlet. But JSTL tags add more than required code to the servlet.
  • Although JSTL provides a powerful set of reusable libraries, it cannot do everything that Java code can do. It is designed to facilitate scripting the presentation code that is typically found in the view tier of Model-View-Controller applications.
 
 
Introduction To Core Taglib -1  
 

Core taglib is the important taglib in the JSTL. It includes the core concepts of the programming like declaring the variable, decision making tags etc.. The next sections will explain all the core taglib tags, which are generally used in the programming.

Standard Syntax:
     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Variable Support Tags

The <c:set> tag sets the value of an EL variable or the property in any of the JSP scopes (page, request, session, or application). If the variable does not exists, it will be created.

The JSP EL variable or property can be set either from the attribute value:

<c:set var="var" scope="session" value="..."/>

OR

<c:set var="var">
...
</c:set>

To remove an EL variable, you use the <c:remove> tag as follows:

<c:remove var="test" scope="session"/>

Conditional Tags
The <c:if> tag allows the conditional execution of its body according to the value of the test attribute. The syntax of the <c:if> conditional block is as follows:-

<c:if test="${condition}"> </c:if>


The <c:choose> tag performs conditional block execution by the embedded <c:when> tags. It renders the body of the first <c:when> tag whose test condition evaluates to be true. If none of the test conditions evaluates to be true, then the body of <c:otherwise> tag is evaluated, if present. The syntax is as follows :-

<c:choose>
     <c:when
test="condition1
" >
     ...
     </c:when>
    <c:when
test="condition2
" >
    ...
    </c:when>
    <c:otherwise>
    </c:otherwise>
</c:choose>

 
 
test page 2  
 
page 2, please change me
 
 
page 2  
 
p2
 
 
this is 2nd page  
 
This is second pages text
 
 
 
Date entered : 1st Jan 1970
Rating :No Rating
Submitted by :
 
0 comments have been posted for this Article.View Comments Here
 
  Home> Articles > >
Copyright Visualbuilder.com 1999-2006