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.
Related
I am using session attributes in my .gsp page like below:
<g:set var="maxValue" value="${session?.MY_VAR}"/>
I am making an AJax call from Javascript to the Groovy controller ( MyController.groovy ) and setting it like below:
session.setAttribute("MY_VAR", "abc");
After Ajax call returns back to the GSP. The value of session variable is not updated. It still stores the old value from the previous load.
Any ideas on how to solve this ?
Your GSP is generated on the server and the resulting HTML is sent to the browser. Your Ajax call does not force a page refresh, so the GSP along with the line below is not reevaluated and the variable maxValue is not changed.
<g:set var="maxValue" value="${session?.MY_VAR}"/>
You should consider render as JSON in your controller to return maxValue and using JavaScript to update the DOM after the Ajax response is received. See render for more info.
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.
Basically I have an Ajax request instantiated by a button where it is passed to my controller, and then that controller returns a list of objects. I initially was thinking whether this could be done by loading the returned ajax object into the JSTL forEach loop, but I think that cannot be done after some research.
This is my ajax request which loads sighting based on a value:
//edit the sighting based on the username value
$(this).on("click", ".edit_sighting", function(){
$username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings){
// load returned object somewhere
});
});
This is my controller which handles the ajax request and responds returning a list of objects 'sighting':
#RequestMapping("/getSighting/{username}")
public #ResponseBody List<Sighting> getSighting(Model model, #PathVariable String username) {
List<Sighting> sightings = sightingsService.getSightings(username);
model.addAttribute("sightings", sightings);
return sightings;
}
And essentially I would like to load the returned objects into a for each loop or something that would display the object fields. for example: something like that.
My for each loop:
<c:forEach var="sighting" items="${sightings }">
<c:out value="sighting.name"/> <!-- load some sighting value -->
</c:forEach>
So essentially what I am trying to achieve is, load multiple or one 'sightings' into a modal type thing when a button is instantiated.
You can't use JSTL for this since JSTL is executed on the server before a page is sent to the client. What you could do is render the HTML on the server and return a HTML document (instead of JSON). So the solution would be to define a JSP view which uses JSTL to render the list and change the AJAX request to accept HTML.
The other solution is to add a JavaScript based template engine and do the template rendering client side.
Or do it manually with jQuery. If you have
<ul id="sightings"></ul>
then you can
var sightings = $('#sightings');
sightings.empty();
$.each(sightings, function(index, e){
var li = $('<li>');
li.text(e);
sightings.append(li);
});
The response to the ajax request is returned to the client, which does not have access to server side mechanisms such as JSTL. The code should use Javascript/jQuery on the client side to display the new DOM elements.
So if you had the following HTML on your page:
<ul id="sightings"></ul>
The callback would look like:
$(this).on("click", ".edit_sighting", function(){
$username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings){
var output = "";
for(var i = 0; i < sightings.length; i++){
output =+ "<li>" + sightings[i].name + "<\/li>";
}
$("#sightings").append(output);
});
});
This will build a String containing HTML which has an li for each sighting. The HTML is then appended to the DOM as children of the #sightings ul.
Since you are using ajax so the page will not reload once your request returns the response so anyway this code
will not work.
what you can do is instead of sending a list you can send a JSON array as response and each array element will have a JSON object having all the required properties and this array can be iterated after the response is received.
I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.
I want to pass parameters from one jsp to another.
I have tried using the post method, <jsp:forward/>, but it doesn't work.
I have created a <form> in html (parameters passed using POST), which is submitted to a servlet which processes the request and forwards it to another servlet that displays a page.
From this servlet i have created links to another jsp, passing through the parameters as GETs in the URL. However, I actually want to pass the parameters to another jsp using POST, and then pass it on to another jsp.
What solutions do you have or this problem?
Check out the Request Dispatcher. You need to forward the request to the landing JSP.
http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html
Sounds like you are creating a multipage form that gathers information from the user across several distinct pages. In that case one option is to use hidden fields on a form to store the previous values. This of course means that as the pages progress the amount of data passing back and forth from client to server increases.
You may consider a server side approach by storing the interim values in a database for instance, then only passing a token back to the client. When the next JSP page is submitted, use the token to look up the values in the database.
JSP has built-in request object.when one jsp redirect to another jsp with some parameter, you can get parameter value using this request object.
<%
String param1 = request.getParameter("parameter_name");
%>
you can find example here -
http://www.roseindia.net/jsp/RequestObjectInJSP.shtml
Why don't you call a page on the click of a submit button by creating
an url in the below format (in javascript):- var
url="your_page_name.jsp?value1="+encodeURIComponent(document.getElementById("your_text_field_or_any_other_field_id"));
and then call the page by using your url
document.your_form_name.action=url;
document.your_form_name.submit();
and then use request.getParameter() method either in servlet
or in the jsp that u'v metioned in the url (servlet or the jsp u'll be
calling thorugh u'r jsp).