Javascript failing to see java function - java

I'm embedding an applet in a web page and trying to call a function in the applet but get the error "Object doesn't support property or method 'setDestination' when I click the button and the "doit()" function is called. The applet is loaded and on the screen.
Java code (compiled and put into a signed jar named webcam.jar):
import javax.swing.JApplet;
public class MyAppletLauncher extends JApplet {
private JarClassLoader jcl;
public void setDestination()
{
System.out.println("MyAppletLauncher: setdestination!");
System.out.println(url);
}
#Override
public void init() {
jcl = new JarClassLoader();
try {
jcl.initApplet("webcam", this);
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void start() {
jcl.startApplet();
}
#Override
public void stop() {
jcl.stopApplet();
}
#Override
public void destroy() {
jcl.destroyApplet();
}
} // class MyAppletLauncher
Here's the HTML:
<HTML><BODY>
<applet id=cameraapplet name="camerax" code="MyAppletLauncher.class" height="100%" width="100%" archive="webcam.jar">
</applet>
<SCRIPT type="text/javascript">
function doit() {
alert(1);
document.camerax.setDestination(); // Dies on this line
alert(2);
}
</Script>
<input type=button onclick='doit();'>
</BODY></HTML>

Use the applet id to get a reference to the applet object:
document.getElementById("cameraapplet").setDestination();
Note however that the <applet> tag is not supported by HTML5. Read this article on how to use
<embed> or <object> for Java applets.

Related

Wicket, modify HTML <body> element

I want to modify the HTML body tag when I open a Wicket-Bootstrap Modal. What I'm trying to achieve is <body class="modal-open"> instead of <body>
Using Wicket 8 M8 , I have this code:
owsImportDialog = new MyModalBootstrapDialog("owsImportDialog"
, new CompoundPropertyModel<>(new BopOwsTO())) {
#Override
void importOws(AjaxRequestTarget target, IModel<BopOwsTO> owsModel) {
appendCloseDialogJavaScript(target);
BopOwsTO owsTo = owsModel.getObject();
try {
importOwsCapabilities(owsTo);
owsViewDialog.header(Model.of("OWS anzeigen"))
.setModel(Model.of(owsTo.getServiceId()));
owsViewDialog.appendShowDialogJavaScript(target);
}
catch (OwsCapsImportException e) {
String localizedMessage = e.getLocalizedMessage();
importAlert.setModelObject(localizedMessage);
importAlert.appendShowDialogJavaScript(target);
error(localizedMessage);
}
finally {
target.appendJavaScript("document.getElementsByTagName('body')[0]" +
".setAttribute('class', 'modal-open');");
// target.appendJavaScript("document.body.setAttribute('class', 'modal-open');");
// target.prependJavaScript("document.body.setAttribute('class', 'modal-open');");
// target.appendJavaScript("alert('Hallo');");
// owsViewDialog is a child of owsView WebMarkupContainer
target.add(owsView, feedback);
}
}
#Override
void saveOws(AjaxRequestTarget target, IModel<BopOwsTO> owsModel)
{ }
#Override
void cancel(AjaxRequestTarget target)
{ }
};
If the line target.appendJavaScript("alert('Hallo');"); is active I actually see the alert window.
I also tried this code in the page class:
#Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
PackageResourceReference resourceReference = new PackageResourceReference(
getClass(), "../css/BuiOwsPage.css");
CssReferenceHeaderItem cssRef = CssReferenceHeaderItem.forReference(resourceReference);
response.render(cssRef);
response.render(OnLoadHeaderItem
.forScript("document.body.setAttribute('class', 'modal-open');"));
}
But none of my attempts was succesful.
Update
The answer of #martin-g didn't solve the issue.
I'm quite sure that the problem is caused by the sequence of these statements:
{
appendCloseDialogJavaScript(target);
...
try {
owsViewDialog.appendShowDialogJavaScript(target);
....
}
catch { ... }
finally {
target.add(owsView, feedback);
}
}
When this modal is closed because of appendCloseDialogJavaScript() ,
the class modal-open is erased from the class attribute of the <body> .
Then owsViewDialog opens, but modal-open isn't inserted in class, no matter if I append the snippet jQuery(document.body).addClass('modal-open') or not. The missing modal-open means that the page can't be scrolled.
Since Wicket and Bootstrap are used then jQuery is also available. I would recommend you to use jQuery(document.body).addClass('modal-open').
There must be a reason why jQuery has both addClass() and attr()!

minify html and js in jersey Interceptor

used jersey mvc and jsp, all requests to html or js files did through #Template or Viewable.
example;
#GET
#Path(JS_URL + "{type}")
#Template(name = "grid")
#Produces("application/javascript")
public Response buildJSGrid(#DefaultValue("") #PathParam("type") String type) {
Grid grid = new Grid(type);
....
return Response.ok(grid).build();
}
where grid is grid.jsp file with pure javascript inside
<%# page contentType="application/javascript;charset=UTF-8" language="java" %>
.....
also possible other variant with html and js, example;
#GET
#Path(FORM_URL + "{type}")
#Template(name = "form")
#Produces(MediaType.TEXT_HTML)
public Response buildAccountForm(#DefaultValue("") #PathParam("type") String type) {
Form form = new Form(type);
....
return Response.ok(form).build();
}
where form is form.jsp with html and js inside <script>..</script>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
...
i need to minify result js and html/js before send to client, i try to use https://code.google.com/archive/p/htmlcompressor/ lib, but there need to pass String to htmlCompressor.compress(input);
tried use WriterInterceptor
public class MinifyJsInterceptor implements WriterInterceptor {
#Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
final OutputStream outputStream = context.getOutputStream();
// here need to convert outputStream to InputStream and after to String ?
// result string to htmlCompressor.compress(resultString);
// after that convert result minify string back to resultOutputStream and set to context ?
context.setOutputStream(new GZIPOutputStream(resultOutputStream));
is it correct way ? and i can`t converts that outputstream to string
thanks
--update
answer to questions;
html + js mean that in some jsp are html markup and js code
<div id="form" style="width: 500px; display: none">
<div class="w2ui-page page-0">
<div class="w2ui-field">
</div>....
<script type="text/javascript">
var uiElement = (function () {
var config = {
onOpen: function (event) {
event.onComplete = function () {
$('#formContainer').w2render('form');
}
...
}());
</script>
on client that file requested by
$('#tempContainer').load('that file name - also dynamic', function (data, status, xhr) {
uiElement.init();
w2ui[layout].content(layout_main, w2ui[uiElement.name]);
});
And do you really return js-files in you resource methods?
some js and html + js files are dynamic build, example;
grid.jsp contains inside
<%# page contentType="application/javascript;charset=UTF-8" language="java" %>
var uiElement = (function () {
var config = {
grid: {
name: ${it.name},
listUrl:'${it.entityListUrl}',
formUrl:'${it.entityFormUrl}',
columns: ${it.columns},
records: ${it.records},
}}
there are ${it..} values from el expression and setting in resource method
#GET
#Path(JS_URL + "{type}")
#Template(name = "grid")
#Produces("application/javascript")
public Response buildJSGrid(#DefaultValue("") #PathParam("type") String type) {
Grid grid = new Grid(type);
....
return Response.ok(grid).build();
}}
and from client that js 'file' called by
$.getScript('dynamic js file name' - it is dynamic too).done(function (script, status, xhr) {
//console.log(xhr.responseText);
uiElement.init();
w2ui[layout].content(layout_main, w2ui[uiElement.name]);
});
also some html blocks build dynamic
{
<c:if test="${it.recid != 0}">
<div class="w2ui-field">
<label>active:</label>
<div>
<input name="active" type="checkbox"/>
</div>
</div>
</c:if>
}
-- update description,
grid builder;
one resource and one template for build any grid,
#GET
#Path(GRID + "{type}")
#Template(name = W2UI_VIEW_PREFIX + "grid/grid")
#Produces(MEDIA_TYPE_APPLICATION_JAVASCRIPT)
public Response buildGrid(#DefaultValue("") #PathParam("type") String type) {
for (W2UI ui : W2UI.values()) {
if (type.equals(ui.getName())) {
W2UIElement grid = ui.getUI();
return Response.ok(grid).build();
}
}
return Response.noContent().build();
}
also possible different templates(jsp files) through Viewable(template, model)
somewhere in menu builder for menu.jsp template
List<MenuItem> items..
MenuItem item1 = new MenuItem(W2UI.TASK_GRID, W2UIService.GRID);
items.add(item1);
where
W2UIService.GRID is string url for client js request and for server method resource #Path() anno.
and
public enum W2UI {
TASK_GRID("task_grid", "tasks", Type.SCRIPT){
#Override
public W2UIElement getUI() {
return new TaskGrid(getName());
}
},
.....
}
TaskGrid is filled model for grid.jsp template with js code, so easy to add any type of grid with different sets of data and buttons.
type of component(Type.SCRIPT) processing on the client by $.getScript(), Type.HTML by $('#tempContainer').load()
---update factory and providers;
#Provider
#Priority(200)
#HtmlMinify
public class HtmlMinifyInterceptor implements WriterInterceptor {
#Inject private HtmlCompressor compressor;
...
public class HtmlMinifierFactory implements Factory<HtmlCompressor> {
private HtmlCompressor compressor;
#Override
public HtmlCompressor provide() {
if (null == compressor) compressor = new HtmlCompressor();
ClosureJavaScriptCompressor jsCompressor = new ClosureJavaScriptCompressor();
jsCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
..
#ApplicationPath("/")
public class MainRsConfig extends ResourceConfig {
public MainRsConfig() {
..
register(new AbstractBinder() {
#Override
protected void configure() {
bindFactory(HtmlMinifierFactory.class).to(HtmlCompressor.class).in(Singleton.class);
}
});
..
You can use a custom implementation of a ByteArrayOutputStream as a wrapper to the OutputStream of the WriterInterceptorContext:
import com.googlecode.htmlcompressor.compressor.Compressor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class HtmlMinifyOutputStream extends ByteArrayOutputStream {
private OutputStream origOut;
private Compressor compressor;
public HtmlMinifyOutputStream(OutputStream origOut, Compressor compressor) {
this.origOut = origOut;
this.compressor = compressor;
}
public void close() throws IOException {
super.close();
String compressedBody = compressor.compress(new String(this.buf));
this.origOut.write(compressedBody.getBytes());
this.origOut.close();
}
}
The HtmlMinifyOutputStream can be used in the WriterInterceptor implementation. The HtmlCompressor instance is injected:
import com.googlecode.htmlcompressor.compressor.Compressor;
import javax.inject.Inject;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.*;
#Provider
#HtmlMinify
public class MinifyHtmlInterceptor implements WriterInterceptor {
#Inject
private Compressor compressor;
#Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
final OutputStream outputStream = context.getOutputStream();
context.setOutputStream(new HtmlMinifyOutputStream(outputStream, compressor));
context.proceed();
}
}
#HtmlMinify is a NameBinding annotation, used to activate the MinifyHtmlInterceptor on specific resource methods. (see https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9988):
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
#NameBinding
#Retention(value = RetentionPolicy.RUNTIME)
public #interface HtmlMinify {}
The HtmlCompressor can be created only once per application and used concurrently, because:
HtmlCompressor and XmlCompressor classes are considered thread safe* and can be used in multi-thread environment (https://code.google.com/archive/p/htmlcompressor/)
Here is a HK2 factory (see: Implementing Custom Injection Provider) which creates the compressor instance and enables inline css and javascript compression:
import com.googlecode.htmlcompressor.compressor.Compressor;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import org.glassfish.hk2.api.Factory;
public class HtmlCompressorFactory implements Factory<Compressor> {
private HtmlCompressor compressor;
#Override
public Compressor provide() {
if(compressor == null) {
compressor = new HtmlCompressor();
}
compressor.setCompressJavaScript(true);
compressor.setCompressCss(true);
return compressor;
}
#Override
public void dispose(Compressor compressor) {}
}
The factory is registered with an AbstractBinder:
final ResourceConfig rc = new ResourceConfig().packages("com.example");
rc.register(new AbstractBinder() {
#Override
protected void configure() {
bindFactory(HtmlCompressorFactory.class).to(Compressor.class).in(Singleton.class);
}
});
If inline javascript or inline css compression is enabled:
HTML compressor with default settings doesn't require any dependencies. Inline CSS compression requires YUI compressor library.Inline JavaScript compression requires either YUI compressor library (by default) or Google Closure Compiler library. (https://code.google.com/archive/p/htmlcompressor/)
I use maven, so I added this dependency to my pom.xml:
<dependency>
<groupId>com.yahoo.platform.yui</groupId>
<artifactId>yuicompressor</artifactId>
<version>2.4.8</version>
</dependency>
If you want to use the Google Closure Compiler use this dependency:
<dependency>
<groupId>com.google.javascript</groupId>
<artifactId>closure-compiler</artifactId>
<version>r2388</version>
</dependency>
and activate it:
compressor.setJavaScriptCompressor(new ClosureJavaScriptCompressor());
compressor.setCompressJavaScript(true);
compressor.setCssCompressor(new YuiCssCompressor());
compressor.setCompressCss(true);
return compressor;
If you want to compress pure JavaScript or CSS files, you cannot use the htmlcompressor. This library supports only HTML files with inline CSS/JS. But you could implement a MinifyJsInterceptor or MinifyCssInterceptor analog to the MinifyHtmlInterceptor, which uses the YUI-Compressor and/or Google Closure libraries directly.
For gzip compression you should implement another interceptor. So it is possible to configure the minification and compression separately. If you activate multiple interceptors, use javax.annotation.Priority to controll the order of execution. (see: https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9927)

how to run java on website and to get values to html

i know the question may sound easy to most of you but I am stuck with it.
First of all i like to define what i am trying to achieve.
on eclipse i am running a piece of code that sends some data over specific port, and via html and javascript i am getting those that it's sent and print them on screen.
I have an account from one of free hosting websites.
I want to run my code on that website e.g mywebsite.blahblah.com/...
and from html file on my computer i want to access that website, get those values produced by java code and print them on screen.
I have no idea where to start.
the codes are
java and html
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class GPSServer extends WebSocketServer {
static int port = 9876;
public GPSServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public GPSServer(InetSocketAddress address) {
super(address);
}
public void sendData(String s) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(s);
}
}
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
System.out.println(arg0.getRemoteSocketAddress().getAddress()
.getHostAddress()
+ " connected to the server!");
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
System.out.println(arg0 + " disconnected!");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
arg1.printStackTrace();
if (arg0 != null) {
}
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
System.out.println(arg0 + ": " + arg1);
}
public static Runnable sendData() {
Runnable r = new Runnable() {
#Override
public void run() {
WebSocketImpl.DEBUG = true;
GPSServer server;
try {
server = new GPSServer(GPSServer.port);
server.start();
System.out.println("GPS server started at port: "
+ server.getPort());
double longitude = 39.55;
double latitude = 22.16;
String lng = Double.toString(longitude);
String ltd = Double.toString(latitude);
String all = lng + "-" + ltd;
while (true) {
server.sendData(all);
/*
* server.sendData(Double.toString(longitude));
* System.out.println("longitude sent...");
* server.sendData(Double.toString(latitude));
* System.out.println("latitude sent...");
*/
Thread.sleep(5000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return r;
}
public static void main(String[] args) throws UnknownHostException {
Thread thread = new Thread(GPSServer.sendData());
thread.start();
}
}
--
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
var lat;
var lng;
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9876/echo");
ws.onopen = function()
{
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var partsArray = evt.data.split('-');
lng=partsArray[0];
lat=partsArray[1];
alert(lat);
alert(lng);
};
ws.onclose = function() {
alert("Connection is closed...");
console.log("Connection is closed...");
};
}
else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
<div>
<p id="para"> BASIC HTML!</p>
</div>
</body>
</html>
Thanks!
I'm assuming you're very new to all this web development. I haven't studied your code fully but the basic idea is you need a server side scripting language like JSP(of course JSP because you're using Java Code). I hope you know Javascript's basic idea is to use resources on the client's end, or to load data dynamically. So if you're only concerned with displaying some values from server to the client, you can simple make a servlet which will print your data.
Following MVC pattern,
Controller== Make a servlet which will handle the request made by user(i.e. the link which will show data,basically). Set your Model in this controller once you receive a request(you can decide what to do on GET/POST separately too).
Model== Make an abstract representation(class of Java) holding all your data that is to be displayed.
View== Here you'll receive the model. In other words, this will be your HTML. You can use JSP helpers to customize the view, the basic idea is to control HOW DATA WILL BE SHOWN TO THE USER(hence the name View). HTML will be automatically generated at run-time and passed to the user.
Again, I say I'm assuming you're very new to web development. Please let me know if I haven't understood your question well. Enjoy coding.

use deployJava.js to call java methods in javascript

I want to call java methods in javascript and Andrew Thompson suggested to use the deployJava.js library for this. I followed these instructions:
http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html
Here is explained how to use the java class in javascript, but I would like to call the java methods from within the javascript. (This is because I want to import a .owl file in java en export the information in json-format to my code written in javascript.)
Does anybody know how to do this with the deployJava library?
This is my code to import the java file:
<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>
<h1>Sending Messages to Other Applets</h1>
<script>
function sendMsgToIncrementCounter() {
receiver.incrementCounter();
}
</script>
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'Sender.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'../Receiver.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
and this is are the sender and receiver java files:
import javax.swing.*;
public class Receiver extends JApplet {
private int ctr = 0;
private JLabel ctrLbl = null;
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ctrLbl = new JLabel("");
add(ctrLbl);
}
});
} catch (Exception e) {
System.err.println("Could not create applet's GUI");
}
}
public void incrementCounter() {
ctr++;
String text = " Current Value Of Counter: " + (new Integer(ctr)).toString();
ctrLbl.setText(text);
}
}
import javax.swing.*;
import java.awt.event.;
import netscape.javascript.;
public class Sender extends JApplet implements ActionListener {
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
final ActionListener al = this;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JButton btn = new JButton("Click To Increment Counter");
add(btn);
btn.addActionListener(al);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public void actionPerformed(ActionEvent e) {
try {
JSObject window = JSObject.getWindow(this);
window.eval("sendMsgToIncrementCounter()");
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
I just copy-paste this from the example given on this site:
http://docs.oracle.com/javase/tutorial/deployment/applet/iac.html
This example works perfect in my browser, so the way it is done is correct, but I suspect that I don't import the javafiles correct, since this are the errors from je java-console:
load: class Sender.class not found.
java.lang.ClassNotFoundException: Sender.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:195)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:249)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:179)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:690)
at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3045)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1497)
at java.lang.Thread.run(Thread.java:680)
Exception: java.lang.ClassNotFoundException: Sender.class
Combining your original method, with the new JS snippet, and part of the accepted answer on your last question (tweaked), gives..
<html>
<head>
<script>
// dangerous to have a 0x0 applet! Some security plug-ins regard it
// as suspicious & automatically remove the element. Better to set it
// not visible using styles
var attributes = {
codebase:'../sesame',
code:'applet_test',
width:10,
height:10
};
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
function test() {
var app = document.applet_test;
alert("Screen Dimension\r\n width:" + app.getScreenWidth()
+ " height:" + app.getScreenHeight());
}
</script>
<body>
<FORM>
<INPUT
type="button"
value="call JAVA"
onClick = "test()">
</FORM>
<script>
deployJava.runApplet(attributes, parameters, version);
</script>
</body>
</html>
But I just wrote that up off the top of my head. Don't trust me, trust a validation service. ;)
I would advise setting up a simple webservice that your javascript code can use. It doesn't need to be very involved, personally I'd use a simple REST layout with JAX-RS (jersey is really nice to work with), especially if you want something simple with JSON support built-in (with the right plugin).
Trying to actually communicate with the applet on the page might be possible, but very browser dependent and IMHO not worth the hassle. If you're working on the web, might as well use a web service.
There was a problem with the directory of the .class files given in the attributes. Here is the correct code:
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'sesame/Sender.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'sesame/Receiver.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>

Using UiBinder to create a login panel. How to make a user loggin and show other widgets

I created a a widget has a log in panel:
Here is the code:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>
/* Add CSS here. See the GWT docs on UI Binder for more details */
</ui:style>
<g:VerticalPanel width="200px" height="auto">
<g:Label text="Username:" width="100%" height="auto" />
<g:TextBox ui:field="Username" width="100%" height="auto" />
<g:Label text="Password:" width="100%" height="auto"/>
<g:PasswordTextBox ui:field="Password" width="100%" height="auto" />
<g:Cell horizontalAlignment="ALIGN_RIGHT">
<g:Button text="Login" ui:field="button" height="25px"/>
</g:Cell>
</g:VerticalPanel>
</ui:UiBinder>
And here is the generated class:
public class LoginPanel extends Composite implements HasText {
private static LoginPanelUiBinder uiBinder = GWT
.create(LoginPanelUiBinder.class);
interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> {
}
public LoginPanel() {
initWidget(uiBinder.createAndBindUi(this));
}
#UiField
Button button;
#UiField
TextBox Username;
#UiField
PasswordTextBox Password;
public LoginPanel(String firstName) {
initWidget(uiBinder.createAndBindUi(this));
}
#UiHandler("button")
void onClick(ClickEvent e) {
Window.alert("Hello!");
}
public String getUsername() {
return Username.getText();
}
public String getPassword() {
return Password.getText();
}
#Override
public String getText() {
// TODO Auto-generated method stub
return null;
}
#Override
public void setText(String text) {
// TODO Auto-generated method stub
}
}
I want to access the click event of this class on the onModuleLoad so that I can know when the user has clicked the button and has successfully logged in, so I can call other panels I created. Only thing this does is an alert.
This is the first time I'm playing with UiBinder, so I might be missing something.
Thank you.
So you want your LoginPanel to notify your main app class when a user has logged in?
This is really a job for EventBus. Take a look at the exact use case that you need (AuthenticatedEvent): How to use the GWT EventBus
First thing you would need to do is to send user-name password to the server. You can use RPC for this purpose. Then in your RPC callback ( onsuccess ) you can show the rest of your UI.
Here is a skeleton of what you will need to do:
private AsyncCallback loginCallback = new AsyncCallback(){
public void onSuccess(){
// show ui here
}
public void onFailure(Throwable caught) {
Window.alert("debug: login failed, message from server: " + caught.getMessage());
}
}
#UiHandler("button")
void onClick(ClickEvent e) {
Window.alert("debug: Sending login data to server");
LoginServiceAsync loginAsync = ...
loginAsync.doLogin(getUsername(),getPasword(),loginCallback);
}
You will need to create a LoginService RPC service using GWT's RPC facilities.

Categories