Saturday, August 23, 2014

Implicit variables and objects in JSP



This is another important lesson in JSP. Before start this section it is better if you can look at our previous examples that have been done using JSP. In  this examples we used some variables without declaration and initialization (out,page...etc). JSP engine makes nine implicit variables to  the JSP page.

The objects that these variables are refer to are called implicit objects.


application variable and object


This variable is belongs to javax.servlet.ServletContext class. This refers to the environment of the web application. 

The application object is a representation of the JSP page through its entire life circle. IT is created when the JSP page is initialized and it will be removed by jspDestroy() method.

<% out.print(application.getServerInfo()); %>



session variable and object


You have learnt a attribute called session in JSP directives. This implicit variable is declared only if the session attribute  of the page directive is true. If session="false", JSP engine doesn't declare this variable. The session object is a instance of javax.servlet.http.HttpSession interface. This is used to track client sessions.

<%@page session="true" %>

<% out.print(session.getId());  %>



request / responce variable and object


These two implicit variables are related to javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponce interfaces. The JSP engine creates new request objects for each and every client requests and also creates response objects to response clients. There are so many method associated with request and response objects.

<%
    String filePath = request.getServletPath();
    out.print("Your file path is: " + filePath);
%>


config variable and object


config variable is a type of javax.servlet.ServletConfig. This object allows to programmer to access to parameters of the JSP engine such as path, location, file name...etc.

<% out.print(config.getServletContext()); %>



out variable and object


This is a instance of javax.servlet.jsp.JspWriter class. This object has similar methods as PrintWriter class in Java. But additionally it has some methods to deal with buffering. This can be used directly in scriptlets and indirectly in expressions.  

<% out.print("Hi one"); %>

<%= "Hi two" %>



page variable and object


This is a instance of java.lang.Object class. This is entirely talk about the whole page and used to call the methods defined by the translated servlet class.

<% out.print(page.getClass().toString()); %>



pageContext variable and object



This object is also use to represent entire JSP page and it is a instance of javax.servlet.jsp.PageContext. pageContext class is an abstract class which stores references to the implicit objects. This class provide methods to set and get attributes.

<% pageContext.setAttribute("i", 10);  %>
<% out.print(pageContext.getAttribute("i"));   %>



exception variable and object


This is a instance of java.lang.Throwable interface. This can be used only if the page is set to a error page using isErrorPage = true. If it is set to true, then you can get the exception messages. 

<html><body>
<%@ page isErrorPage='true' %>
Error Message: <%=exception.toString()%> 
</body></html>






Thursday, August 14, 2014

JSP JavaBeans


What is JavaBean ?


JavaBean is a special Java class which is written according to the JavaBean API. There are conventions for JavaBeans.

  • The class should be serializable.
  • The class must have a public constructor (no arguments). 
  • It can have getter and setter methods for every property in the class.

JavaBean naming conventions


There is a post for Java naming rules in this blog. You can refer it for more details.

Example for JavaBean



package user;

import java.io.Serializable;

public class JavaBeanExample implements Serializable{
    
    private String name=null;
    //setProperty
    public void setName(String name){
        this.name=name;
    }
    
    //getProperty
    public String getName(){
        return name;
    } 
}


JavaBean with JSP



You can access JavaBeans through JSP. To do this task we use jsp:useBean action with few attributes. Here is an example that shows how to add useBean action into your JSP page.


<jsp:useBean id="Bean ID" scope="Bean's scope"/>


jsp:useBean attributes



There you have seen what are the attribute that can be used with jsp:useBean. There are few rules that you need to follow writing jsp pages.

  • id attribute is mandatory. This is the unique identifier of the bean.
  • scope attribute is optional. Default value is page. You cannot use session scope if session attribute of page directive is set to false.
  • Other three attributes can be used according to following combinations. At least one of them should be mentioned.
      1. class
      2. type
      3. class + type
      4. beanName + type

jsp:setProperty action



In JavaBean class there are setter and getter methods as I mentioned before. This setProperty action is used set methods. Here you can see how to use it in JSP.

<jsp:setProperty name="bean's id" property="property name" value="value">

jsp:setProperty attributes




As you can see there are only four attributes in jsp:setProperty. You need to understand few things before step forward into jsp:getProperty.


  • name attribute is mandatory. Because this is used to identify the bean. This value should be same as the id of the jsp:useBean action.
  • property attribute is also mandatory. It indicates the property of the bean to be set. You can set all the properties to respect values using " * " for property attribute. (property = "*")
  • value is optional attribute. Look at the following codes. Both are same.

<jsp:setProperty name="userName" property="firstName" value="Ann">

Above code is equal to following scriplet code.

