Passing javascript variable to spring MVC controller with request param - javascript

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

Related

Passing spring java object to 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>);
});

In an action method, how can I bind post data to a dynamic object?

I want to do this:
public ActionResult SaveStuff(dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
This doesn't work, MVC doesn't seem to want to create a dynamic object with properties that correspond to the post data of the request.
Now I know that the whole point of properly defined view models is to create strongly typed data structures and have MVC bind data into them, but given that I'm posting data from javascript using ajax it's not strongly typed data anyway, so I don't see that I'm loosing any maintainability by doing this, and it will save me time and effort creating view model classes.
Can anyone help suggest how I can bind post data to a dynamic object, posssibly using a custom model binder?
One possible way to achieve this would be to use a custom model binder, assuming that you are posting Json to the action
public class DynamicBinder : IModelBinder
{
public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
using( var streamReader = new StreamReader( controllerContext.HttpContext.Request.InputStream ) )
{
return JsonConvert.DeserializeObject< dynamic >( streamReader.ReadToEnd() );
}
}
}
then in your action you can tell it, to use the custom binder
public ActionResult SaveStuff([ModelBinder(typeof(DynamicBinder))]dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
then post your json as such :
{
"myvalue":{...}
}
dynamic type and ajax request that you do with javascript is not corresponding.
You always can create your strongly typed object properties on javascript side.
Anyway you can use FormCollection like this:
[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
StoreTheValue(Convert.ToString(collection["myvalue"]));
return Content("Saved :)");
}
But I think it's better to think of a strongly typed way.

setting variables in javascript in jasp from ini file

In my spring mvc project i have a properties.property file whose structure is as such
TestOrderURL=blah
LiveOrderURL=blah1
These values are used in my controller and are read using the #Value annotation.
The view [.jsp] has a javascript function which has variables that need to have their default value set from the above properties file. Is there a way to set this?
My HomeController.java
#RequestMapping(value = "/Home.html", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
logger.info("Welcome home! the client locale is "+ locale.toString());
return "Home";
}
Set your variables from controller to some specific scope i.e HttpSession so that you could access them in your javascript via Expression Language or Scriptlet.
UPDATE:
In your controller call:
request.getSession(false).setAttribute("YourProperty",propertyvalue);
then in javascript access them like:
var property=<%=session.getAttribute("YourProperty")%>;
UPDATE:
Change your controller method to this:
#RequestMapping(value = "/Home.html", method = RequestMethod.GET)
public String home(Locale locale, Model model,HttpServletRequest request)
{
request.getSession(false).setAttribute("YourProperty",propertyvalue);
logger.info("Welcome home! the client locale is "+ locale.toString());
return "Home";
}
or you could set in Your model also.

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.

asp.net mvc url to string

i am creating mvc application and is it possible to get the url to string somehow?
my url is like:http://localhost:7264/Asortiman/Browse?kategorije=327
and in the head of some view i would like to get this url like string and take last 3 digits in this case 327 and use it as param in my function.
Why dont you do it at the Controller level and send it with the ViewBag dynamic object?
I Suppose your Controller is Asortiman and your Action method is Browse. Then if you define your method like;
public ActionResult Browse(int kategorije){
ViewBag.KategoriJe = kategorije;
return View();
}
Then at the view you can now reach it with the same dynamic object. For further use see the default mvc application project at the vs2010

Categories

Resources