Tuesday, 8 April 2014

Spring Framework - PART - II - Spring MVC

In this discussion ,I'll be focussing on spring MVC .

  • As the name suggests spring MVC is made around model , view and controller or in another words ,  it is the web component of spring framework . 
  • It provides the functionality to make web applications .
  • spring framework can be integrated easily with other web frameworks like struts . There is no tight coupling between spring and other web frameworks.
Table of Contents :-

  • Basic Introduction
  • Workflow of spring MVC 
  • Features 
  • Configuration
  • Implementing Controllers
  • Small application with spring framework - GET request handling
  • Form handling - POST request

Basic Introduction :- 
Root of spring MVC framework is DispatcherServlet that dispatches the request to handlers or controllers , that leads to the development of spring web application.
                       
                                         
                                                                                                                 

Workflow of spring MVC :- 
The spring model-view-controller is designed around a dispatcher servlet that is responsible for handling http request and response cycle.Few steps to handle request and response cycle are :-
  • When request comes to Dispatcher Servlet , it consults to handler mapping to find the appropriate controller.
  • Controller takes the request and call the appropriate service method based on GET or POST request.
  • Service method set the model based on business logic and returns view name to Dispatcher Servlet.
  • Servlet then consults the view resolver to get the view.
  • View is then rendered to the client.
Features :- 

  • It provides support for REST based web services
  • It provides annotation based configuration support.
  • It allows any number of request handling methods.
  • It does not have any interface or base class requirement.
Configuration :-
As first of all request comes to Dispatcher servlet so we need to set up the dispatcher servlet in web.xml file .

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3-Hibernate</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>springhibernate</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springhibernate</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

In above example we have defined servlet name(<servlet-name>) and mapping (<url-pattern>) that it'll handle.

springhibernate-servlet.xml file : - 


<?xml  version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
  <context:component-scan base-package="com.mycompany.app.user.controller" />
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>
  • Upon initialization of Dispatcher servlet , framework looks for the file named [servlet-name] -servlet.xml file in the WEB-INF directory. i.e. springhibernate-servlet.xml file as shown above.
  •  In springhibernate-servlet.xml   we have used InternalResourceViewResolver that have the internal rules for rendering view . e.g. If handler return hello then according to suffix (".jsp") hello.jsp view will be render that is located in (/WEB-INF/jsp) i.e. defined in prefix.
  • Before moving to application we should have knowledge about @controller , @RequestMapping ,@PathVariable annotations . How these annotations works during request response cycle.
Implementing controllers :- 

MVC controller provided annotation based programming model that uses annotations such as @RequestMapping , @PathVariable , @ModelAttribute etc. 
I have taken the example of my controller which i have made in my application :-

@Controller
public class userController {
    @Autowired
    private userService userService;
    @RequestMapping("/index")
    public String listUsers(Map<String, Object> map) {
        map.put("user", new user());
        map.put("userList", userService.listUser());
        return "user";
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user")
    user user, BindingResult result) {
    userService.addUser(user);
        return "redirect:/index";
    }
    @RequestMapping("/delete/{userId}")
    public String deleteUser(@PathVariable("userId")
    Integer userId) {
    userService.removeUser(userId);
        return "redirect:/index";
    }
}

Defining a controller with @Controller :- 
  • @Controller annotations describes that particular class is playing the role of controller.  and in Spring we do not have to extend any base class controller.
  • In [servlet-name]-servelet.xml file we define a tag to scan the controller as :-                  <context:component-scan base-package="com.mycompany.app.user.controller" />    
  •  So, dispatcher scans controller classes define with @controller annotation and detects for another annotations.
@RequestMapping  :-
  • To map the URLs , we use @RequestMapping annotation . It can be use with handler or particular method.
  • As in above example , @RequestMapping is used in many places . 
  • First usage in listUsers method . It means this method will handle the request that will have URL like :-   localhost:8080/springhibernate/index
  • Second usage in addUser Function . It means this method will handle the request that will have URL like :-   localhost:8080/springhibernate/add
  • Third usage in deleteUser. This method will handle the request that will have URL like :- localhost:8080/sprinhghibernate/delete/12 , where 12 = {userId}
@ModelAttribute :- 
  • In addUser Function we have user @ModelAttribute annotation . and also this method has POST request . During POST request we bind the form data with @ModelAttribute  annotation . It specifies the method arguments that is passed from the Form. 
  • In above example, I have passed the user information that is filled into form .