<% userName.setFirstName("Ann") %>


  • Instead of using value attribute it can be used  param attribute to define requested parameters. Following codes are equivalent.

<jsp:setProperty name="userName" property="firstName" param="newName">


Above code is equal to following scriptlet code.

<% userName.setName(request.getParamter("newName")) %>


jsp:getProperty action



This is used to retrieve and print values of the bean. You can use it as follows.

<jsp:getProperty name="beanInstanceName" property="propertyName">



jsp:getProperty attributes



Following JSP code and Scriptlet  codes are equal.

<jsp:getProperty name="userName" property="firstName">

This is equal to, 

<% out.print(userName.getFirstName()); %>


Now it is the time to see what really happens in coding. Here is an example that demonstrate how to use JavaBeans with JSP.


EmployeeBean.java


package factory;

import java.io.Serializable;

public class EmployeeBean implements Serializable{
    
    private String name = null;
    private String id = null;

    public String getName(){
        return name;
    }
    
    public String getId(){
        return id;
    }
    
    public void setName(String name){
        this.name = name;
    }
    
    public void setId(String id){
        this.id = id;
    }
}


home.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <body>
        <h2>Employee details</h2>
        
        <form method="post" action="employeeJsp.jsp">
            <label>Name :</label> <input type="text" name="name"></br>
            <label>ID :</label> <input type="text" name="id"></br>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>





employeeJsp.jsp



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="factory" class="factory.EmployeeBean" scope="session"/>
<jsp:setProperty name="factory" property="name"/>
<jsp:setProperty name="factory" property="id"/>
<%-- 
Instead of using above two statemens, you can use following code
    <jsp:setProperty name="factory" property="*"/>
--%>

<!DOCTYPE html>
<html>
    <body>
        <h1>Hi <jsp:getProperty name="factory" property="name"/> ! </h1>
        <h2>Your ID is <jsp:getProperty name="factory" property="id"/> </h2>
        <%--
        Instead of using jsp:getProperty, you can use following code
            <%= factory.getName() %>
            <%= factory.getId() %>
        --%>
    </body>
</html>


Download project file










Tuesday, August 12, 2014

Re-usability of JSP



JSP always make your code easier to handle. If you are familiar with php you can remember there is something that you can include a php page to a another page. Think about a simple html page.




You can divide your php file into few sections like above image. Then you can create separate web pages like header.php, nav.php and footer.php likewise. Then once you need that section, you can include it using php include command. 

