Showing posts with label GWT. Show all posts
Showing posts with label GWT. Show all posts

Google App Engine, JDO and GXT(Ext GWT) Grid - Make All These Working Together

Previously I have written some blogs about GXT Grid  where the data resides in the client side. But as per the request of my readers I feel the necessity of writing some tutorials with remote data store. And for this purpose I have chosen Google App Engine data store as the back-end with JDO implementation.

It requires a configuration file in the final WAR named  jdoconfig.xml which resides in the directory war/WEB-INF/classes/META-INF/. Eclipse creates this file as src/META-INF/jdoconfig.xml. This file is automatically copied into war/WEB-INF/classes/META-INF/ when you build your project. This file should contain the following contains.

<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">

   <persistence-manager-factory name="transactions-optional">
       <property name="javax.jdo.PersistenceManagerFactoryClass"
           value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/>
       <property name="javax.jdo.option.ConnectionURL" value="appengine"/>
       <property name="javax.jdo.option.NontransactionalRead" value="true"/>
       <property name="javax.jdo.option.NontransactionalWrite" value="true"/>
       <property name="javax.jdo.option.RetainValues" value="true"/>
       <property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
   </persistence-manager-factory>
</jdoconfig>

Here I am going to describe the way of loading a comment list from the App Engine data store and making the list viewable in the GXT Grid. So At first I need a POJO class to store and retrieve comments from the App Engine data store using the JDO API. Here is my Comments class.

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Comments {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    @Column(name="comments")
    private String comments;

    @Persistent
    @Column(name="posted_by")
    private String postedBy;
    
    @Persistent
    @Column(name="posted_date")
    private Date postedDate;

    public Comments(String comments, String postedBy, Date date) {
        this.comments = comments;
        this.postedDate = date;
        this.postedBy = postedBy;
   }

    public Long getId() {
        return id;
    }

 public String getComments() {
  return comments;
 }

 public void setComments(String comments) {
  this.comments = comments;
 }

 public Date getPostedDate() {
  return postedDate;
 }

 public void setPostedDate(Date postedDate) {
  this.postedDate = postedDate;
 }

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

 public String getPostedBy() {
  return postedBy;
 }

 public void setPostedBy(String postedBy) {
  this.postedBy = postedBy;
 }
}

Now when you want to transfer data from server to client you need a DTO (Data Transfer Object). As I am going to show the comments in GXT Grid so my DTO has to inherit the properties of GXT's BaseModel. Here is the CommentModel class which will serve my purposes.

public class CommentModel extends BaseModel {

private static final long serialVersionUID = 1L;

public CommentModel(){}

public CommentModel(String comments, String postedBy, Date date) {
set("comments", comments);
set("postedDate", date);
set("postedBy",postedBy);
}

public String getComments() {
return (String) get("comments");
}

public String getPostedBy() {
return (String) get("postedBy");
}

public Date getStartingDate() {
return ((Date) get("postedDate"));
}
}

For any operation on data store you have to request the data store for the desired operation. Each request that uses the data store creates a new instance of the PersistenceManager class through the instance of  PersistenceManagerFactory class. As creating an instance of PersistenceManagerFactory class is a very costly process, I have used a Singleton class PMF for this purpose.

public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");

private PMF() {}

public static PersistenceManagerFactory get() {
return pmfInstance;
}
}

If you are familiar with GWT RPC Service then create a service named CommentService and add a method
List<CommentModel> getAllComment();. Here is the implementation of the method where JDOQL is used to write a query which returns all the comments from the data store.

public List<Commentmodel> getAllComment() 
{
   List<Commentmodel> commentList = new ArrayList<Commentmodel>();
   PersistenceManager pm = PMF.get().getPersistenceManager(); 
   try {
      String query = "select from " + Comments.class.getName()+" order by  postedDate desc"; 
      List<Comments> list = (List<Comments>) pm.newQuery(query).execute();
      if (!list.isEmpty()) {
         for (Comments c : list)
         {
            //convert from entity object to DTO
            commentList.add(CommentConverter.entityToModel(c));
         }
      }
   }catch (Exception ex) {}
   finally {
      pm.close();
   }
   return commentList;
}

CommentConverter is a utility class which converts an object of Comments class to an object of CommentModel class.

public class CommentConverter 
{
   public static CommentModel entityToModel(Comments comment)
   {
      CommentModel model = new CommentModel(comment.getComments(), comment.getPostedBy(), comment.getPostedDate());
      return model;
   }
} 

All the server side coding is done. Let's come to client side.

First create an instance of CommentServiceAsync.
public static final CommentServiceAsync commentService = GWT.create(CommentService.class);
 

