Calling a java function with parameter within javascript function - java

is it possible to call java method within a javascript function? Let me explain my problem:
I am working with JSP (have to) and I have a JavaScript form validator which is checking whether a entered value is allowed. It depends on whether there already is such an entry in my MySQL DB. The Script looks like the following:
<script type="text/javascript">
<% DbConnection db = new DbConnection(); %>
function validateForm()
{
var x=document.forms["form"]["name"].value;
if (<%= db.validateName("%> x <%=") %>)
{
alert("Themenname bereits vergeben.");
return false;
}
}
</script>
So what I have to do is passing the entered value (javascript parameter) to my java method (db.validateName) in order to receive a boolean value.
Any idea how to solve this? Java runs server-side whereas JS runs on the client-side, right? Unfortunately I have no clue on how else I could validate from mySQL db.
Thanks in advance! :)

You need send to the server your validation, with AJAX, you can use a Servlet or another JSP validation that receives the validation input and response with validation result/message to the client.
render your html -> fire the event to validate -> send to the servlet/jsp in to server side -> validate into server -> response to the cliente -> in the client receive the server response -> in the client side render the validation menssage -> process form

You have to use AJAX.
You can have a look at DWR also if you want, here is the link http://directwebremoting.org/dwr/index.html

Related

Jquery AJAX Result data retrieve back to client side in velocity template