@PathVariable:-
  • It indicates that the meethod paramater is bound to the URI template variable.
  • In above example, userId will get from the URI : - localhost:8080/springhibernate/delete/12 , here userId =12
Small application with spring framework - GET request handling :- 
Before starting an application we should have following :-
  • Eclipse
  • Tomcat
  • JDK
Our goal it to print hello world .

Getting Started :- 

  • create a maven project , write the command as :-

mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  • To convert maven project to support eclipse IDE , issue the command :-

mvn eclipse:eclipse
  • Now Import the project into eclipse.
  • Next step is to adding dependency into pom.xml file :-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>springMVC</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
<properties>
     <org.springframework.version>3.0.2.RELEASE</org.springframework.version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
<configuration>
<!-- Directory for Web application-->
<webappDirectory>webapp</webappDirectory>
<webResources></webResources>
</configuration>
</plugin>
</plugins>
<finalName>springMVC</finalName>
</build>
  <name>springMVC</name>
  <url>http://maven.apache.org</url>
 <dependencies>
   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
  </project>

As I stated before , first of all request comes to dispatcher servlet ,so we have to define the dispatcher servlet name and url-pattern in web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>SpringMVC</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Next step is to make springMVC-servlet.xml file in WEB-INF folder. and as i explained earlier , in this file i'll define context-scan base package and internalviewresolver bean that will have prefix and suffix properties for the view name. As shown below :-

springhibernate-servlet.xml file : - 

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
  <context:component-scan base-package="com.mycompany.app.user.controller" />
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

Next step is to make controller file :-

package com.mycompany.app.user.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class userController {
  @RequestMapping("/welcome" , method=RequestMethod.GET)
    public String showWelocme(ModelMap model) {
        model.addAttribute("message","Hello world");
        return "hello";
    }
 }

  • When controller will return the hello to the dispatcher servlet , then it'll consult the view resolver to find the appropriate view . View resolver then render the particular view to the client. 
  • As we have defined in the dispatcher servlet xml file(i.e. springhibernate-servlet.xml) file, Internalviewresolver will find out the hello.jsp file in WEB-INF/jsp folder. and render it to the browser.
  • So next step is to make hello.jsp file in WEB-INF/jsp folder.
hello.jsp file :-

<html>
   <body>
   <h2>Message : ${message}</h2>
   </body>
</html>

  • Next step is to deploy the war on tomcat and restart the server. 
  • Hit the  url :- localhost:8080/springMVC/welcome.
  • Message will display i.e. Hello world
This is what about GET request.

Form Handling - POST request :-

  • In this example i'll show web application which make use of html forms using spring framework .
  • Make the configuration files i.e. web.xml  and  servlet file  as i stated above in first example.
  • Next step is to create an entity file , controller and jsp file.
Entity file :-

package com.mycompany.app.user.form;


public class user {
private Integer id;
 private String firstname;
 private String lastname;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

}

Controller File :-

package com.mycompany.app.user.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;

@Controller

public class userController {

   @RequestMapping(value = "/user", method = RequestMethod.GET)

   public ModelAndView user() {
      return new ModelAndView("user", "command", new user());
   }
   
   @RequestMapping(value = "/adduser", method = RequestMethod.POST)
   public String addUser(@ModelAttribute("SpringWeb")user user, 
   ModelMap model) {
      model.addAttribute("firstname", user.getFirstname());
      model.addAttribute("lastname", user.getlastname());
      model.addAttribute("id", user.getId());
      
      return "result";
   }

}

In controller file we have 2 functions :-

  1. First is user() function that has ModelandView return type. Request Mapping for this function is /user .i.e. when we will hit the locahost:8080/springWeb/user then user.jsp view will be render. Next is the command object , when we use<form:form> tag in jsp file then spring framework expects command object.
  2. Second is addUser() , The request mapping for this function is /adduser and RequestMethod is POST. During POST request , here we are using @ModelAttribute to set the form data in user. 


  • Next step is to make user.jsp file and result.jsp file.
  • user.jsp file for form and result.jsp file to show the data that we'll fill into the form.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>User Info</h2>
<form:form method="POST" action="/HelloWeb/addUser">
   <table>
    <tr>
        <td><form:label path="firstname">First Name</form:label></td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Last Name</form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>  
</form:form>
</body>
</html>

