HTML file not working within a GWT/GXT project - html

The following code is working fine when I run it by itself but when I run it from within a widget in my project the alert does not show up. Am I doing something wrong or forgetting to do something?
<html>
<head>
<title>Upload</title>
<script>
function test() {
alert("Works");
}
</script>
</head>
<body>
<input type='file' size='30' id='fileDiag' maxlength='45'
name='fileDiag'>
<input type="button" onclick="test()" value="TEST" />
</body>
</html>

Try replacing the content of your widget's HTML with just this:
<input type='file' size='30' id='fileDiag' maxlength='45' name='fileDiag'>
<input type="button" onclick="test()" value="TEST" />
<script>
function test() {
alert("Works");
}
</script>
You also shouldn't place JavaScript function directly in your widget's html. You can either create it using a UiBinder and specify a handler using #UiHandler in your UiBinder class, or create a class that extends a Composite and then use a XTemplates as follows:
public interface WidgetTemplates extends XTemplates {
#XTemplate(source = "content.html")
SafeHtml content();
}
Then in your widget's constructor you can add the template's content:
WidgetTemplates templates = GWT.create(WidgetTemplates.class);
public class MyWidget extends Composite {
public MyWidget() {
HTMLPanel rootPanel = new HTMLPanel(templates.content());
initWidget(rootPanel);
sinkEvents(Event.ONCLICK);
}
public void onBrowserEvent(Event evt) {
// handler for all events
}
}
I didn't fully test the above code, but you might get the general idea. You want to code the GWT way, not to circumvent it.

Related

Call a jsp function by submitting a form