I have just created an AJAX request in velocity template and able to get request at .java file as below: (java file is extended for "JiraWebActionSupport" as webwork module).
var url = "PlanIssuesAction!IssuesPlanning.jspa";
jQuery.post(url,myJSONObject,function(result) {
alert('success');
})
.done(function() { alert("in done"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
On the server side, in doIssuesPlanning method, able to get call and insert the posted data.
public String doIssuesPlanning() {
System.out.println("Success executed result appear"); //i want this value to be //retrieval at client side but it's not working. unable to receive at ajax response.
return getRedirect("PlanIssuesAction!default.jspa");
//return "result is success" //also tried instead of getRedirect ,used direct response //return but not worked, it capture at error in ajax response at client side.
}
Now I need to return the result data to the client side back at jquery "Result" parameter.
How can I achieve this? Currently, in "Result" object shows all HTML text and nothing else.
(i have set object above through - "System.out.println and expect to be retrieved at client side but not working).
Can you please let me know , what is wrong here.
Thank you.
Webwork jspa URLs return HTML since that is their purpose. Most AJAX calls would be to a REST resource that returns JSON. I'd define a new REST resource for this. More information at https://developer.atlassian.com/display/DOCS/Developing+a+REST+Service+Plugin

Who's Calling my HttpServletRequest?

I have a jsp containing a jquery post to a servlet on my tomcat server which creates a HttpServletRequest. I would like to ensure that only my jsp's calls to my servlet are processed and any requests originating from a source other than my jsp are ignored.
Is there a guaranteed way to see what is the referring page calling my server? I have read that using request.getHeader("referer") can be spoofed so I know I can't rely on that.
Generate an unique string as token, store it in the session and embed it as a hidden input value in the POST form of the JSP and finally check in the servlet if the token is valid.
Basically:
On session creation (in HttpSessionListener#sessionCreated(), for example):
Set<String> tokens = new HashSet<String>();
event.getSession().setAttribute("tokens", tokens);
On preprocessing of the JSP request (in HttpServlet#doGet(), for example):
String token = UUID.randomUUID().toString();
Set<String> tokens = (Set<String>) request.getSession().getAttribute("tokens");
tokens.add(token);
request.setAttribute("token", token);
On processing the JSP itself:
<input type="hidden" name="token" value="${token}" />
On postprocessing of the form submit (in HttpServlet#doPost(), for example):
String token = request.getParameter("token");
Set<String> tokens = (Set<String>) request.getSession().getAttribute("tokens");
if (!tokens.remove(token)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// ...
I of course assume that your jQuery.post() functions are written in an unobtrusive way as in $.post(form.action, form.serialize(), callback) so that it simulates exactly the normal synchronous request (in other words, your forms works perfectly fine with JS disabled).
You can create a random cookie for your jsp, then append it to your POST form, and accept only requests with correct cookie value.
You could render a secure token to your JSP and include it in your Ajax call to the Servlet where you could verify it. This also doesn't guarantee that the Ajax call is made using a browser and your Javascript but it at least requires someone to get the secure token from the JSP before making the call.
A similar concept is recommended to mitigate CSRF.
Just a bit of semantics. Requests are created usually from the browser which displays your JSP. You can not stop another program from requesting your JSP and using whatever information you give them to request again.
You CAN stop another webpage that is being viewed in a user's browser from executing a request to your site. This is called Cross-site request forgery. You can mitigate this scenario.
So depending on what you are trying to prevent, CSRF solutions might work for you. You can find a premade solution from your web server. For example, here is Tomcat's

Applet web app interaction

I have an applet that calls a URL, on a user action, and passes some parameters. These parameters are executed on a ROR server and then I update a partial, which is on the applet's page, based on the result. However, the partial is not updating.
The console says that the partial is rendered but it is not. Is it because I am calling the URL from the applet and the server is unaware that the applet is in the current session, hence it does not know which session partial to render?
Here is the code of the controller:
def add_point
#comments = Comment.find(:all)
render :update do |page|
page[:comment_text].value = ""
page.replace_html :comments_partial, :partial => 'comments', :collections=>#comments
end
end
EDIT: I use Apache commons http wrapper to send the request:
PostMethod post = new PostMethod("http://localhost:3001/vizs/add_point");
post.addParameter("upload[test]", dataImg);
post.addParameter("upload[user_id]", new Integer(user_id).toString());
post.addParameter("upload[viz_id]", new Integer(viz_id).toString());
I think I need to set additional request variables but I am unsure what to set....
Any suggestion on how to solve this?
Thanks,
Slotishtype
rails is not aware about the applet, and does not know how to work with it, you need to send xml or json or even html:
def add_point
#comments = Comment.find(:all)
render :partial => 'comments', :collections=>#comments, :layout => nil
end
parse it in applet and fill appropriate fields by yourself.

Is it possible to invoke a javaScript server side?

greetings all
i was wondering if it's possible to send some javaScript code in the response of a controller
meaning that i want to invoke a javaScript but not from the jsp (from server side)
something like:
var d = new Date();
var gmtHours = -d.getTimezoneOffset()/60;
var tz=gmtHours;
window.location="page?tz="+tz;
what do you think guys ?
There are two parts to the answer:
Executing JavaScript when the answer comes back from the server. To do that you can wrtite a Javascript in html, something like
<script>
alert("This code just executed");
</script>
usually people have something like
<script>
function init() {
document.getElementsByTagName('input')[0].focus();"
}
window.onload = init;
</script>
It will execute your function when windows loads.
It looks like you want to know the timezone for the user you are displaying results to. As mentioned, HTTP headers don't have this information, so you need to submit it or store as user preference.
If you don't want to store it, you either need to add it to every submit or URL. This way you will always have timezone on server side and you don't need to do 2 round trips.
The workflow might look like this:
1. User submits form or clicks a link -> 2. you form the results on server side -> 3. display results on client side.
Looks like you want to show some dates/times specific to timezone. If you send data to the client using ajax, you can then get it in javascript before step 3 and change it according to your preferences.
If you want to do all the formatting on server side you need to submit the timezone with the original request in step 1.
You can add 2 more steps 1.2 submit timezone request as a response to user action. 1.3 Re-submit the request with timezone info using javascript. This is not optimal, but could work.
I am still not very clear about the question. But it you are asking to invoke a javavscript when a response comes back from server than you can use AJAX and do your processing in the callback.
If you want to access the timezone than another way to send it as part of the parameter right in the beginning as a request parameter itself.

jQuery Address - redirect after form submit

I use jQuery and AJAX to load content from links and forms into a content div. In addition I use the Address plugin to enable the back button and refresh. On the server side I use Java and Spring MVC.
Since I'm using jQuery Address and AJAX the only page that is directly loaded is "index.html". Everything else is loaded into a content div, and what page to load is specified in the hash, ie. "index.html#/users/add.html" will load "users/add.html".
Now, "users/add.html" contains a form for creating a new user. When the form is submitted and everything went OK, the controller redirects to "users/index.html". The problem is that jQuery Address doesn't know about the redirect, so the url will remain "index.html#/users/add.html". And this is a problem when you refresh the page and then get sent back to the form, instead of the index page.
Is there a way to fix this problem?
Thanks,
Stian
Take a look at the new Form Sample. It's very basic but will be probably usable.
http://www.asual.com/jquery/address/samples/form/
In your case you won't be able to use $('form').address() function because you will want to change the address after the server response comes back.
You can use a data.redirect property to detect potential response redirects:
How to manage a redirect request after a jQuery Ajax call
I realize my description of the problem wasn't the best, apologies for that.
I reformulated the problem in another question, got no answers but I found a solution myself. :)
AJAX - Get response URL after redirect
First I init my form like that :
$('FORM').submit(function () {
shareData = $(this).serializeArray();
$.address.value($(this).attr('action'));
})
after I have in my change method something like that :
$.address.change(function(event) {
if (event.path != '/' && event.parameters.layout_to_use != undefined) {
// if no json, load don't do a post request
shareData = _arrayToJson(shareData);;
$('#areatoreload')
.html('<span style="background-color:red;">loading...</span>')
.load('myscript.php', shareData, function() {});
}
return false;
});
And i manage my link in the same way. I hope it can help you. shareData is not a very good way, but i don't find something else for the moment. this code is not tested, I just extract some part of my own code.

Categories