In JSP there is a mechanism to do that task. JSP can reuse web components. This can be done in two ways.

  1. Static
  2. Dynamic

    Static include



    This is very similar to php include. But in this method you can include any text based file (JSP, HTML, XML or even text file) into your JSP page. The content of another file is included with the current JSP file. In translation it looks like a single servlet. This can be done in two ways as follows. 


    <%@include file="mango.jsp" %>
        
    <jsp:directive.include file="Cherry.jsp"/>
    
    

    Here is an example to understand about Static include. I have created four files to demonstrate this. You can download NetBeans project file below and try it. Final browser view should be like this.


    Download source code



    Rules of Static include

    • file name attribute cannot be an expression.
    • file attribute cannot pass any parameters.

    Dynamic include



    In this way, If you request a JSP page, it sends a request to the object and the output is included in current JSP file. This can be done in two ways using include and forward.


    <jsp:include page="url" flush="true" />
    <jsp:forward page="url" />
    
    

    Using include

    This can be done as follows. You can include files using following methods.


       <%
           RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
           dispatcher.include(request, response);
       %>
    
    

    Method 2
       
       <%
           pageContext.include("newPage.jsp");
       %>
    
    

    Method 3

        <jsp:forward page="newPage.jsp" flush="true"/>
    
    


    Using forward

    There are three ways to perform this task.

    Method 1

       <%
           RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
           dispatcher.forward(request, response);
       %>
    
    

    Method 2
       
       <%
           pageContext.forward("newPage.jsp");
       %>
    
    

    Method 3

        <jsp:forward page="newPage.jsp"/>
    
    


    Here is an example for both Including and forwarding. You can import it and run on NetBeans. Then try to understand what is the different between Static and Dynamic inclusions using the result.  









    Friday, August 8, 2014

    Celsius to Fahrenheit converter GUI application

    This is very simple program with NetBeans. First create the GUI using design view of NetBeans, and then try to code as follows. 


    Application on design view



    Application components on Navigator  



    Final design


    Here is the code that I copied from NetBeans. It looks too long, but many of codes are auto generated by NetBeans.


    package tempcal;
    
    public class Temp extends javax.swing.JFrame {
    
        public Temp() {
            initComponents();
        }
    
        @SuppressWarnings("unchecked")
        //                           
        private void initComponents() {
    
            tempInput = new javax.swing.JTextField();
            celLabel = new javax.swing.JLabel();
            convertBtn = new javax.swing.JButton();
            farLabel = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Celsius to Fahrenheit");
            setAutoRequestFocus(false);
            setBackground(new java.awt.Color(204, 204, 204));
            setFont(new java.awt.Font("Corbel", 0, 10)); // NOI18N
    
            tempInput.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
            tempInput.setToolTipText("Enter celsius value");
            tempInput.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
            tempInput.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    tempInputActionPerformed(evt);
                }
            });
    
            celLabel.setText("Celsius value");
    
            convertBtn.setText("Convert");
            convertBtn.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    convertBtnActionPerformed(evt);
                }
            });
    
            farLabel.setForeground(new java.awt.Color(0, 153, 153));
            farLabel.setText("Fahrenheit");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(convertBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(farLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(tempInput, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(celLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(98, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tempInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(celLabel))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(convertBtn)
                        .addComponent(farLabel))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }//                         
    
        private void convertBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
            int far = (int)((Double.parseDouble(tempInput.getText()))* 1.8 + 32);
            farLabel.setText(far + " Fahrenheit");
        }                                          
    
        private void tempInputActionPerformed(java.awt.event.ActionEvent evt) {                                          
            
        }                                         
    
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Temp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Temp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Temp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Temp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Temp().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JLabel celLabel;
        private javax.swing.JButton convertBtn;
        private javax.swing.JLabel farLabel;
        private javax.swing.JTextField tempInput;
        // End of variables declaration                   
    }
    
    
    


    Here is the final project file. You can copy it and import it to your NetBeans and then you can try it. Happy coding...!!!




    Thursday, August 7, 2014

    Introduction to EJB

    What is EJB ?



    • Stands for Enterprise Java Beans.
    • Very important part in J2EE platform.
    • Provides components based development architecture.


    What is a Bean ?


    • Simply, a bean is a component. 
    • Component is something like building block.


    Why EJB ?


    EBJ is a component based architecture design. It means it consist of components. When in a enterprise application, it is very easy to interact with this kind of design. EJB gives you a lot of services. So you need not to write them in your programs. Basically EJB let you to think about the business logic easily.  

    Other thing is, you can customize and reuse your components at deploy time without touching the source code. This is a one of main advantages of EJB.

    EJB services


    EBJ gives you many services that you need not to code. 
    • Security
    • Concurrency
    • Networking
    • Transaction management
    • Resource management
    • Persistence
    • Messaging
    • Customization

    Architecture of EJB




    As you can see Enterprise beans are in EJB container. There are EJB objects also within the container. Later on we discuss about them. This is the very simple demonstration of the EJB container and how it works with client objects. Client can be a servlet or JSP or other Java application and we think he is a remote one. 

    Think about a banking system. You have a bank account and a ATM card (Master card, VISA...etc) for your account. So you can get your money back using that ATM card from anywhere in the world. You can use your mobile phone to do transactions with your account. Then you are a remote client who are not directly connect to the main server and you are running on another JVM. EJB is very useful to do this kind of huge processing and transactions. I think now you have a question, how to connect remote clients as above image. It looks very simple, isn't it ? 




    It is very easy to understand. Think if you are a client and you use your laptop and WiFi network to connect to the internet to connect to some kind of enterprise application to get some details from its database.   

    EJB has highly thought about security. No one can directly connect with a Enterprise bean even you. You have to use EJB object to connect and access Enterprise bean. EJB object is like a bodyguard of a Enterprise bean. So clients have to  connect to Enterprise bean via EJB object. 


    Image resource : http://blog.xebialabs.com/

    But I have said that client is a remote one on the most of enterprise applications which is running on another JVM. Then it is not easy to connect with client and EJB object of the enterprise application, because client has to go through proxies, firewalls and other protocols. So how to handle these things ? 

    These things are handled by Java RIM (Remote Method Invocation). It gives you a proxy object called "stub" to handle the communication with remote objects. This object act as a helper to the client object. It helps to programmer with promoting network transparency. So you need not to think about them.

    There is another object in server side as well. It is called "skeleton object". This object is received the remote connection from remote stub and figure out what it says.



    Types of Beans in EJB



    • Session beans
    • Entity beans
    • Message driven beans

    Session beans

    Session bean stores a data of a particular user in a session. There are two types of session beans.

    1. Stateless
    2. Stateful

    Entity beans

    This is use to represent a thing in a persistence store. You can use it to save data on database and retrieve data from it.

    Message driven beans

    This can be used only if you want JMS (Java Message Service) consumer. It listen for messages from JMS.