Then create a ListStore of CommentModel, commentStore and call the getAllComment method of the commentService. In the onSuccess method add the returned list to the commentStore.
 final Label lbError = new Label();
  final ListStore<Commentmodel> commentStore = new ListStore<Commentmodel>();
  commentService.getAllComment(new AsyncCallback<List<Commentmodel>>() {

   @Override
   public void onFailure(Throwable caught) {
    lbError.setText("data loading failure");

   }

   @Override
   public void onSuccess(List<Commentmodel> result) {
    commentStore.add(result);

   }
  }); 

The rest of the tasks are very familiar with the GXT users. Creating a List of ColumnConfig, a Grid with the commentStore and  ColumnConfig lists, etc.

        List<Columnconfig> configs = new ArrayList<Columnconfig>();
        ColumnConfig column = new ColumnConfig();
        column.setId("comments");
        column.setHeader("Comments");
        column.setWidth(200);
        configs.add(column);

        column = new ColumnConfig("postedBy", "Posted By", 150);
        column.setAlignment(HorizontalAlignment.LEFT);
        configs.add(column);

        column = new ColumnConfig("postedDate", "Posting Date", 100);
        column.setAlignment(HorizontalAlignment.RIGHT);
        column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());
        configs.add(column);

        ColumnModel cm = new ColumnModel(configs);

        final Grid<Commentmodel> grid = new Grid<Commentmodel>(commentStore, cm);
        grid.setBorders(true);
        grid.setAutoExpandColumn("comments");
        grid.setStyleAttribute("borderTop", "none");
        grid.setStripeRows(true);

        ContentPanel cp = new ContentPanel();
        cp.setBodyBorder(false);
        cp.setHeading("Grid with Pagination");
        cp.setButtonAlign(HorizontalAlignment.CENTER);
        cp.setLayout(new FitLayout());
        cp.setSize(700, 300);
        cp.add(grid);

That's all for today. You will get a live example of this tutorial here.
For more about Google App Engine and JDO visit this.

How to Call a Servlet in GWT

Sometimes you may need a HttpServlet other than GWT Rpc Service in a real life application. If needed then how to call the Servlet from your GWT client? Here you will find the answer.

Here is a simple HelloServlet

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ 
String name = request.getParameter("name");
response.getWriter().write("Hello "+name+", Welcome in My Servlet");
}
}
The Servlet uses a request a parameter 'name' and writes it in the response writer.

To call the Servlet from the client first configure the web.xml (war/WEB-INF/web.xml) file to let your GWT client know about the HelloServlet.

 HelloServlet
 org.ratul.servlettest.server.HelloServlet


 HelloServlet
 /hello

Value of the url-pattern node will be used later to call the Servlet.

Now make a simple UI with a TextBox and a Button.
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
RootPanel.get().add(nameField);
RootPanel.get().add(sendButton);

In the Click Handler of the sendButton call the Servlet with the 'name' parameter in the following way
sendButton.addClickHandler(new ClickHandler() {
  public void onClick(ClickEvent event) {
    Window.Location.replace("/hello?name="+nameField.getText());
    //the url-pattern value is used here
  }
});

Thats' all for today. Happy coding with GWT :-)

How to Use Your Session Beans from GWT Client

Recently we have finished a project in which we were using EJB3.0 in the business tier and a GWT client for the user interface. Here i will share you how we connected them in a very convenient way.

Suppose you have an Entity class, Department and a stateless Session Bean named DepartmentBean which implements a remote interface DepartmentBeanRemote. To save a department the bean class
has a create method

public BigInteger create(Department department)
{
try
{
em.persist(department);
em.flush();
return department.getIdNr();
} catch (InvalidStateException in)
{
in.printStackTrace();
} catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}

Now how to call this create method from your GWT client?

First create a GWT RPC Service named DepartmentService and DepartmentServiceImpl is the implementation class of this service interface. The service implemenltation class will serve as a gateway between client and bean class.

Create an instance of DepartmentBeanRemote by dependency injection in DepartmentServiceImpl.
@EJB
private DepartmentBeanRemote departmentBeanRemote;
Now use this instance to call the methods of the DepartmentBean in the following way

public Long create()
{
try
{
Department department = new Department();
department.setIdNr(null);
department.setDepartmentNameSt("Computer Science");
department.setDepartmentDescriptionSt("Most popular department of the university");
BigInteger returnValue = departmentBeanRemote.create(department);
return new Long(returnValue.toString());
}
catch (Exception e)
{
e.printStackTrace();
return null; 
}
}
Call the service method from the client. You have just made a complete path between your GWT Client and the Session Beans.

