I'm working on a system for my university and I'm using the play framework to do that.
The Admin of this system sets a marker on a google map and I get the coordinates from that point.
Now I'm trying to pass this information to the server side, so that I might store these to Strings in a mySQL database. The only problem I have is passing the data from my String in javascript/JQuery to the java function.
I tried different solutions on the internet but some of them seemed outdated and I couldn't figure out how to do it.
I've only been programming in Java, Javascript, JQuery and PHP and have never used AJAX (like the $.get() methode from JQuery), but I think it might be pretty similar to what I know from PHP.
e.g.
http://java.dzone.com/articles/jquery-ajax-play-2
I'd like to pass my String with a button click to my java function, so I can store it in my db.
I'm really confused about this.
I know I can use something like
<a href="{#routes.Application.postMethod()}"> Send </>
and then mention the function in the routes like
POST /post controllers.Application.post();
but how do I pass my qjuery string?
and how do I store my String as a String in a java function like:
public static Result post(String Lat, String Lng){
???????????? EVOLUTION NEEDED ?????
}
Thanks in advance I really need your help :)!
I don't see why you are doing a POST, since this can be done using a GET request.
As per this example:
http://www.playframework.com/documentation/1.2/ajax#jsaction
We can see Play makes it easier using the jsAction tag. Lets assume you have the following route:
GET /admins/marker Admins.marker
Then in your HTML, at the bottom you'd do something like:
<script type="text/javascript">
$('#myButton').click( function() {
var action = #{jsAction #marker(':latitude',':longitude') /}
$('#result').load(
action({latitude: '23', longitude: $('#longitudeField').val }),
function() {
$('#content').css('visibility', 'visible')
}
)
});
</script>
In this case, the request will be sent like (example):
GET /admins/marker?latitude=23&longitude=67
And then on your backend, you need the have to java fn to deal with that route.
Basically the javascript/jquery, is called when #myButton element is clicked, then we generate the route URL we are going to make a request to using jsAction, then we make using load to make a GET request. You can change this to post too if you'd like.
Related
I would like to get the page content as a stream/or a string from a Page.class directly.
At the moment: I have to go through the route:
String uri = linkSource.createPageRenderLink(AnotherPage.class).toAbsoluteURI();
IOUtils.toString(uri, "UTF-8")
The problem with this approach is the call to toAbsoluteURI() makes the framework feel like the request is made from an external source; and it asks the user to login again; which should not be the case, as its one tapestry page accessing the other within the same application.
Note: I am not trying to "redirect" to AnotherPage.class. I would simply like to get another page's content as String without having to go via toAbsoluteURI() etc.
Alternatively, getting another page's content as Stream works too.
I am using Apache Tapestry 5.4.1
Take a look at the tapestry-offline module. It lets you obtain the HTML from a Tapeatry-generated page quite easily.
https://github.com/uklance/tapestry-offline
Have the method onActivate return an implementation of a StreamResponse, e.g.
public StreamResponse onActivate(Long productId) {
return new TextStreamResponse("text/csv", convertProductToCsv(productId));
}
By default a page returns a template, but in this way you override that behaviour.
Check out this page: https://wiki.apache.org/tapestry/Tapestry5HowToStreamAnExistingBinaryFile.
I'm trying to redirect my users to an AngularJS style URL:
http://somedomain.com/#/oauth/authorize
And I have some parameters I'm adding to the URL via my model. So far, so standard. Right up until Spring MVC takes a dark and sinister turn inside of RedirectView at line 400. If you click that link you'll see the comment:
// Append anchor fragment, if any, to end of URL.
No! This is not good for AngularJS! That would make my normally beautiful redirect:
http://somedomain.com/#/oauth/authorize?query=params
look like:
http://somedomain.com/?query=params#/oauth/authorize
This is bad juju!
So I have two questions:
What purpose does this arrangement of anchor and query params serve.
How do I circumvent this devilish machinery?
Thanks for any help!
I feel like I need to take a shower after doing this, but this is a possible solution.
Place this in your main script (i.e. app.js) immediately before creating the module in which you configure your $routeProvider.
var urlLoaded = window.location.href;
var qIndex = urlLoaded.indexOf('?');
var hashIndex = urlLoaded.indexOf('#');
if (qIndex !== -1 && hashIndex !== -1 && qIndex < hashIndex) {
var correctedPath = urlLoaded.substring(hashIndex);
var correctedParams = urlLoaded.substring(qIndex, hashIndex);
var base = urlLoaded.substring(0, qIndex);
var correctedUrl = base + correctedPath + correctedParams;
window.location.href = correctedUrl;
}
If you are in the early stages, I would look into using HTML5 pushState. This way you can use anchors like they were meant to be used, and you url's will look cleaner. There are browser limitations to this, and other considerations, but getting it in correctly might save you time down the line from running into this again.
You can extend this class, override the method, and fix it to be smarter than it currently is. Register it with spring (it might take a couple of overrides, look at ViewControllerRegistry), and if you're feeling nice, submit a Pull Request and see if they want it.
Beat that URL back into submission in angular as #hartz1989 has suggested
Instead of doing a redirect, you could respond back with a query parameter that has the redirected url, and add a handler in angular that understands this and does the "redirect". I don't really like this idea, but it is another idea.
Good evening,
I have a form on a JSP page that's connected to a servlet, that form has some dynamic parts using JavaScript like adding a row to a table or adding a text field based on the selected option on a select element, Actually my problem is that I have some validations on the servlet-side, so when I go to servlet to check the (National ID) for example if there's any problem or any violations to my validation I force to get back to the form using :
if (dbm.MatchIdNumber(Candidate.getRegNumber(), Candidate.getNationalID()) == false) {
out.println("<script>\n"
+ " alert('Your National Id does not match your Registration Number');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
What happens is when I get back to the form I lose all the JavaScript changes, Which's very important.
I've been reading for a while that using ajax might be the optimal solution for me, but here is my questions:
Is there a way to call a java method from JavaScript or JQuery before getting to servlet without using ajax !?!
Is there a way to get back from the servlet to the jsp page with the ability to keep all the JavaScript Chages !?
If not !!, How to use ajax in my case ?!
Thank you so much
No. JavaScript runs on the user's browser and your Java code runs on your webserver, so basically the only way to communicate between the two is via HTTP requests.
If you don't want to use AJAX, you could provide all of the relevant info when you submit the form to the server for validation. You could pass all the info you need to re-generate the form as it was, like which new fields are there and such
First, you'll need to add a new webservice to your Java webapp which performs validation. To achieve this, you could either add additional logic to your servlet (so that it looks for a request parameter like "doValidation=1" and performs validation if it's there) or write a different servlet that handles validation itself. You'll need to decide the format it should expect the form data in and how it should return the validation information.
On your frontend page, you'll need to modify the behavior of the form so that, when you need to do validation, it performs a request to this webservice and passes along the form data. I would probably do this with jQuery and do something like jQuery.ajax(...) and pass the contents of the form as a JSON object.
When your validation servlet returns data from the ajax call, you'll need to update the form based on the data it provides. If I was doing it, I would probably just have the servlet return a JSON object like {errorMessage:"..."} and I would use jQuery to add an element to the form containing the text of the validation error when it occurs. If the servlet returns an empty string or JSON object or something, I would consider it a validation success.
I have an URL which shows me a coupon form based on id:
GET /coupon/:couponId
All the coupon forms are different and submit different POST params to:
POST /saveCoupon/:id
I want to have a convenient way of debugging my coupons and be able to have a way of viewing actual POST params submitted.
I've made a controller on URL POST /outputPOST/saveCoupon/:id which saves nothing, but prints to browser POST params received.
Now I want to have an URL like GET /changeActionUrl/coupon/:couponId which calls GET /coupon/:couponId and then substitutes form's action URL POST /saveCoupon/:id with POST /outputPOST/saveCoupon/:id .
In other words I want to do something like:
Result.getHtml().replace("/saveCoupon/","/outputPOST/saveCoupon/");
With this I can easily debug my coupons just by adding "/outputPOST" in the browser.
You could just use a bookmarklet and javascript to replace all of the forms' action attributes. That way your developer can do it with one click instead of changing urls.
Something like this will prefix all form actions on the page with "/outputPOST".
javascript:(function(){var forms=document.getElementsByTagName('FORM');for(i=0;i<forms.length;++i){forms[i].setAttribute('action','/outputPOST'+forms[i].getAttribute('action'));}})();
I don't understand, at least not everything ;)
In general you can debug every piece of Play app using debugger (check for your favorite IDE tips how to do that) - this will be always better, faster, etc etc, than modifying code only for checking incoming values.
I.e. Idea 13+ with Play support allows for debbuging like a dream!
I'm currently building a Twitter client in Java using the Twitter4J API. To create a Twitter "timeline", I am currently pulling data from Twitter such as profile images, tweets and usernames, then displaying them in a JTextPane, formatted using HTML. Code example below:
StringBuilder out = new StringBuilder();
try {
List<Status> statuses = HandleEvents.instance().twitter.getHomeTimeline();
out.append("<html>");
for (Status status : statuses)
{
out.append("<img src=\"").append(status.getUser().getProfileImageURL())
.append("\" width=30 height=30><b>").append(status.getUser().getName())
.append(":</b> ").append(status.getText())
.append("<br><br>");
}
out.append("</html>");
tweetsTextPane.setText(out.toString());
This displays a timeline of 20 tweets, separated by two line breaks. Under each tweet, I would like to place a simple hyperlink, called "Retweet", which calls one of my Java methods - HandleEvents.instance().twitter.retweetStatus(status.getId())
How would I got about doing this? Can the call be made directly between the tags, or do I have to make the call using JavaScript?
Any help would be appreciated. Many thanks.
You don't really need to have a hyperlink do you? Since it's a Swing app you could just add a JLabel that only looks like a hyperlink (but if you put in a little effort, it could behave like one as well). Add a listener for mouse clicks on that JLabel and you've can hook your current handler there.
On the other hand, if you do want actual HTML links, what you can do is implement your own HyperlinkListener.
Here are a couple of examples:
http://www.java2s.com/Tutorial/Java/0240__Swing/HyperlinkListenerExample.htm
http://www.java2s.com/Code/Java/Event/DemonstratingtheHyperlinkListener.htm
http://www.devx.com/tips/Tip/12997