Super dev mode is one of the feature given in GWT after 2.5 version.
Showing posts with label GWT. Show all posts
Showing posts with label GWT. Show all posts
Thursday, 3 July 2014
Thursday, 19 June 2014
How do upgrade GWT in Eclipse
How do upgrade GWT in Eclipse
- Download the GWT SDK(s) you need from https://developers.google.com/web-toolkit/versions
- Extract it anywhere you like
- In Eclipse Preferences > Google > Web Toolkit, use the "Add..." button and navigate to the GWT SDK directory
- Then, in each Eclipse project's properties page (Project > Properties > Google > Web Toolkit), you can choose one of your installed SDKs.
Labels:
GWT
Sunday, 23 February 2014
How to Use RichTextToolbar in GWT
How to Use RichTextToolbar in GWT
If you’ve ever tried to use the RichTextToolbar that is showcased in the Gwt Showcase, you will quickly find out that it’s not actually built into GWT. Many GWT developers have experienced this WTFery, as their hopes to conveniently import RichTextToolbar have been dashed. It is supposedly so that developers are not locked into using that toolbar, but of course, a good default is better than no default…As you can see here, multiple bugs have been filed about this exact issue since 2008, to no avail! Drats, I guess it is one of those things that has low priority because there’s a work-around, but it does affect a good number of developers, which should count for something.
Anyway, to use it in your code:
- Navigate to <path>/gwt-2.0.3/samples/Showcase/src/com/google/gwt/sample/showcase/client/content/text on your computer, and you should see a bunch of icons, RichTextToolbar.java and RichTextToolbar$Strings.properties.
- Copy RichTextToolbar.java and RichTextToolbar$Strings.properties and paste them into your source code folder and modify the package names accordingly.
- Copy all the icons and paste them somewhere (I created a folder <project>/client/icon)
- In RichTextToolbar.java, above each “Image Resource…”, you will need to indicate the source of the image. For example,
@Source(“../icons/bold.gif”)
ImageResource bold();
if the directory you copied RichTextToolbar.java is under client.
That’s it, a little annoying, but hopefully it will find its way into GWT itself soon, though don’t hold your breath.
Also, you can easily play around with the Toolbar– I removed the bottom row of ListBoxes that give you lots of control over background and foreground colors, font and font sizes (I don’t want my users to have that much control over how my website looks!), and it ends up looking like this:
Hope that helps, and that it will save a few people some time!
Related posts:
Labels:
GWT
Thursday, 23 January 2014
GWT KeyPressHandler getCharCode issues
GWT KeyPressHandler getCharCode issues
- event.getNativeEvent().getKeyCode()
- KeyCodes.KEY_ENTER=13
This code returns the '10' in chrome so the following code is not working.
- if(event.getNativeEvent().getKeyCode()==KeyCodes.KEY_ENTER)
This code returns the '13' in firefox so the following code is working.
so like the code like following for both chrome and firefox
- if(event.getNativeEvent().getKeyCode()==13)
- {
- //Do something
- }else if(event.getNativeEvent().getKeyCode()==10)
- {
- //Do something
- }
Labels:
GWT
Tuesday, 19 November 2013
How to convert java.util.Date to String in GWT client side
How to convert java.util.Date to String in GWT client side
In GWT we use SimpleDateFormat in Client side it throws the compiling error.
so use DateTimeFormat instead of SimpleDateFormat.
String currentdate="";try{DateTimeFormat dateFormat =DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");currentdate= dateFormat.format(new Date());} catch (Exception e){e.printStackTrace();}
Labels:
GWT
Thursday, 16 May 2013
how to submit datebox inside form-GWT
how to submit datebox inside form-GWT
The issue is DateBox doesn't have the "name" attribute:
You can set name attribute to DateBox, since it has TextBox:
DateBox dateBox = new DateBox();
dateBox.getTextBox().setName(name);
Labels:
GWT
Monday, 15 April 2013
GWT event listeners
GWT event listeners
GWT defines event listeners that you can attach to your widgets to monitor browser events. Event Listeners are just interfaces that you can implement in your widget. If you want to trap mouse click events, then your widget should implement the
You can create a new anonymous
ClickListener interface and define theonClick(Widget sender) method. The code inside this method will be fired every time the user clicks on your widget.You can create a new anonymous
ClickListener every time you want to assign it to a widget as given in the Hello gwt example.But this results in localized code and lesser code reusability. Let us say we want to add another widget (a HTML link), which has to run the same code as in thebutton.addClickListener(new ClickListener() { public void onClick(Widget sender) { processData(sender.getText()); reportData(sender.getText()); logResults(); } });
onClick() method. We would be using the addClickListenermethod for this link and would be rewriting the same code again separately. And if we need to add another method in the onClick() method code between processData() and reportData() we will have to change each instance of onClick().Alternatively, we can implement the listeners in the container widget to handle the events of contained widgets as shown below, making the code more reusable.
With this approach, if we want to add apublic class MainPanel extends Composite implements ClickListener{ private Button button=new Button("Button"); public MainPanel(){ //... button.addClickListener(this); } public void onClick(Widget sender){ if(sender==button){ processData(sender.getText()); reportData(sender.getText()); logResults(); } } }
HTML widget link that implements the same function, we would just have to add the lineinlink.addClickListener(this);
MainPanel() and modify one line in the onClick(Widget sender)methodGiven Below is a listing of GWT Event listeners for handling various events:if(sender==button||sender==link)
| Listener | Event notifications | Methods Defined |
| HistoryListener | Changes to Browser History | onHistoryChanged(String historyToken) |
| WindowCloseListener | Window Closure Events | onWindowClosed() onWindowClosing() |
| WindowResizeListener | Window Resizing Events | onWindowResized(int width, int height) |
| ChangeListener | fires when a widget changes | onChange(Widget sender) |
| ClickListener | fires when a widget receives a 'click' | onClick(Widget sender) |
| FormHandler | fires on receiving Form events from the FormPanel to which it is attached | onSubmit(FormSubmitEvent event) onSubmitComplete( FormSubmitCompleteEvent event) |
| FocusListener | Focus Events | onFocus(Widget sender) onLostFocus(Widget sender) |
| KeyBoardListener | Keyboard Events | onKeyDown(Widget sender, char keycode, int modifiers) onKeyPress(Widget sender, char keycode, int modifiers) onKeyUp(Widget sender, char keycode, int modifiers) |
| LoadListener | listens to 'load' event of a widget | onLoad(Widget Sender) onError(Widget Sender) |
| MouseListener | listens to mouse events of a widget | onMouseEnter(Widget sender) onMouseLeave(Widget sender) onMouseDown(Widget sender, int x, int y) onMouseUp(Widget sender, int x, int y) onMouseMove(Widget sender, int x, int y) |
| PopupListener | listens to the events of a PopupPanel widget | onPopupClosed(PopupPanel sender, boolean autoClose) |
| ScrollListener | listens to Scroll events | onScroll(Widget widget, int scrollLeft, int scrollTop) |
| TableListener | listens to events pertaining to a Table widget | onCellClicked( SourcesTableEvents sources, int row, int cell) |
| TabListener | listens to the events of a Tab Widget | onBeforeTabSelected( SourcesTabEvents sender, int tabIndex) onTabSelected( SourcesTabEvents sender, int tabIndex) |
| TreeListener | listens to the events of a Tree Widget | onTreeItemSelected( TreeItem item) onTreeItemChanged( TreeItem item) |
The
Button widget defines the addClickListener method which attaches a ClickListener object to it. Similarly, the Tree widget defines theaddTreeListener method. Not all event listeners are available for all widgets - for example, the addMouseListener method is not defined for aDockPanel Widget. One way to add the MouseListener functionality to thisDockPanel is to create a composite that includes a FocusPanel widget (which supports addMouseListener) and wrap the DockPanel widget within it.
Labels:
GWT
Monday, 18 March 2013
JSon Client Code
JSon Client Code
package com.javanotes2all.client;
import java.util.Set;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Entry point classes define onModuleLoad().
*/
public class Test implements EntryPoint {
public void onModuleLoad() {
String firstJSON="{'wz':'123','java':111,'other':['zhangsan','lisi'],'obj':{'name':'jam','age':18,'married':true,'child':null,'likes':['cat','dog']}}";
JSONValue value=JSONParser.parse(firstJSON);
System.out.println(value.toString());
JSONObject o1= value.isObject();
JSONValue v1=o1.get("wz");
System.out.println("v1 "+v1.isString());
JSONValue v2=o1.get("java");
System.out.println("v2 "+v2.isNumber());
JSONValue v3=o1.get("other");
System.out.println("v3 "+v3.isArray());
JSONObject object=new JSONObject();
object.put("a", JSONBoolean.getInstance(true));
object.put("b", new JSONString("yes"));
object.put("c", new JSONNumber(1.23));
object.put("d",JSONNull.getInstance());
System.out.println("v6 "+object.toString());
JSONArray v33=v3.isArray();
int arraylength=v33.size();
v33.set(arraylength, new JSONString("wangwu"));
System.out.println("v3 "+v3.isArray());
JSONObject v4=o1.get("obj").isObject();
System.out.println("v4 "+v4.toString());
System.out.println("v44 "+v4.get("name").isString());
String jsJSON=jsmethod();
JSONObject jsobj=JSONParser.parse(jsJSON).isObject();
System.out.println("v5 "+jsobj);
System.out.println("v55 "+jsobj.get("name").isString());
RootPanel.get().add(new Label("success!!!"));
}
public native String jsmethod()/*-{
var code="{'name':'Tom','age':18.0,'married':true}";
return code;
}-*/;
}
Tuesday, 12 February 2013
How can I check if the given URL of an image exists using GWT?
How can I check if the given URL of an image exists using GWT?
Image img = new Image("some_url/img.jpg"); img.addErrorHandler(new ErrorHandler() { @Override public void onError(ErrorEvent event) { System.out.println("Error - image not loaded."); } });
Labels:
GWT
Saturday, 2 February 2013
Adding CAPTCHA to your GWT application
Adding CAPTCHA to your GWT application
What is CAPTCHA?
In a world full of malicious bots, what can you do to protect your precious web application? One of the basic things that you really should do is add CAPTCHA capabilities to it. If you are not familiar with the (rather bizarre sounding) term, CAPTCHA is a simplistic way to ensure that a user is actually a real person, and not a computer. This can be done by challenging the user and asking from him to provide a response to a “problem”. Because computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. The most common way is to ask the user to type letters or digits from a distorted image that appears on the screen.
Labels:
GWT
Thursday, 17 January 2013
GWT Paging Scroll Table
GWT Paging Scroll Table
Introduction
I've been doing a lot of development lately with the Google Web Toolkit. One of the things I clamored for was a decent grid or table that had good performance, sortable columns, and pagination. Surprisingly, there are few options out there (to date), for GWT developers. There are some standard widgets in GWT like FlexTable and Grid, and these widgets work great for small tasks, but they don't support pagination, scrolling, or large data sets. GWT also has a ScrollPanel, but again that lacks pagination and support for large data sets.
Labels:
GWT
Monday, 17 December 2012
Black preview in GWT Designer in Eclipse on Ubuntu
Black preview in GWT Designer in Eclipse on Ubuntu
Update: It seems like the problem was fixed. No need to install GWT Designer anymore, you can just install Google Plugin for Eclipse then install libwebkit 1.0, since it’s not installed by default.
libwebkit 1.0 can be installed by running the following command in the terminal (both 32bit and 64bit):
sudo apt-get install libwebkitgtk-1.0-0
see more clickhere.
Labels:
GWT
Friday, 7 December 2012
Application Flow for GWT
During
its bootstrap process, a Google Web Toolkit application goes through
a series of sometimes cryptically-named files. These files, generated
by the GWT Compiler, usually seem strange to developers new to GWT.
To effectively deploy a GWT application, however, it is necessary to
understand these files so that they can be placed appropriately on
the web server.
The
important files produced by the GWT Compiler are:
- <Module Name>.nocache.js
- <alphanumeric>.gwt.rpc
Each
of the items listed above is described below. However, first it's
important to understand the concept of deferred binding since that
notion is at the heart of the bootstrap process injected into
the <Module
Name>.nocache.js file,
so you might want to read a bit about deferred
binding before
continuing.
Before
explaining what each file does, it's also useful to summarize the
overall bootstrap procedure for a GWT application:
- The browser loads and processes the host HTML page.
- When the browser encounters the page's <script src="<Module Name>.nocache.js"> tag, it immediately downloads and executes the JavaScript code in the file.
- The .nocache.js file contains JavaScript code that resolves the Deferred Binding configurations (such as browser detection, for instance) and then uses a lookup table generated by the GWT Compiler to locate one of the .cache.html files to use.
- The JavaScript code in .nocache.js then creates a hidden <iframe>, inserts it to the host page's DOM, and loads the .cache.html file into that iframe.
- The .cache.html file contains the actual program logic of the GWT application.
That's
the process in a nutshell. For an example the bootstrap process for a
complete GWT application, check out the Developer
Guide example.
The sections below describe each of the GWT application files in
detail.
The .cache.html Files
The
"cache" files contain your application's logic. If you were
to look inside a .cache.html file,
you would see that it is JavaScript code wrapped in a thin HTML
wrapper. You might wonder why the GWT Compiler doesn't simply emit it
as a JavaScript .js file. The reason for this is that certain
browsers do not correctly handle compression of pure-JavaScript files
in some circumstances. This would effectively mean that users
unfortunate enough to be using such a browser would download the .js
file uncompressed. Since the GWT mantra is no-compromise,
high-performance AJAX code, the GWT Compiler wraps the JavaScript in
an HTML file to wiggle around this browser quirk.
They
are named according to the MD5 sum of their contents. This guarantees
deterministic behavior by the GWT Compiler: if you recompile your
application without changing code, the contents of the output will
not change, and so the MD5 sums will remain the same. Conversely, if
you do change your source code, the output JavaScript code will
likewise change, and so the MD5 sums and thus the filenames will
change.
Because
of this uniqueness guarantee, it is safe (and indeed preferable) for
browsers to cache these files, which is reflected in
their .cache.html file
extension.
The .nocache.js File
The
"nocache" file is where Deferred
Binding occurs.
Before the application can run, any dynamically-bound code must be
resolved. This might include browser-specific versions of classes,
the specific set of string constants appropriate to the user's
selected language, and so on. In Java, this would be handled by
simply loading an appropriate service-provider class that implements
a particular interface. To maximize performance and minimize download
size, however, GWT does this selection up-front in the "nocache"
file.
The
reason the file is named ".nocache.html" is to indicate
that the file should never be cached. That is, it must be downloaded
and executed again each time the browser starts the GWT application.
The reason it must be re-downloaded each time is that the GWT
Compiler regenerates it each time, but under the same file name. If
the browsers were allowed to cache the file, they might not download
the new version of the file, when the GWT application was recompiled
and redeployed on the server. To help prevent caching, the code
in gwt.js actually
appends an HTTP GET parameter on the end of file name containing a
unique timestamp. The browser interprets this as a dynamic HTTP
request, and thus should not load the file from cache.
The .gwt.rpc File
In
previous versions of GWT, if your application used GWT RPC, the types
that you wanted to serialize across the wire had to implement
the IsSerializable interface.
As of GWT 1.4, types that implement
the java.io.Serializable interface
now also qualify for serialization over RPC, with some conditions.
One
of these conditions is that the types that you would like to
serialize over the wire must be included in the .gwt.rpc file
generated by the GWT compiler. The .gwt.rpc file serves as a
serialization policy to indicate which types
implementing java.io.Serializable are
allowed to be serialized over the wire. For more details on this and
other conditions to use Serializable types
in GWT RPC, check out this FAQ.
Labels:
GWT
MVC or MVP Pattern – Whats the difference?
MVC or MVP Pattern – Whats the difference?
Over the years I have mentored many developers on using design patterns and best practices. One question that keeps coming up over and over again is: What are the differences between the Model View Controller (MVC) and Model View Presenter (MVP) patterns? Surprisingly the answer is more complex than what you would suspect. Part of reasons I think many developers shy away from using either pattern is the confusion over the differences.
Before we dig into the differences let’s examine how the patterns work and the key benefits to using either one. Both (MVC & MVP) patterns have been use for several years and address a key OO principal namely separation of concerns between the UI and the business layers. There are a number of frameworks is use today that based on these patterns including: JAVA Struts, ROR, Microsoft Smart Client Software Factory (CAB),Microsoft Web Client Software Factory, and the recently announced ASP.Net MVC framework.
Model View Controller (MVC) Pattern
The MVC pattern is a UI presentation pattern that focuses on separating the UI (View) from its business layer (Model). The pattern separates responsibilities across three components: the view is responsible for rending UI elements, the controller is responsible for responding to UI actions, and the model is responsible for business behaviors and state management. In most implementation all three components can directly interact with each other and in some implementations the controller is responsible for determining which view to display (Front Controller Pattern),
Model View Presenter (MVP) Pattern
The MVP pattern is a UI presentation pattern based on the concepts of the MVC pattern. The pattern separates responsibilities across four components: the view is responsible for rending UI elements, the view interface is used to loosely couple the presenter from its view, the presenter is responsible for interacting between the view/model, and the model is responsible for business behaviors and state management. In some implementations the presenter interacts with a service (controller) layer to retrieve/persist the model. The view interface and service layer are commonly used to make writing unit tests for the presenter and the model easier.
Key Benefits
Before using any pattern a developers needs to consider the pros and cons of using it. There are a number of key benefits to using either the MVC or MVP pattern (See list below). But, there also a few draw backs to consider. The biggest drawbacks are additional complexity and learning curve. While the patterns may not be appropriate for simple solutions; advance solutions can greatly benefit from using the pattern. I’m my experience a have seen a few solutions eliminate a large amount of complexity but being re-factored to use either pattern.
· Loose coupling – The presenter/controller are an intermediary between the UI code and the model. This allows the view and the model to evolve independently of each other.
· Clear separation of concerns/responsibility
o UI (Form or Page) – Responsible for rending UI elements
o Presenter/controller – Responsible for reacting to UI events and interacts with the model
o Model – Responsible for business behaviors and state management
· Test Driven – By isolating each major component (UI, Presenter/controller, and model) it is easier to write unit tests. This is especially true when using the MVP pattern which only interacts with the view using an interface.
· Code Reuse – By using a separation of concerns/responsible design approach you will increase code reuse. This is especially true when using a full blown domain model and keeping all the business/state management logic where it belongs.
· Hide Data Access – Using these patterns forces you to put the data access code where it belongs in a data access layer. There a number of other patterns that typical works with the MVP/MVC pattern for data access. Two of the most common ones are repository and unit of work. (See Martin Fowler – Patterns of Enterprise Application Architecture for more details)
· Flexibility/Adaptable – By isolating most of your code into the presenter/controller and model components your code base is more adaptable to change. For example consider how much UI and data access technologies have changed over the years and the number of choices we have available today. A properly design solution using MVC or MVP can support multi UI and data access technologies at the same time.
Key Differences
So what really are the differences between the MVC and MVP pattern. Actually there are not a whole lot of differences between them. Both patterns focus on separating responsibility across multi components and promote loosely coupling the UI (View) from the business layer (Model). The major differences are how the pattern is implemented and in some advanced scenarios you need both presenters and controllers.
Here are the key differences between the patterns:
· MVP Pattern
o View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
o Easier to unit test because interaction with the view is through an interface
o Usually view to presenter map one to one. Complex views may have multi presenters.
· MVC Pattern
o Controller are based on behaviors and can be shared across views
o Can be responsible for determining which view to display (Front Controller Pattern)
Hopefully you found this post interesting and it helped clarify the differences between the MVC and MVP pattern. If not, do not be discouraged patterns are powerful tools that can be hard to use sometimes. One thing to remember is that a pattern is a blue print and not an out of the box solutions. Developers should use them as a guide and modify the implementation according to their problem domain.
Labels:
GWT
What are MVP and MVC and what is the difference?
What are MVP and MVC and what is the difference?
Model-View-Presenter
In MVP,
the Presenter contains the UI business logic for the View. All
invocations from the View delegate directly to Presenter. The
Presenter is also decoupled directly from the View and talks to it
through an interface. This is to allow mocking of the View in a unit
test. One common attribute of MVP is that there has to be a lot of
two-way dispatching. For example, when someone clicks the "Save"
button, the event handler delegates to the Presenter's "OnSave"
method. Once the save is completed, the Presenter will then call back
the View through its interface so that the View can display that the
save has completed.
MVP
tends to be a very natural pattern for achieving separated
presentation in Web Forms. The reason is that the View is always
created first by the ASP.NET runtime. You can find
out more about both variants.
Two primary variations
Passive
View: The
View is as dumb as possible and contains almost zero logic. The
Presenter is a middle man that talks to the View and the Model. The
View and Model are completely shielded from one another. The Model
may raise events, but the Presenter subscribes to them for updating
the View. In Passive View there is no direct data binding, instead
the View exposes setter properties which the Presenter uses to set
the data. All state is managed in the Presenter and not the View.
- Pro: maximum testability surface; clean separation of the View and Model
- Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising
Controller: The
Presenter handles user gestures. The View binds to the Model directly
through data binding. In this case it's the Presenter's job to pass
off the Model to the View so that it can bind to it. The Presenter
will also contain logic for gestures like pressing a button,
navigation, etc.
- Pro: by leveraging databinding the amount of code is reduced.
- Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller
In
the MVC,
the Controller is responsible for determining which View is displayed
in response to any action including when the application loads. This
differs from MVP where actions route through the View to the
Presenter. In MVC, every action in the View correlates with a call to
a Controller along with an action. In the web each action involves a
call to a URL on the other side of which there is a Controller who
responds. Once that Controller has completed its processing, it will
return the correct View. The sequence continues in that manner
throughout the life of the application:
Action in the View -> Call to Controller -> Controller Logic -> Controller returns the View.
One
other big difference about MVC is that the View does not directly
bind to the Model. The view simply renders, and is completely
stateless. In implementations of MVC the View usually will not have
any logic in the code behind. This is contrary to MVP where it is
absolutely necessary as if the View does not delegate to the
Presenter, it will never get called.
Presentation Model
One
other pattern to look at is the Presentation
Model pattern.
In this pattern there is no Presenter. Instead the View binds
directly to a Presentation Model. The Presentation Model is a Model
crafted specifically for the View. This means this Model can expose
properties that one would never put on a domain model as it would be
a violation of separation-of-concerns. In this case, the Presentation
Model binds to the domain model, and may subscribe to events coming
from that Model. The View then subscribes to events coming from the
Presentation Model and updates itself accordingly. The Presentation
Model can expose commands which the view uses for invoking actions.
The advantage of this approach is that you can essentially remove the
code-behind altogether as the PM completely encapsulates all of the
behaviour for the view. This pattern is a very strong candidate for
use in WPF applications and is also called Model-View-ViewModel.
Labels:
GWT
Saturday, 17 November 2012
Gwt Json
Gwt Json
Step1: Create the GWT project
Step2: Create the Servlet in server package
example:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JsonStockData extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try
{
PrintWriter out = resp.getWriter();
out.println('[');==================//Start of the json data
String name = req.getParameter("q");
String encryption=byteArrayToHexString(computeHash(name));
out.println(" {");===============//Start of the object
out.print(" \"name\": \"");=========//key for pojoclass variable
out.print(name+"\");=================//value for pojoclass variable
out.println(",");===================//separetion for the variables
out.print(" \"encryption\": \"");
out.print(encryption+"\"");
out.println(" },");===============//end of the object
out.println(']');==================//end of the json data
out.flush();
}catch(Exception e)
{
System.out.println(e);
}
}
public byte[] computeHash(String x) throws Exception
{
java.security.MessageDigest d =null;
d = java.security.MessageDigest.getInstance("SHA-1");
d.reset(); d.update(x.getBytes());
return d.digest();
}
public String byteArrayToHexString(byte[] b)
{
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++)
{
int v = b[i] & 0xff;
if (v < 16)
{
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
}
Step 3: Add the following data in web.xml
example:
<servlet>
<servlet-name>jsonStockData</servlet-name>
<servlet-class>com.json.server.JsonStockData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jsonStockData</servlet-name>
<url-pattern>/jsonproject/jsonproj</url-pattern>
</servlet-mapping>
Step4: Write the jsonobject class in client package
example:
import com.google.gwt.core.client.JavaScriptObject;
public class jsondata extends JavaScriptObject
{
protected jsondata(){}
// JSNI methods to get stock data.
public final native String getName() ======//javaobject see servlet(step2)
/*-{ return this.name; }-*/;
public final native String getEncryption()
/*-{ return this.encryption; }-*/;
}
Step 5: Call the url in the client side
Step 5.1: formate the url
example:
private static final String JSON_URL = GWT.getModuleBaseURL() + "jsonproj?q=";
Step 5.2:Add the query Strings
example:
String url = JSON_URL+”name”;
url = URL.encode(url);
Step 5.3:Send request to the server
example:
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
Window.alert("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response)
{
if (200 == response.getStatusCode())
{
Window.alert(response.getText());
updateTable(asArrayOfJsonData(response.getText()));
}
else {
Window.alert("Couldn't retrieve JSON2 (" + response.getStatusText()
+ ")");
}
}
});
} catch (RequestException e) {
Window.alert("Couldn't retrieve JSON1");
}
Internal methods for the above code:
==========This method for the getting and divide the json objects=====
private void updateTable(JsArray<jsondata> jsArray)
{
for (int i = 0; i < jsArray.length(); i++) {
updateTable(jsArray.get(i));
}
}
==========This method for getting the each object and values=====
private void updateTable(jsondata jsondata)
{
Window.alert(jsondata.getName()));
Window.alert(jsondata.getEncryption()));
}
==========Convert the string of JSON into JavaScript object=====
private final native JsArray<jsondata> asArrayOfJsonData(String json)
/*-{
return eval(json);
}-*/;
Labels:
GWT






