Passing spring java object to javascript - javascript

I want to pass a java object to javascript. I am using spring as backend. For html I just passed the object to my model and I can call them in html through the "$" parameter. But in javascript it seems that this will not work.
So my question is. How can I call a passed object (which is already a json string) in javascript?
// java side
model.addAttribute("data", jsonObject);
// javascript side
// ???

You need to use ajax and call the api in the from spring controller.
#RequestMapping(value = 'url', method = RequestMethod.methodType)
public #ResponseBody List < SomeClass > getAllData(pass parameter here) {
return someResultFromHere;
}

You should add an ajax call for that specific api endpoint and use the name of the model to extract anything with in.. As brk stated you will call it and it will get value.Then you can use that to parse the data comming from the beckend of your server this is an example of the code.
// java side
model.addAttribute("data", jsonObject);
//ajax side
$getJSON('http://<yourserverip>:<yourport>/myapi/values/', function(data){
console.log(data.<yourValue>);
});

Related

Passing javascript variable to spring MVC controller with request param

Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view?
I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.
Maybe there's a way to do it with thymeleaf?
If you're using Thymeleaf then just reference the template you want to return to the user by its filename.
#Controller
public class YourController {
#GetMapping("/someUrl")
public String getTemplate(#RequestParam String templateName){
return templateName;
}
}
This would be the bare minimum that you'd need, assuming your templates are in the correct folder - by default in resources/static. If the frontend sends a GET (/someUrl?templateName=xyz) to the backend, it would return the xyz.html from your templates. If it does not find the template that was requested in the parameters then it will return a 404.
Edit: Reading through the comments I realized there might be a confusion between #RequestParam and #PathVariable. In case you want to use a path variable to define the template name, so that the frontend can call GET (/someUrl/xyz), then you can do
#Controller
public class YourController {
#GetMapping("/someUrl/{templateName}")
public String getTemplate(#PathVariable String templateName){
return templateName;
}
}
Resources for both below:
https://www.baeldung.com/spring-request-param
https://www.baeldung.com/spring-pathvariable

How to get JSON file from server? (ASP.NET)

I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.
CONST WORDS = [
["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]
Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage).
Here is a backend code
namespace LFrench
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
}
}
}
The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.
Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.
Your JQuery should look like:
$(document).ready(function(){
$.ajax({
method: "GET", accept: "application/json; charset=utf-8;",
url: 'MyPage.aspx/GetDataFromDB', success: function(data){
console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
}, fail: function(err){
console.log(err);
}
});
});
And your CodeBehind should look like:
[WebMethod]
public static string GetDataFromDB()
{
var myData = YourDbCall(); // Some method to retrieve data from database
var body = new
{
Firstname = myData.Firstname,
Lastname = myData.Lastname,
Email = myData.Email,
// Any Other Information
};
var json = JsonConvert.SerializeObject(body);
return json;
}
EDIT
Here is how your Word Set will be sent back as JSON:
[WebMethod]
public static string GetDataFromDB()
{
List<Words> WordsSet = Words.GetWords("Business");
return JsonConvert.SerializeObject(WordsSet);
}
Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console. if not you can Open Package Manager Console and run this command:
PM> Install-Package Newtonsoft.Json
You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.

How to create ajersey restful method that can accept three arrays of strings

I have been trying to send string arrays to a restful services without any luck. I have written this
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getBackgroundImages(#QueryParam("missions") String[] missions,
#QueryParam("objects")String[] objects,
#QueryParam("dates")String[] dates) {
........
return generateTxt();
}
on the javascript side I have this
var missions = new Array("One", "Two");
var objects = new Array("objOne" ,"objTwo");
var dates = new Array("1967-11-07","1977-12-17");
$.ajax({
url: "myurl/rest/UploadBackgroundFile/",
data: {'missions':missions,'objects':objects,'dates':dates},
success: function (data) {
arr = JSON.parse(data);
$('.container-fluid').css('background-image','url('+arr[0].img+')');
}
});
my problem is that this is not working and I am getting this exception
org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type
public java.lang.String UploadBackgroundFile.getBackgroundImages(java.lang.String[],java.lang.String[],java.lang.String[])
if I change the parameters to normal string and send strings from the javascript side than the method will work.
so the question is how to send and receive string arrays from the jquery ajax to the jersey restful method.
with regards,
es
Server side, you have to change the string array to a List<String> to make it work.
Client side, you can see this to help you how to send the datas. I know in title it's write PHP, but it's well explained.

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

send JavaScript object with unknown properties to asp.net MVC controller

I have read quite some blogs and stackoverflow answers on how to send a JavaScript object to an asp.net MVC controller. But all examples I have seen so far require you to know which properties the JavaScript object will have (because they all convert the JavaScript object to a C# object).
When I was using PageMethods in asp.net webforms I could send any complex JavaScript object or array (even hierarchical data) and it would be converted to a Dictionary which I could iterate. Any chance I can do something similar in asp.net MVC?
I now found a way which works for me.
I am converting my data to json and receive it as a string in my ASP.net MVC controller.
Then I use the json.net library to read the data - since this library allows me to read the data without converting it to a C# (or VB) object.
JavaScript code:
//first include the json2 library for older browsers and jQuery
$.post(url, {json: JSON.stringify(mydata)});
Server side code:
public void xyz(string json)
{
JObject j = JObject.Parse(json);
string name = (string)j.SelectToken("Products[0].Name");
//...
}
The good thing: it is "normal" json which means it is not some uncommon format or interface-type.
EDIT: I found out that I don't even need the C# json-library if I am using .net 4 - since I can convert any json string to a Dictionary with the help of the JavaScriptSerializer:
JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> data = (Dictionary<string, object>) jss.Deserialize<dynamic>(json_string);
What you can do is use jQuery plugin toDictionary, this plugin will transform your object to dictionary that asp.net MVC default model binder can understand
e.g.
$.ajax({
url: "/SomeURL",
type: "POST",
data: $.toDictionary(dataToSend)
});
Remember dataToSend is your object
This will be converted to a dictionary:
[{"key":0, "value":"something"},{"key":2, "value":"something else"},]
Obviously, you could do string,string or int, bool or etc...
For example, I have a method like this:
public int CollabSortFolder(int FolderId, Dictionary<int, int> Items)
I would call is using a GET:
/CollabSortFolder?FolderId=111111&Items=[{"Key":3685,"Value":0},{"Key":3670,"Value":1},{"Key":3687,"Value":2}]
Now as a GET it's not very elegant, but a post would work the same way.
Have you tried using the Request.Forms dictionary?
public ActionResult MyAction(FormCollection formValues)
{
}
Iterate over formValues

Categories

Resources