Session Management (Set and Get Data from Session) in GWT

When you think about the Security of a web application 'Session Management' is the first thing that strikes in your head. I am now working with an enterprise web application using GWT and you know security is a very vital issue in an enterprise application. And we have ensured the security by managing session data. Here i will describe how to store and retrieve data from session by using GWT RPC.

Suppose you want to store the user name in session after login to the application and check the session value later. Then what do you do?

First create a GWT RPC Service named 'SessionManagementService'. You can give any other name as you like. In SessionManagementService interface add two methods

public void setUserName(String userName);
public String getUserName();

And synchronize the methods with 'SessionManagementServiceAsync'.
public void setUserName(String userName, AsyncCallback<Void> asyncCallback);
public void getUserName(AsyncCallback<String> asyncCallback);

Now implement the methods in 'SessionManagementServiceImpl'. Let's first talk about the setter method.
public void setUserName(String userName)
{
     HttpSession httpSession = getThreadLocalRequest().getSession(true);
     httpSession.setAttribute("userName", userName);
}

The getThreadLocalRequest method returns you a HttpServletRequest object for the current call. For simultaneous invocation you will get different request object. And the getSession method returns you the current HttpSession for the associated request. So you can get the current session of the current call by getThreadLocalRequest().getSession(true).



The setAttribute method binds an object to the associated session. It stores the object's value as a Name-Value pair. You can put any thing as the value of the object. A String value or List<String> any thing. Here the name of the object is "useName" and the object is bound to this session with this name.

Now come to the getter method.
public String getUserName()
{
    HttpSession session = getThreadLocalRequest().getSession(true);
    if (session.getAttribute("userName") != null)
    {
        return (String) session.getAttribute("userName");
    }
    else 
    {
        return "";
    }
}

Get the current session in the same way as described for the setter method. The getAttribute method returns the value of the object which is bound with this session with the specific name. Then simply cast it with your desired type.

Thats all. Just call the services according to your requirement. Play with GWT and stay in touched. :-D

Working with GXT(Ext GWT) Grid : Create an Editable Grid

Last week i was so busy that i can not afford to manage time on writing. And i am afraid that whether i can keep my promise on writing a series of tutorials about GXT and GWT or not. In the upcoming days i have to work in six! projects simultaneously. Good thing is that there will be a lot of new things that i can learn and surely i will share those here whenever i get time. Now i will show you how you can make a GXT Grid editable with TextField, ComboBox and Date Picker.

Create a new project named GxtEditableGrid and add GXT library in the project. As like my previous blogs about GXT Grid i have used the same Employee model and TestData class for generating data. You will find the code of these classes here. Go to the onModuleLoad method of GxtEditableGrid class and remove all the auto generated code of this method.

Starting with creating a list of ColumnConfig and a ColumnConfig instance named column. Configure this column to show and edit Employee Name first. To add the editing functionality create a TextField and a CellEditor with this TextField. Then set the CellEditor as the editor of the column.

List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
ColumnConfig column = new ColumnConfig();
column.setId("name");
column.setHeader("Employee Name");
column.setWidth(200);
TextField<String> text = new TextField<String>();  
text.setAllowBlank(false);  
text.setAutoValidate(true);  
column.setEditor(new CellEditor(text));
configs.add(column); 



For the Department column rather than using a TextField we are going to use a ComboBox to edit this field. First create a SimpleComboBox and add the possible values to it.

final SimpleComboBox<String> combo = new SimpleComboBox<String>();  
combo.setTriggerAction(TriggerAction.ALL);  
combo.add("General Administration");  
combo.add("Information Technology");  
combo.add("Marketing");  
combo.add("Accounts"); 

Then create a CellEditor with the SimpleComboBox and set it as the editor of the department column.

CellEditor editor = new CellEditor(combo) {  
@Override  
public Object preProcessValue(Object value) {  
if (value == null) {  
return value;  
}  
return combo.findModel(value.toString());  
}  

@Override  
public Object postProcessValue(Object value) {  
if (value == null) {  
return value;  
}  
return ((ModelData) value).get("value");  
}  
};  

column = new ColumnConfig("department", "Department", 150);
column.setAlignment(HorizontalAlignment.LEFT);
column.setEditor(editor);  
configs.add(column);

For the Designation column configure it like the Employee Name column and for the Salary column set a cell editor with NumberField. That is this field will only accept numeric values.