result.jsp  file :-

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Submitted User Information</h2>
   <table>
    <tr>
        <td>First Name</td>
        <td>${firstname}</td>
    </tr>
    <tr>
        <td>Last Name</td>
        <td>${lastname}</td>
    </tr>
    <tr>
        <td>ID</td>
        <td>${id}</td>
    </tr>
</table>  
</body>
</html>

This is what about handling forms in spring framework. 

 For further details about spring with hibernate you can read to my next tutorial(in progress).


























Tuesday, 1 April 2014

Spring Framework - Introduction - PART - I

In this discussion ,I'll be focussing on spring framework , Why spring framework came into existence , and how to use spring framework to implement business logic.

Table of Contents :-

  • What is spring framework ?
  • Modules and its overview
  • Advantages
  • When to use It ?
  • Beans
  • Dependency injection
  • How to use it in Real world ?
Spring Framework :

Spring is a lightweight framework that provides comprehensive infrastructure support for developing Java applications from plain old Java objects . It provides support to various frameworks like Struts , hibernate etc . 

Modules :- 
The spring framework organized into several modules such as AOP(Aspect oriented programming )  , IOC , ORM , WEB MVC etc . As Shown in Fig. 1.1 , these  modules are grouped into Core Container , Data Access/Integration , Web , AOP ,Instrumentation and tests .

                             
Fig. 1.1

Overview of spring framework Modules :- 
Core Container :-  
Core container consists of Beans , Core ,Context and Expresion language modules .The Core and Beans provides basic parts of framework including the IOC and dependency injection features. 

Context module builds on the base provided by Core and Beans. This module inherits the features from Core and Bean and add support for internationalization ,event propagation , resource loading . It also supports Java EE features such as JMX , EJB and basic remoting

The Expression Language module provides expression language for quering and manipulating the object at run time . 

Data Access / Integration :-
This layer consists of JDBC , ORM , OXM ,JMS and transactions modules .

  • JDBC provides JDBC abstraction layer for JDBC connection .
  • ORM module provides the integration layer for object relational mapping API's including hibernate , iBatis etc.
  • OXM module provides an abstraction layer that supports object/XML mapping  implementation for JAXB, XMLBeans.
  • JMS supports for producing and consuming messages.
  • Transactions module provides transaction management for all the POJOs.

Web :- 
  • The Web layer consists of Web ,Servlet , Portlet and struts modules.
  • Web module provides web oriented features such as file upload functionality and initialization of IOC container using web application context. 
  • Web Servlet module provides spring MVC implementation for Web application.
  • Web Struts module provides support for integrating a classic struts web tier within spring application through supporting classes.
  • Web Portlet module provides the MVC implementation to be used in spring enviroment.
AOP :-
  • AOP module provides an AOP Alliance complaint aspect oriented programming implementation allowing you to define method interceptors to decouple the code that implements functionality.
Instrumentation :- 
  • It provides class implementation support and class-loader implementations for application servers.
Test :- 
  • It provides support for testing of spring components with JUnit ot TestNG.
Advantages of Spring Framework :- 
Loose Coupling :-
  • Due to dependency injection in spring , the applications in spring are loosely coupled. Later we will see in detail about dependency injection
Fast Development :-
  • The Dependency injection feature makes the development faster.
Lightweight :-
  • Due to POJO implementation spring framework is light weight.
Predefined Templates :-
  • Spring framework provides templates for JDBC , hibernate etc.  So there is no need of writing too much code. It hides the basic steps of these technologies.
Declarative Support :-
  • It provides declarative support for caching , transactions , validation etc.

When to use Spring framework :- 
  • In large applications , objects dependencies arise or in other words objects are tightly coupled and it becomes very difficult to manage the objects as well as applications .Also from testing perspective , application consumes too much time for testing.  So Spring framework was evolved.
  • Here i am taking the example of draw shape to show how objects are tightly coupled and with the help of spring framework they can be loosely coupled. 

Draw Shape Example :- 
I have a interface Shape and classes that implements shape :-

public interface Shape
{
 public void drawShape();
}
class Rectangle :-
public class Rectangle implements Shape
{
 public void drawShape(){
  System.out.println("Rectangle");
 }
}
class Triangle :-
public class Triangle implements Shape
{
 public void drawShape(){
  System.out.println("Triangle");
 }
}
Main class :-
public class App 
{
    public static void main( String[] args )
    {
     Shape shapeObj= new Rectangle ();
     output.drawShape();
    }
}
Problem in above normal call :-
shapeObj is tightly coupled to Rectangle . Any changes in interface shape may lead to changes in code . If this code is using in your whole application , then it becomes bottleneck .
Next Option is we can take helper class that will create the object of class for which shape to be drawn . 
e.g.

