GWT (Google Web Toolkit)帮助开发者使用Java来开发复杂的JavaScript应用。很多出色的产品,如Google AdSense,Google AdWords等都是使用GWT开发的。这里介绍下如何创建第一个GWT应用,以及如何通过GWT来创建一个简单的Web扫描应用。
参考原文:Building Web Scanning Applications with GWT
GWT下载安装
使用Eclipse+GWT插件来搭建开发环境。请确认系统是否安装了JDK 7。
-
Eclipse 4.4 (Luna) > https://dl.google.com/eclipse/plugin/4.4
-
Eclipse 4.3 (Kepler) > https://dl.google.com/eclipse/plugin/4.3
-
Eclipse 3.8/4.2 (Juno) > https://dl.google.com/eclipse/plugin/4.2
插件安装方法:
-
运行Eclipse
-
点击Help > Install New Software…
-
点击Add…,添加地址http://dl.google.com/eclipse/plugin/4.4
创建第一个GWT应用
点击插件按钮,创建一个工程WebTwainDemo:
输入包名com.dynamsoft.sample.WebTwainDemo:
现在运行应用。在第一次运行的时候,会看到Chrome需要安装插件:
安装之后刷新页面,程序可以正常运行了:
使用GWT和DWT创建Web扫描应用
找到Dynamic Web TWAIN的安装目录{Dynamic Web TWAIN Installation Path}\Dynamic Web TWAIN SDK 10.1.1 Trial\Samples\Getting Started。拷贝Resources目录到工程的war目录下。接下来做一些代码修改。
WebTwainDemo.html
包含两个js资源文件:
1
2
|
<script type=
"text/javascript"
src=
"Resources/dynamsoft.webtwain.initiate.js"
> </script>
<script type=
"text/javascript"
src=
"Resources/dynamsoft.webtwain.config.js"
> </script>
|
添加DWT容器:
1
|
<
div
id
=
"dwtcontrolContainer"
></
div
>
|
添加按钮容器:
1
|
<
div
id
=
"scanButtonContainer"
></
div
>
|
比较代码可以发现。使用GWT开发,HTML文件中不需要添加按钮元素和JS代码。
WebTwainDemo.java
找到入口函数onModuleLoad(),创建一个按钮实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
final
Button scanButton =
new
Button(
"Scan"
);
scanButton.addStyleName(
"scanButton"
);
RootPanel.get(
"scanButtonContainer"
).add(scanButton);
class
TwainHandler
implements
ClickHandler {
public
void
onClick(ClickEvent event) {
acquireImage();
}
private
void
acquireImage() {
nativeAcquireImage();
}
}
TwainHandler twainHandler =
new
TwainHandler();
scanButton.addClickHandler(twainHandler);
|
通过JSNI,使用Java调用JavaScript代码:
1
2
3
4
5
6
7
|
public
static
native void nativeAcquireImage()
/*-{
var DWObject = $wnd.Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'.
DWObject.IfDisableSourceAfterAcquire = true; // Source will be closed automatically after acquisition.
DWObject.SelectSource(); // Select a Data Source (a device like scanner) from the Data Source Manager.
DWObject.OpenSource(); // Open the source. You can set resolution, pixel type, etc. after this method. Please refer to the sample 'Scan' -> 'Custom Scan' for more info.
DWObject.AcquireImage(); // Acquire image(s) from the Data Source. Please NOTE this is a asynchronous method. In other words, it doesn't wait for the Data Source to come back.
}-*/
;
|
现在刷新一下测试页面,扫描应用已经可以运行了。
视频
源码
https://github.com/DynamsoftRD/DWT-with-Web-App-Framework/tree/master/gwt
1
|
git clone https://github.com/DynamsoftRD/DWT-with-Web-App-Framework.git
|