Call a JSF method via JS [duplicate] - java

This question already has an answer here:
How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
(1 answer)
Closed 2 years ago.
i have a for loop in JS code, i want to call a method with parameters written in a JAVA managed bean that calculate a value and return a new one that will be used in the JS
Note: i'm using primefaces in the xhtml page
and handsontable to display data
that's how my js looks like
function updateMoneyValue(){
var thetable; //the handsonTable
for (var i =0 ; i < thetable.length ; i++)
{
var myNewValue = theBeanMethod (firstParam , secondParam);
}
}

You can use PrimeFaces remote command component (<p:remoteCommand>).
RemoteCommand enables executing backing bean methods and do partial
update triggered by custom client side script. This example
demonstrates a use case where a certain part of a page can be lazily
loaded on demand.
Add it to the view it in a following way:
<p:remoteCommand name="myRemote" actionListener="#{myBean.listen}"/>
And use it in Javascript like so:
<script type="text/javascript">
myRemote(); //makes a remote call
</script>
or call it from an event handler like so:
<div onclick="myremote();">...</div>
If you additionally want to pass parameters to the server make a following call:
<script type="text/javascript">
myRemote([{name:'param1', value:150}, {name:'param2', value:220}]); //makes a remote call with parameters
</script>
The listener could be like:
public void listen(){
FacesContext context = FacesContext.getCurrentInstance();
Map<String,String> params = context.getExternalContext().getRequestParameterMap();
System.out.println(params.get("param1"));
System.out.println(params.get("param2"));
}

you can use primefaces remoteCommand component. you can find details about remoteCommand in this blog post.
http://blogs.bytecode.com.au/glen/2013/09/25/calling-primefaces-remotecommand-with-javascript-arguments.html

There's no way to do that directly.
Your java/jsf code is parsed and executed on server and then sent to client (browser). Only in browser javascript starts executing.
If you want to call some bean's method and get the result from client/javascript, you need to initiate new network request via AJAX call or somewhat. Also you can try to rework the logic of your application.

Related

AJAX to call java method

There are many similar questions but I am not clear about one thing as mentioned below-
I have ajax call
var url = '/test/testjsp.do?param1=' + xyz;
$.ajax({
type:'GET',
dataType:'html',
url:url,
success:function (data) {
alert("Success");
}
});
which is calling an JSP page
and in that file, I am calling method from SM class
<%# page import="com.testAjax.SM" %>
<%
if (null != request.getParameter("
SM.randomMethod(request.getParameter("param1"));
}
%>
So my question is ,
I there any alternative method where I don't have to create extra Jsp file and call java method directly from Ajax call
Please help and Advise
As javascript is a client side script, it cannot invoke java methods directly which resides on the server.
To do that you have to create a web service or jsp like you did.
But I have seen vaadin gives option to call java code from javascript without writing a service or jsp. I dont know how it will help you.
https://vaadin.com/tutorials/calling-java-from-javascript
There are some concept like java adaptors and javavm to combine javascript and java try them to find it suits your need.

How to send response through ajax from servlet back to jsp? [duplicate]

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Struts 2 make dynamic parameter

I am using Struts 2 and JavaScript. I want to edit a parameter value or add parameter to URL with JavaScript to make dynamic parameter. I can not set value for param why this not have id. Any other form of do?
var urle = document.getElementsByName("vari");
urle.value = 5;
<s:url var="urlex" action="actionDo"><s:param name="vari" value=""/></s:url>
Struts tags are JSP tags that compiled and executed on server, JavaScript is executed on client browser. You can't access the server from javascript code without making ajax request. But you don't need too. Use
var url = '<s:url var="urlex" action="actionDo">' +'?vari=' + val;
You have to set jsonObject when this action class has been called. So according to set parameter it will set parameter dynamic.

Setting a session and ajax call happens parallely

I am setting a session variable in doGet() like
HttpSession session = request.getSession(true);
session.setAttribute("MySessionVariable", "String goes here");
I am trying to display that in my JSP page upon ready like
<%= session.getAttribute("MySessionVariable")%>
and I am making a call to the servlet on ready like
<Script>
$(document).ready(function() {
$.ajax({
type : "GET",
url : "UserInfoDisplay"
});
});
</Script>
But what I see is that, the value is null for the first time and when I refresh again I get the value. That is the ajax call onReady and the page load happens parallely. How should I fix this? I want the data to appear on the first load itself.
Well, it's not exactly like that. Page load happens first, and when the page is loaded, it invokes the servlet. You have to take into account that <%= session.getAttribute("MySessionVariable")%> is executed server side, before the browser gets any HTML. Then, the browser gets the response and your script calls the server again and sets the property, but the page was already rendered. You have to do this in a different way. Can you explain what are you trying to achieve?
If you need it only for the first time, then why make a ajax call in the first place?
Ajax is meant for sending asynchronous requests. Correct me if I am wrong, the better approach would be to redirect a request to the servlet and get a response, isnt it?

JSP page values are not getting populated after getting values from JSP popup window

I am passing JSP values to JSF's backing bean. Once I get the values in bean, then I am trying to assign values to inputText fields with setters method, something like this.
public void testProcess(){
empBean.setEmpName(empBean.getEmpId());
}
testProcess method is called in the action of the JSP page.
My question when I set the value in the bean, my JSF page's values are not getting populated. Do I need to explicitly refresh my JSF page, if so how could I do that?
Yes, you need to refresh the main page. What happens on the server will not automatically make something happen on the client (browser).
One fairly common pattern for this type of operation is to have the popup do the form post using ajax (easy with many javascript frameworks like jQuery). See http://jquery.malsup.com/form/ for a nice example using the jQuery form plugin. In the response handler for the ajax-call, you reload the main page (using the window.opener property) and close the popup. In the example with the jQuery Form plugin, you would do something like:
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
// reload main page
window.opener.location.reload();
// close popup
window.close();
});
});
</script>
The reason you want to submit the form using ajax is that you want to wait to refresh the main page until the post is completed and doing a regular post will cause the popup to reload, which in some browsers will invalidate the window.opener property, making it impossible to reload the main page.

Categories