public class ShapeCreatorService 
{
    private Shape shapeObj= new Rectangle ();

    public void draw()
    {
     shapeObj.drawShape();
    }
}
Now create the main class that will create the object of service class
public class App 
{
    public static void main( String[] args )
    {
     ShapeCreatorService shapeServiceObj= new ShapeCreatorService ();
     shapeServiceObj.draw();
    }
}
Problem in above call:-
Here problem lies in ShapeCreatorService . it has a shape variable that points to Rectangle .Here main problem arises due to new operator. what in future if i want to draw triangle . I have to change the source code to draw triangle . it means classes are very tightly coupled.
Solution to above problems - Dependency Injection and How to use it in Real word :-
  • Instead of changing the code of ShapeCreatorService to draw rectangle or triangle why not we assign the task to spring container which creates the instance of bean by reading spring configuartion file .
  • So Spring's dependency injection came into exist to remove tight coupling between classes.
Before knowing the dependency injection you should have knowledge of beans. Basically what beans are.

Beans :- 
Beans are nothing , these are simply objects .Rather than creating objects with new operator to avoid tight coupling , beans creation or instantiation is managed by IOC container . Beans are created in configuration metadata that we supply to spring container . configuration metadata is basically configuration file as shown below :-
Now create spring configuration file having following beans :-

<!-- Spring-Common.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 <bean id="ShapeCreatorService" class="com.src.main.java.impl.ShapeCreatorService">
  <property name="shapeObj" ref="Triangle" />
 </bean>
 
 <bean id="Triangle" class="com.src.main.java.impl.Triangle" />
 <bean id="Rectangle" class="com.src.main.java.impl.Rectangle" />
 
</beans>
  • In above xml file bean is defined in bean tag . id attribute is unique in xml file  and class attribute provides actual class for this bean id.
  • The Bean tag has a property tag to set property of particular bean.
  • The property tag has an attribute ref which is used to inject the instance to bean. ref tag uses setter method of a bean to inject an instance.
  • We modify our ShapeCreatorService class ,now rather than creating the object using new operator , it will have setter method in which we pass the object of shape , i.e. we are injecting the object to it.

 public class ShapeCreatorService {
 private Shape shapeObj;;
 
 public void draw(){
  shapeObj.drawShape();
 }
        public void setshape(Shape shapeObj){
  this.shapeObj= shapeObj;
 }
}
Main application class for calling shapeCreatorService by reading spring configuartion file.


