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.
Related
I'm still learning JS, Thymeleaf, and Spring Boot and can't seem to figure out how I can use data variables in my JavaScript file and send them to a database through Spring MVC controller. Here is what I have so far:
html:
<body>
<!--PRINT OUT TEST_VAR HERE FOR USERS TO SEE DATA-->
<script src="../static/js/TEST.js" type="text/javascript" th:src="#{/js/TEST.js}"></script>
</body>
JavaScript:
var TEST_VAR = 37;
Java/Spring MVC Controller:
#RequestMapping(value = "TEST_VAR", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("test_db", "test_var");
return "TESTindex";
// Not sure what to write in the controller.
}
in a SpringBoot Controller, the "value" in the requestmap annotation is where the end point is binded to
so the example below binds to "abc.com/api/v1/17"
and 17 is the variable that will be readed from path (because if you use GET method, you need to read data from path) Get methods doesn't have request body (investigate GET and POST method diffrences, if you need )
#RequestMapping(value = "/api/v1/{id}", method = GET)
public String getFoosBySimplePathWithPathVariable(
#PathVariable("id") String id) {
return "you send id = " + id;
}
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
I am trying to pass dynamic parameters from jquery to mvc controller. This is my jquery function
function OpenBrowserUrl(type, params)
{
window.open("{0}?linkType={1}&{2}".format(URL.openBrowserLinkURL, type, $.param(params)), '_blank');
}
params would be different things based on who passes it in. For example, it's an object like this: var param = { P1: "Test1", P2: "Test2" }
I am trying to bind those in MVC Controller. This is what it looks like right now:
public virtual RedirectResult OpenBrowserLink(object urlParameters)
{
IDictionary<string, object> paramsPair = new RouteValueDictionary(urlParameters);
foreach (var item in paramsPair)
{
System.Diagnostics.Debug.WriteLine(item.Key);
}
}
However, it's not binding properly. the values are empty. On fiddler, this is how it's sending data: http://www.url.com?param1=1¶m2=2¶m3=3
Any idea what's going on? or Is there a better way to handle this? Basically I am trying to mimic the way Html Helpers send parameters and bind it from the controller side using JQuery. HtmlHelper example: Html.TextboxFor(m => m.Text, new { Param1=1, Param2=2, Param3=3 });
Thanks a lot for the help
Model binder won't work because your object urlParameters has no properties. You should either create strongly typed model:
public class UrlParamerters
{
public string Param1 {get; set;}
public string Param2 {get; set;}
public string Param3 {get; set;}
}
or change your action signature:
public virtual RedirectResult OpenBrowserLink(string[] params)
and just pass an array or parameters.
I'm trying to build some web pages in JSP (framework Spring MVC 4) using Polymer 1.0.
I would like to see some values from the Java object "User" in the web page but I can't understand how can I do to retrieve these values on Polymer.
First, I set a new object User in the Spring Controller and the method test() will retrieve a ModelAndView object:
#RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() {
logger.info("-- Method: test()");
User user = new User();
user.setFirstname("fname");
ModelAndView data = new ModelAndView();
data.addObject("user", user);
data.setViewName("test");
return data;
}
After this, I put the ModelAndView object in my custom element in Polymer:
...
<custom-element userdata="${user}"></custom-element>
...
Finally, I create my "custom-element" using Polymer library:
<dom-module id="custom-element">
<template>
<span>{{userdata.firstname}}</span>
</template>
<script>
Polymer({
is: "custom-element",
properties:
{
userdata:
{
type: Object
}
}});
</script>
</dom-module>
When I launch the webpage, I can't see the value "fname" in the page...why? What I'm doing wrong?
Thanks in advance
i don't see any binding issue in your code with polymer .
if your jsp is showing null for the {{user.firstname}} implies that there should be an error in request mapping in the controller. As a result this method test is never called to set the Firstname variable of the user model.
make sure the mapping is done properly in MVC
Trying to pass a dictionary from JS to MVC with no success. The data (reportIdAndStatus in mvc controller) is null.
I'm using angular $resource and MVC 3. Thanks.
Angular Controller:
var reportStatusdictionary = {};
//build a dictionary
for (var x = 0; x < reports.length; x++) {
reportStatusdictionary[reports[x].Id] = reports[x].StatusId
}
reportsService.getReportStatusComment({ reportStatusdictionary: reportStatusdictionary }
Angular Resource Definition:
getReportStatusComment:
{
method: 'GET',
params: { reportIdAndStatus: '#reportIdAndStatus', command: 'GetReportStatusComment' },
isArray: false
}
MCV Controller:
[HttpGet]
public string GetReportStatusComment(Dictionary<Guid, int> reportIdAndStatus)
Request In Browser:
Instead of dictionary,I'd recommend creating a view model for simplicity and ease of debugging purposes. You can do as below:
Create view model like below:
public class ReportViewModel
{
public Guid Id{get;set;}
public int StatusId{get;set;}
}
Then your controller will look like
[HttpGet]
public string GetReportStatusComment(IEnumerable<ReportViewModel> reportViewModel)
Then your get url will be
http://localhost:53854/report/getreportstatuscomment?[0].id=guidValue1&[0].StatusId=1&[1].id=guidValue2&[1].StatusId=2
You can easilty construct the url structure like this in your JavaScript Code. You can read more on model binding at #Darin Dimitrov's answer, Phil Haack's blog post and MSDN magazine article.
Update
If you don't want to build that url structure then you can send JSON to server.