I want to execute a jsp function when a submit button is clicked. Here's what I'm trying to do:
<form>
<input type="text" id="input">
<input type="submit" onClick="(I want the function to be here)">
</form>
<#!
public static void get(){
String s = request.getParameter("input");
System.out.println(s);
}
(I have simplified the code, if you don't understand please let me know.)
I don't really know if this is possible in anyway, I have been searching and I have seen suggestions on similar cases of using AJAX, but I'm not familiar with it and if there is a simpler solution it would be so much easier.
Edit: I just wanted to specify that the function I'm trying to call isn't this simple, I simplified. The actual function uses code that only Java can run (using a Java library).
This is how you can make a simple ajax request from your jsp file to some java code:
Returning String as plain text
The jsp page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$("#somediv").text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
Servlet doGet() method:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
//you can write whatever java code you want to have here, and you can pass the results to the jsp file through the response writer. (text) This will only work from simple strings. If you want to pass more complicated information like lists or objects you will need to convert it to a json object
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
If you want to do it in a form you can do it like this:
Ajaxifying an existing form
<form id="someform" action="someservlet" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="text" name="baz" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
$(document).on("submit", "#someform", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(response) {
// ...
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");
//do some java stuff here
//then return whatever you want
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8"); /
response.getWriter().write("hello world");
}
Examples taken from: How to use Servlets and Ajax
The onClick() function is meant to be used for JavaScript or JavaScript frameworks, you can do what you are trying to do with JS.
In JS create a function with a parameter, then, the onClick() will look like this
onClick="(myFunction(variableName))"
Inside myFunction(variableName) should look like this
myFunction(variableName){
alert("The variable is: " +variableName);
}
alert("The variable is: " +variableName); will create like a pop up at the top of the webpage showing your variable value.
You can try with this code:
if(request.getParameter("btnSubmit")!=null) //btnSubmit is the name of your button, not id of that button.
{
java.util.Date d = new java.util.Date();
System.out.println(d.toString());
}
<input type="submit" id="btnSubmit" name="btnSubmit" value="Execute Test"/>
Source: onClick function call using scriptlet

Polymer- using custom element in other projects like angular and Java jsp

I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java
my-element.js:
class MyElement extends HTMLElement {
// This gets called when the HTML parser sees your tag
constructor() {
super(); // always call super() first in the ctor.
this.msg = 'Hello, World!';
}
// Called when your element is inserted in the DOM or
// immediately after the constructor if it’s already in the DOM
connectedCallback() {
this.innerHTML = `<form action="/action_page.php">
<div class="container">
<label><b>Name</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Age</b></label>
<input type="text" placeholder="Enter Age" name="age" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Add</button>
</div>
</div>
</form>`;
}
}
// This registers your new tag and associates it with your class
window.customElements.define('my-element', MyElement);
my-element.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
<link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">
<script src="my-element.js"></script>
<!-- <link rel="import" href="add-form.html"> -->
</head>
<body>
<my-element></my-element>
</body>
</html>
Two issues I am struggling with now are below
1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?
<link rel="import" href="my-element.html">
<script src="my-element.js"></script>
<my-element></my-element>
I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements
[
{
"name":"Name",
"type":"text",
"size":"20",
"readyOnly": false,
"validateFunction":"onlyText"
},
{
"name":"Age",
"type":"number",
"size":"3",
"readyOnly": false,
"validateFunction":"onlyNumber"
}
]
I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors
<my-element form-data="{{data}}"></my-element>
ad 1) yes you can use your element with every server system you would like. It's "just html" that the beauty in it :)
ad 2)
HTMLElement won't do anything automatically. So if you wish to access your json you will have to do something like this
<my-element form-data="{'name': 'Name', 'type': 'text'}""></my-element>
connectedCallback() {
let rawData = this.getAttribute('form-data');
let jsonData = JSON.parse(rawData.replace(/'/g, '"'));
}
Notice that in the form-data json there are ' instead of ". So we have to replace them before using JSON.parse.
it looks like this is using a web component as opposed to a polymer component. The native web component API does not include data binding, although angular and polymer both do (but implemented in different ways).
Native web components and polymer components can be used with Angular as well as other frameworks.
Depending on whether you are using Angular.js(1) or Angular(2+), setting up the data object to be passed into the DOM will vary, but in general the data should be "set up" so to speak in the JS and passed into the DOM. Otherwise as #daKmoR said, the data would need to be declared as he did in his example.
There are packages that assist in implementing data 2-way binding between polymer's data bindings and angulars bindings if that is needed.
Trey

Need help tossing a coin in Java

I am struggling creating my java coin toss for my webpage. I need to write a Java script to put on the webpage that will show pictures of coins being tossed and carry out the coin toss. here is what I have, why isn't it working? It just opens a new page and says "about:blank?"
<html>
<head>
<title> </title>
<script>
function toss() {
if (Math.random()>.5) {
window.document.coin.src = "heads.jpeg";
}
else {
window.document.coin.src = "tails.jpeg";
}
return false;
</script>
<body>
<img name="coin" src="questionmark.jpeg">
<form action="" onSubmit="return toss() ;">
<input type="submit" value="Toss">
</form>
</body>
</html>
You are missing the closing curly brace for your toss() function. Once fixed it appears to work fine. Also, yes, javascript...not java.
function toss() {
if (Math.random()>.5) {
window.document.coin.src = "heads.jpeg";
}
else {
window.document.coin.src = "tails.jpeg";
}
return false;
}

Very simple spring MVC button click

I have the following code in my SampleController;
#Controller
public class SampleController {
#RequestMapping("home")
public String loadHomePage(Model m) {
m.addAttribute("name", "CodeTutr");
return "home";
}
#RequestMapping(value="/test", method=RequestMethod.GET)
public String handlePost(#RequestParam String action, Model m) {
if( action.equals("save") ){
//handle save
}
else if( action.equals("renew") ){
//handle renew
}
m.addAttribute("name", "change");
return "home";
}
}
on page load the attribute I set it successful shown on the web page. I am trying to get my head around button clicks on spring mvc below is my jsp code;
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Application</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<input type="submit" name="action" value="save" />
</body>
</html>
My input does not do anything, the method handlePost is never hit. I was trying to change the attribute "name" to the word "change", I am not sure what I am doing incorrectly.
Your issue isn't with Spring, it's with HTML. You cannot submit a button. You can only submit a <form>.
Wrap your <input> element in a <form>
<form action="<c:url value="/test" />" method="GET">
<input type="submit" name="action" value="save" />
</form>
Where <c:url> is the url tag of the core taglib. Now, when you click the button, the browser will serialize your <input> elements as url-encoded form parameters and send them. They will appear as request parameters to your server/web application. Spring will deserialize them by name and inject them as arguments where you have a #RequestParam method parameter.
There needs to be a form encapsulating your input.
General FYI: Your "save" and "renew" use cases should be separate controller actions.
Also consider removing "POST" from your action name. Seeing as the action is decorated with GET, and the html is saying its GET

Wicket: DropDown box with checkboxes for multiple selection

I need to compactly present multi-selection inside a drop-down box in Wicket by having a check box next to each value in the drop down box. I'm thinking of using ListView with CheckBox and Label as a component for DropDownChoice but then I am not sure how to proceed further.
You can use some javascript library applied to Wicket's ListMultipleChoice (which generates a [select multiple="multiple"] HTML tag. I've found one (jQuery UI MultiSelect Widget, hosted at GitHub) implemented as a jQuery plugin, which works very well. Thanks to #erichynds!
The Page class is just a plain-old Wicket page, and all you have to do is to import the scripts/stylesheets, and call a single function (highly configurable):
HomePage.java:
public class HomePage extends WebPage {
List<String> selection = new ArrayList<String>();
public HomePage() {
add(CSSPackageResource.getHeaderContribution(HomePage.class, "jquery.multiselect.css"));
add(JavascriptPackageResource.getHeaderContribution(HomePage.class, "jquery.multiselect.min.js"));
add(new FeedbackPanel("feedback"));
Form form = new Form("form") {
#Override
protected void onSubmit() {
info(selection.toString());
}
};
form.add(new ListMultipleChoice("list",
new PropertyModel(this, "selection"),
Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H")));
add(form);
}
}
HomePage.html
<html xmlns:wicket="http://wicket.apache.org">
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/themes/cupertino/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select").multiselect();
});
</script>
</head>
<body>
<div wicket:id="feedback"></div>
<form wicket:id="form">
<select wicket:id="list"></select>
<br/>
<input type="submit">
</form>
</body>
</html>
Alas Wicket is used to generate HTML, and in HTML there is no facility to have a drop-down with checkboxes. (In Swing or another Windowing UI, this would be possible, and your approach would be correct.)
Take a look on the internet for example code for HTML which can cause a similar effect (e.g. a <div> which is shown / not shown when you click on the value you're editing). For example I found this thread here: http://www.webdeveloper.com/forum/showthread.php?t=182976