import org.springframework.context.ApplicationContext;                         import org.springframework.context.support.ClassPathXmlApplicationContext;     public class App 
{
    public static void main( String[] args )
    {                                                                                   ApplicationContext context =    new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
     //ShapeCreatorService shapeServiceObj= new ShapeCreatorService ();            shapeCreatorService shapeServiceObj= (shapeCreatorService)context.getBean("shapeCreatorService");                                                            shapeServiceObj.draw();                                                      }                                                                         }
Now you don't need to change the code, just change the xml file.
This is what about general introduction of spring framework. For further details about spring like spring MVC you can read to my next tutorial(in progress).

    






Thursday, 27 February 2014

Developing apps using PowerBuilder

PowerBuilder is an integrated development environment owned by Sybase, a division of SAP. It is the fastest tool for creating high-performance applications at less cost and less time.
Pre-requisite :- Power Builder should be installed.
go to following link to install powerbuilder trial.

 http://www.sybase.com/products/modelingdevelopment/powerbuilder?htab=Technical+Info&vtab=Product+Manuals&hid=80395&vid=80383 

Getting started with development of an application using PowerBuilder :-

I am taking the example of employee management application :-
Steps :-
  1. Create a workspace by clicking on file->new->workspace in powerbuilder ,  say empManagement. As shown in figure :-                                        

                                   

Workspace will create as :-                  
                                                                         


             

 Next step is to create application .Right click on workspace , Click on new as shown in figure :-
                                                        

 

   then click on application as shown :-
                                                   
        
 
 
 Give it a name say empmgt , and save it .it'll be shown as :-

                                                    




                               

 As for creating an application ,first need is database and tables .
 For database :-
  •  go to file -> new 
  •  a window will open 
  • go to its database tab and 
  • select database painter as shown in figure :-

                                      
                                                             
 Next step is to create tables in database . as shown in figure .
  •  go to tools and 
  • click database painter.

                                                    


 Database painter will open .Create tables by right click on tables and select new table as shown in figure :-
                                         

  
 I created a table say emp having columns as shown in figure :-
            
                                     
and another table dept having column dept_id and name.
dept_id is foreign key in emp table. i.e. it is master table for emp table . I am directly inserting some department values into this table by insert queries.

Next step is to create connectservice from where connection information is obtained.
For connection information we have 3 options :-
  • ini file
  • Registry file
  • Script
i am using script option
 To create connectservice :-
  • go to file->new
  • click on PB object tab
  • click on connection object wizard.
                                       



connectservice(n_empmgt_connectservice) will create as shown in figure :-

                                                
    
Go to edit source of empmgt file (i.e. main application file) , connect db through n_empmgt_connectservice by writing following code snippet at the end of file :-
              
                                                                                                                                                                                                                       
 where gnv_connect is a global variable of type n_empmgt_connectservice . don't forget to declare it .

In above code snippet there is a code open(login_page) that means when i'll run ma app first page that will open will be the login_page.

 So next step is to create application pages :-

 I am creating a master page and will inherit other pages from master page by using inheritance feature of powerbuilder so that all the pages in application have same look and feel. 
steps to create a page:-
  • Click on file->new
  • go to PB object tab and click on window
  • a window will create
  • save it as master page as shown in figure :-
                            


 For better UI iadd a picture on master_page .
 Click on insert->control->picture as shown in figure :-

                            

 Picture control will show at window . Give it name and path of the picture as shown in figure :-
                            

Next i'll create login page inherited from master_page.
steps are :-
  • click on file->inherit
  • a window will be open
  • choose the master_page in window, click ok as shown in figure:-
                           
  • page will be create, name it as login_page .as shown in figure :-
                                          
  Login page having the image as in master page because of it is inherited from master_page. Take static text , singlelineedit control and buttons on login_page.
As shown in figure :-
                             
         
 Next step is to create Welcome page and register page. also inherit these pages from master_page .
As shown in figure My register page is :-
              
                                                 
 Now i want , when register page is opened , then supervisor and department dropdownlistbox values should come from database tables emp and dept respectively.
   
 For this , Go to :-
  •     open tab of register page
  •     write code to connect to database and then add following code snippet :-
                             
  where supervisor_value and department_value is tha name of dropdownlistbox respectively.

   After Register into app ,  
   Next step is to login to application with these username and password values. so write code at click event of login button. steps are:-
  •    write code to connect to db
  •    and then add following code snippet :-
              

Now i login to application by these username and password . As shown in figure :-                                                                           

      and redirected to welcome page  as shown in figure :-

                                            
  Next main feature of powerbuilder is its datawindow control :-
 DataWindow Control :- it is the container of datawindow objects in PowerBuilder and used to display the data or in other words , we use datawindow control for reporting.
 Here i am using datawindowcontrol for showing the list of employees.
 First make a employee_list page that is inherited from master_page and take a datawindow control at this page . As shown in figure :-
                
                         

 
 Next step is to add dataobject for datawindow control .
steps to create dataobject :-
  • go to file->new
  • go to datawindow tab of opened window. 
  • select grid at ths tab
  • click ok
  • then select quickselect
  • click next
  • then select the table for which you want to show the data on datawindow . i select emp table. (When i select emp then dept table can also select because both table have relationship)
  • as shown in below  fig , at right hand sight there is columns window , select columns that you want to show in datawindow..
  • click ok 
You'll see something like this :-
                                                                                                                                                                                              
   
  • click next->finish
  • dataobject will create.
Next step is to add dataobject in datawindow control. 
  • Go to data window property.
  • select dataobject.
  • as shown in fig :-
                            

i want datawindow to be updated or refresh every time when i go to employee_list page for this write  dw_1.Retrieve( )  at open event of datawindow control. 
When i run this page data will be shown in datawindow control as shown in fig :-                                                                                                                                                                                                                                                                  
This is my small app that i developed using PowerBuilder .
Enjoy developing application using PowerBuilder . :-)