I want to create a JSON object in java code and then pass it on to javascript/jquery for parsing(further processing).
I am using Struts 2 framework.
This has to be done at page load, not after a AJAX call.
How to access the JSON object (created in java) in javascript/jquery.
Also are any API's for creating JSON object for java object??
You should check out the Google GSON library.
To convert an Object to a JSON string is as simple as:
Gson gson = new Gson();
String jsonString = gson.toJson(myObject);
For your use case (Struts 2), a simple solution would be to place the jsonString property in your Action, then refer to it in the JSP page as follows:
<!-- this goes into your .jsp -->
<script type="text/javascript">
var myJsonObject = <s:property value="jsonString" default="[]" escape="false" />;
</script>
You could try this POST for the question library.
As for consuming the json string in javascript you can use jQuery
jQuery.parseJSON( string );
Related
I am using play framework 2.3.8 java and using ajax to submit a form but I am not able to get the Form object from that request.My problem is explained below.
I have a Model
#Entity
public class Permission {
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String per1= "off";
private String per2= "off";
// getter setters
}
my form
<form id="form-permission">
<!--Setting "on" and "of" value from js-->
<input type="checkbox" id="per1" name="per1">
<input type="checkbox" id="per2" name="per2">
<input type="submit" >
</form>
$('#form-permission').on('submit',function(){
var uid=// id to update
myJsRoutes.controllers.MyController.updatePer(uid).ajax({
data : $("#form-permission").serialize(),
success : function(data) {
console.log(data);
});
return false;
});
When submitting form without ajax then play binds that request data to model Object and we can get Form object like
Form<Permission> permissionFormData = Form.form(Permission.class).bindFromRequest();
and we can get the object by permissionFormData.get() since the request are same for post form with ajax and without ajax In the case of ajax I am doing the same thing but when I try to get Entity members from it gave me a No Value exception with
Logger.info("---Permission one is "+permissionFormData.get().getPer1());
What am I doing wrong here?And is there any other approaches for getting an object from the form in play while using ajax.I want the object here instead of JSON because at the end I have persisted the object with JSON I have to iterate all of its key value and create an object.
EDIT: when I try simply ajax it gave me the same exception
$("#form-permission").on('submit', function() {
var $this = $(this);
var uid=//some uid
$.ajax({
url: '/account/permission?id='+uid,
data: $this.serialize(),
type: 'POST'
});
return false;
});
The approach I am currently using is passing a JSON from ajax request and in my controller I do Json.fromJson() to convert JSON from entity object but I just want to know why AJAX request is behaving differently than normal form submit ie why I am not able to get an entity from request when both requests are of the same type.
Thanks in advance.
Step 1: Rename all private properties to public and remove getter and setter methods.
e.g.
private String per1= "off"; to public String per1= "off";
Step 2. Ensure your route file is a GET request
Step 3. Try using basic Jquery ajax to test run.
$("#form-permission").on('submit', function() {
var $this = $(this);
$.ajax({
url: '/url/to/controller',
data: $this.serialize(),
type: 'GET'
});
return false;
});
You can always should from GET to POST at your convenience, kindly ensure you change your JQuery and html form method to POST value and also your Playframework routes file to POST.
Hope this works!
Well, the other approach which you are looking for where you want the object instead of Json at the server side --
You can always de-serialize it.
Tools like gson and fasterxml json are there and something you should be looking into. This way there is no extra effort in creating the entities you want to persist.
HTH.
I get list on my jsp using
<%List selectedArray = (List) session.getAttribute("clist");%>
is [4,5].And I am sending this list to javascript using hidden variable in jsp
<input type='hidden' id="agencycontactid" name="agencycontactid" value="<%=selectedArray%>" />
and i am taking this in javascript var abc=$('#agencycontactid').val(); .
I want to send this abc to servlet using ajax call that is through data.And i want this list in simple array format in servlet.
Please help me.
Thanks
If you wanna pass an actual array (ie. an indexed array) then you can do:
$.post('/url', {'someKeyName': ['value','value']});
You can also build a param string by looping other the data (in my case a multi-select)
$(".choosenItems option").each(function() {
chosenStr = chosenStr + "&chItems=" + $(this).val();
});
so if you create a queryString of
...?name=Fred&name=Joe&name=Sally
then in your servlet you can do
String names[] = request.getParameterValues ("name");
I want to read parameter passed by one JSP to another using HTTP POST method.
Following are my two JSP files.
One.jsp
<body>
<form action="Two.jsp" method="post">
<input type="text" value="test value" name="txtOne">
<input type="submit" value="Submit">
</form>
</body>
Two.jsp
<body>
<% response.getWriter().println(request.getParameter("txtOne")); %>
</body>
I can access the parameter in Two.jsp file using scriplet.
I want to avoid scriplet, so I am looking for JavaScript or jQuery solution.
So far I have searched and found JavaScript solution which only reads parameters sent using GET method(query string only).
Any suggestion will be appreciated.
Thanks in advance.
Solution:
I was able to get the value using JSTL:
${param.txtOne}
Try expression language - ${txtOne}, of if the method in one.jsp is GET instead of POST, you would be able to read URL in javascript and extract parameter value from there.
Yes you can get the value by use of JSTL
${param.txtOne}
Update
From EL info page
In EL there are several implicit objects available.
EL Scriptlet (out.print and null checks omitted!)
---------------------------------- ---------------------------------------------
${param.foo} request.getParameter("foo");
${paramValues.foo} request.getParameterValues("foo");
${header['user-agent']} request.getHeader("user-agent");
${pageContext.request.contextPath} request.getContextPath();
${cookie.somename} Too verbose (start with request.getCookies())
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
I want to avoid scriplet, so I am looking for JavaScript or jquery solution.
Simply you cannot.
request object can only accessible on server side, i.e in your JSP. You cannot access request or response object in client side that i.e javascript/jquery/whatever.
If you want access jsp value in javascript, try something like
var news=<%= request.getParameter("txtOne")) %>;
As a side note: Avoid scriplets and go for Expression language.
It is time for you to move to some MVC framework like struts than plain JSP. Then you can fill an ActionForm from parameters and use them on Two.jsp.
I want to access a model attribute in Javascript. I use the following code:
model.addAttribute("data", responseDTO);
My DTO class:
public class ResponseDTO {
private List<ObjectError> errors;
private Boolean actionPassed;
private String dataRequestName;
// and setter getter for all fields
}
I tried accessing the DTO using:
var data = "${data}";
But it is giving me a string representation of responseDTO instead, i.e com.req.dto.ResponseDTO#115f4ea. I can successfully access a field inside the DTO using:
var data = "${data.actionPassed}";
But this is not working for the errors attribute inside the DTO, as it is a List of ObjectError. How can I get complete responseDTO object in Javascript?
Thanks!
EDIT :
Initially I was using jquery.post
$.post('ajax/test.html', function(data) {
// Here I was able to retrieve every attribute even list of ObjectError.
});
Now I want to remove Ajax and want to convert it into non-ajax approach (because of some unavoidable reasons). So I am doing a normal form submit and want load same form again and trying to load data model attribute in Javascript so that I can keep the rest of the code as it is.
I was wondering if it can be achieved in Javascript as it is doable using Jquery post?
EDIT 2 :
I tried (Thank you #Grant for suggestions)
JSONObject jsonObject =JSONObject.fromObject(responseDTO);
String jsonString = jsonObject.toString();
model.addAttribute("data",jsonString);
and in Javascript
var data = eval('('+ ${dataJson} +')'); // Getting error on this line
alert(data.actionPassed);
But getting error and no alert is displayed
Error :
First of all, there's no way to convert a Java object to a Javascript object directly since they have nothing to do with each other. One is server-side language and the other is client-side language.
So to accomplish this goal, you have to do some convertion. I think you have two options:
Convert ResponseDTO object to JSON string and pass it to jsp and you may get the javascript object directly.
Pass ResponseDTO object to JSP and populate the javascript object as what you are trying now.
For option #1, you should use a library to generate JSON string by the Java object. You can use this one JSON-lib.
e.g:
JSONObject jsonObject = JSONObject.fromObject( responseDTO );
/*
jsonStr is something like below, "errors" represents the List<ObjectError>
I don't know what's in ObjectError, errorName is just an example property.
{
"dataRequestName":"request1",
"actionPassed":true,
"errors":[{"errorName":"error"},{"errorName":"unknown error"}]
}
*/
String jsonStr = jsonObject.toString();
model.addAttribute("dataJson", jsonStr);
/*In JSP, get the corresponding javascript object
by eval the json string directly.*/
<script>
var data = eval('('+'${dataJson}'+')');
</script>
For option #2,
//Pass java object as you do now
model.addAttribute("data",responseDTO);
//In JSP, include jstl taglib to help accessing List.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script>
var errorArr = [], errorObj;
<c:forEach var="error" items="${data.errors}">
errorObj = { errorName: '${error.errorName}' };
errorArr.push(errorObj);
</c:forEach>
//Populate the corresponding javascript object.
var data = {
dataRequestName: '${data.dataRequestName}',
actionPassed: ${data.actionPassed},
errors: errorArr
};
</script>
As you can see, option #2 is complicated and only useful if the Java object is simple while option #1 is much easier and maintainable.
So I just implemented a similar solution to Grant's first option with a List of objects, but used the Gson library to convert the object to a JSON string, then used JSON.parse() to turn it into a javascript object:
On the server:
List<CustomObject> foo = database.getCustomObjects();
model.addAttribute("foo", new Gson().toJson(foo));
In the page javascript:
var customObjectList = JSON.parse('${foo}');
console.log(customObjectList);
Notice that when I reference the model object foo, that I do so as a string '${foo}'. I believe you are getting your error because you reference it outside of a string. So the correct code would be:
var data = eval('('+ '${dataJson}' +')');
its very simple
in your spring controller
model.addAttribute("attributeName", "attributeValue");
in the script
<script type="text/javascript">
$(window).on('load', function () {
var springAttribute= '${attributeName}';
alert(springAttribute);
</script>
a little back story:
I am working on a file that got to be very large, eventually resulting in the following error:
The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit.
In order to get around this, I have been "modularising" the file by utilizing the jsp:include tags. I have successfully passed objects from the main file to the included file by serializing the objects and using the jsp:param tag and then deserializing in the jsp:include file. However, being as though these objects are used, modified and reused and re-modified in the main file and in multiple included files. I am wondering
if there is a way to pass back the object to the main file after rendering the included file OR if there is a way to access these objects by reference so that they can be modified within one included file and the right instance of the modified object could be reused other included files below it?
So far I have considered pagecontext.setAttribute() (which does not seem to be by ref and does not seem to let me pass the value back after being modified to the main file) and jsp:param (pretty much the same thing as as the pagecontext.setAttribute()).
This is what I have so far:
Code Sample below: (I hope this doesn't confuse anyone. I'm not looking for syntax corrections, I'm just looking for a solution that will allow the same object to be accessed by reference (such as a global variable along with the include tags) or for me to pass the object back to the main.jsp so that the next jsp:include can access it after it's been modified.
Main.jsp
//Serialized Objects, Google Gson object
Gson gson = new Gson();
String serializedObject = gson.toJson( objectName );
<jsp:include page="/includes/includedFileName1.jsp">
<jsp:param name="serializedObject" value="<%= serializedObject %>" />
</jsp:include>
<!-- Is there a way to ensure includedFileName2 .jsp gets the modified version of object from includedFileName1.jsp? -->
<jsp:include page="/includes/includedFileName2.jsp">
<jsp:param name="serializedObject" value="<%= serializedObject %>" />
</jsp:include>
<!-- Is there a way to ensure includedFileName3 .jsp gets the modified version of object from includedFileName2.jsp? -->
<jsp:include page="/includes/includedFileName3.jsp">
<jsp:param name="serializedObject" value="<%= serializedObject %>" />
</jsp:include>
includedFileName1.jsp
//Gson object used to convert serialized strings to java objects
Gson gson = new Gson();
ObjectType object = null;
if (null != request.getParameter("serializedObject")) {
object = gson.fromJson(request.getParameter("serializedObject"), ObjectType.class);
}
if (x = y) {object = somethingNew1;}
//is there a way to pass object back to the main.jsp?
includedFileName2.jsp
//Gson object used to convert serialized strings to java objects
Gson gson = new Gson();
ObjectType object = null;
if (null != request.getParameter("serializedObject")) {
object = gson.fromJson(request.getParameter("serializedObject"), ObjectType.class);
}
if (x = y) {object = somethingNew2;}
//is there a way to pass object back to the main.jsp?
includedFileName3.jsp
//Gson object used to convert serialized strings to java objects
Gson gson = new Gson();
ObjectType object = null;
if (null != request.getParameter("serializedObject")) {
object = gson.fromJson(request.getParameter("serializedObject"), ObjectType.class);
}
if (x = y) {object = somethingNew3;}
//is there a way to pass object back to the main.jsp?
The object may or may not be modified but has to be accessible from all three includes and the objects latest changes has to be accesible.
Thank you for your time.
Thanks #home, #Ashley ...
I re-thought the way this was implemented and resolved my issue using request.setAttribute() and request.getAttribute().
<%
//set new parameters to be passed through to the jsp:include
request.setAttribute("objectName", objectInstance);
%>
<jsp:include page="/includes/requisitionClinicalConditionContent.jsp"/>
<%
//get parameters passed from the jsp:include
objectInstance = (object) request.getAttribute("objectName");
%>
I pass through the object using request.setAttribute() and receive it in my jsp:include. If it was modified within the jsp:include (which it isn;t in most cases, but I do have 1 or two cases which may modify the value), I return the object from the jsp:iclude using request.setAttribute(0 and recive it back in my parent jsp page.
Thanks for all the help, I'm sorry I didn't reply back sooner.