column = new ColumnConfig("designation", "Designation", 150);
column.setAlignment(HorizontalAlignment.LEFT);
TextField<String> text2 = new TextField<String>();  
text2.setAllowBlank(false);  
text2.setAutoValidate(true);  
column.setEditor(new CellEditor(text2));
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>";
}  
};  
column.setRenderer(checkSalary); 
column.setEditor(new CellEditor(new NumberField()));  
configs.add(column);

To change date field in a Grid with date picker create a DateField, set a date fomat for the DateField and finally set this as the editor for the ColumnConfig.

DateField dateField = new DateField();  
dateField.getPropertyEditor().setFormat(DateTimeFormat.getFormat("MM/dd/y"));

column = new ColumnConfig("joiningdate", "Joining Date", 100);
column.setAlignment(HorizontalAlignment.RIGHT);
column.setEditor(new CellEditor(dateField));  
column.setDateTimeFormat(DateTimeFormat.getMediumDateFormat());
configs.add(column);

To enable the editable functionality of grid you have to create an instance of EditorGrid class instead of a Grid class now. Other things are described in my previous tutorials about GXT Grid.

ListStore<Employee> employeeList = new ListStore<Employee>();
employeeList.add(TestData.getEmployees());
ColumnModel cm = new ColumnModel(configs);

final EditorGrid<Employee> grid = new EditorGrid<Employee>(employeeList, cm);
grid.setStyleAttribute("borderTop", "none");
grid.setAutoExpandColumn("name");
grid.setBorders(true);
grid.setStripeRows(true);

ContentPanel cp = new ContentPanel();
cp.setBodyBorder(false);
cp.setHeading("Employee List");
cp.setButtonAlign(HorizontalAlignment.CENTER);
cp.setLayout(new FitLayout());
cp.setSize(700, 300);
cp.add(grid);
RootPanel.get().add(cp);

That's all. Run the application check the magic GXT. To view the live demo of this tutorial Click here.

editableGrid

Working with GXT(Ext GWT) Grid : Add Grouping Funtionality

Grouping is very helpful when you view a large set of data. It creates a more readable view for the user. GXT provides us with a very easy way of adding grouping functionality with a grid. Here i describe how to add grouping functionality with GXT grid.

Create a new project named GxtGridGrouping and add GXT library in the project. As like my previous blogs about GXT Grid i have used the same Employee model and TestData class for generating data. You will find the code of these classes here. Go to the onModuleLoad method of GxtGridGrouping class and remove all the auto generated code of this method.

First create an instance of GroupingStore, a specialized store implementation which extends the ListStore that provides for grouping models by one of the available fields.

GroupingStore<Employee> employeeList = new GroupingStore<Employee>();  
employeeList.add(TestData.getEmployees());  
employeeList.groupBy("department");   

The groupBy method takes a property of your model by which you want to group your grid. In the example i have grouped the grid by 'department' property. You can change it to 'designation' property and see how it works.

Now define a list of ColumnConfig and a ColumnModel by using this list as before.
List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);   
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>"; 
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

final ColumnModel cm = new ColumnModel(configs); 

Create an instance of GroupView which groups the data based on the GroupStore. Then set it as the view of the Grid.

GroupingView view = new GroupingView();  
view.setForceFit(true);  
view.setGroupRenderer(new GridGroupRenderer() {  
public String render(GroupColumnData data) {  
String f = cm.getColumnById(data.field).getHeader();  
String l = data.models.size() == 1 ? "Item" : "Items";  
return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";  
}  
});  

Grid<Employee> grid = new Grid<Employee>(employeeList, cm);  
grid.setView(view);  
grid.setBorders(true);

Here setForceFit is set true to auto expand the columns to fit the grid width and setGroupRenderer is used to create a heading for the groups.

Finally add the grid to the content panel.

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 420); 
cp.add(grid);  
RootPanel.get().add(cp);



Run the application and see how readable the grid is now. To view the live demo of this tutorial Click here.
gxtGridGrouping

Working with GXT(Ext GWT) Grid : Add Local Pagination Functionality

In my previous blog i have described how to create a simple Grid of GXT.  I have a plan to write a series of blog about other useful functionalities which can be added to the Grid. Here i write down the way of adding local pagination functionality with the Grid.

Create a new project named GxtPagingExample and add GXT library in the project. To create a grid at first you need a base model class and have to generate data for that model. In this tutorial i have used the same Employee model and TestData class for generating data which i used in my previous blog. You will find the code of these classes there.

Now go to the onModuleLoad method of GxtPagingExample class. Remove all the auto generated code of this method. First create an instance of PagingModelMemoryProxy which is a specialized DataProxy that supports paging when the entire data set is in the memory.

PagingModelMemoryProxy proxy = new PagingModelMemoryProxy(TestData.getEmployees());
   PagingLoader loader = new BasePagingLoader(proxy);
   loader.setRemoteSort(true);
   ListStore<Employee> employeeList = new ListStore<Employee>(loader);  
BasePagingLoader is an implementation of the PagingLoader interface which loads data using the proxy.If remote sort is enable then it will allow you to sort between the whole data set otherwise the sorting will be done only between the viewable data set. Then create a ListStore of Employee type.




Now create a PagingToolBar widget then bind it with the loader. It takes the page size in the constructor.
final PagingToolBar toolBar = new PagingToolBar(5);
   toolBar.bind(loader);
   loader.load(0, 5);
The arguments of the load method of PagingLoader are the begin index and page size.

Create a list of ColumnConfig and define each column. Then create a grid and add the grid and the PagingToolBar in a panel.

List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>"; 
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

ColumnModel cm = new ColumnModel(configs);
Grid<Employee> grid = new Grid<Employee>(employeeList, cm); 
grid.setStyleAttribute("borderTop", "none"); 
grid.setAutoExpandColumn("name"); 
grid.setBorders(true); 
grid.setStripeRows(true);

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 300); 
cp.add(grid);  
cp.setBottomComponent(toolBar);
RootPanel.get().add(cp);

Explanation of the above code is written here.
That's all. Run the application and test the pagination functionality. To view the live demo of this tutorial Click here.

Keep yourself updated with the latest GWT technologies (gwt , app engine and gxt)

It’s been long since i have worked with GWT. I have been very busy with my scheduled tasks and can not afford to spend time on investing the features of this outstanding web technology.  Today i have sit with it and found that everything is required to be updated. The SDK for GWT, Google App Engine and the Ext GWT Library (The world is running fast?huh). I have updated all these and  here i write down the procedure for eclipse 3.4.

Download GWT version 1.7 from here and Google App Engine SDK 1.2.2 from here. Unzip the folders then open the Window->Preference window of eclipse.

Expand the Google menu from the left tree menu.  Select the Web Toolkit menu and it will show you the previous version of GWT. Click on the Add Button and select the unzipped folder as the installation directory.  Now check the latest SDK so that it will be the default SDK for the newly created projects.

gwtupdate1

 

Now select the App Engine menu and follow the steps stated above to add the latest version of the SDK.

You are now ready to use the latest version of GWT and Google App Engine SDK.

To use the latest version of Ext GWT library download this from here and follow my previous blog about how to use it in your GWT project.

Getting started with GWT : Create your first GWT application in Eclipse 3.4

To my mind GWT is going to take the lead among the web application development tools. So this is the high time to start learning about GWT. Here I describe you how to create your first GWT application in Eclipse 3.4 (Ganymede).

If you have not installed Google plugin and SDK for eclipse please go to this page and follow the instructions.

Create your project
Select File-> New-> Web Application project. Enter "FirstGwtApp" for your project name and "com.ratul.FirstGwtApp" for the package name.



Create GWT entry point

Now you have to create an Entry point class which is similar to the main method in Java.
Right click on the "com.ratul.FirstGwtApp.client" and select New-> Class. Enter "HelloWorld" as the name of the class.



This class must implement the interface "com.google.gwt.core.client.EntryPoint".
So click on the Add button and write "entrypoint" in the choose interface text field.
Select the matching item.



Here is the code of the HelloWorld class

package com.ratul.FirstGwtApp.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.RootPanel;

public class HelloWorld implements EntryPoint {

@Override
public void onModuleLoad() {
Label label = new Label("Enter your name:");
final TextBox textBox = new TextBox();
Button button = new Button("Click Here");
button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.alert("Hello "+ textBox.getText());
}
});

RootPanel.get().add(label);
RootPanel.get().add(textBox);
RootPanel.get().add(button);
}
}


Now change the FirstGwtApp.gwt.xml in package com.ratul.FirstGwtApp to set the HelloWorld class as the entry point class of your application.



Create a Start HTML page

In the war folder you will find a file, named FirstGwtApp.html. Between the body tag write the following code

<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabindex="-1" style="border: 0pt none ; position: absolute; width: 0pt; height: 0pt;"></iframe>

<h1>Welcome to my first GWT Application</h1>




Configure the web.xml

Go to war-> WEB-INF folder and there you will find a web.xml file. The Google Plug-in created this configuration file and placed a reference to a servlet.
Set the FirstGwtApp.html as the welcome file of your application.



You are only one step away from running your first GWT application.

Run GWT application

To run your application right-click the project and select Run As -> "Web application".

The result will be like this.



Enter your name in the text field and click on the button. Your name will be appeared in the alert window :).


Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers