What is the most effective method in the Java Spring Framework for transferring elements from a .properties file to a variable in JavaScript?

Currently, I am working on a Java Spring project with most of the front-end built in AngularJS, HTML, and other technologies. Within my application.properties file, I store various key-value pairs such as name, id number, password, context path, server details, UI links, and a boolean value.

    name:myName
    idNum:8888888888
    password:squirrels
    contextPath:/ilovesquirrels-ui
    server:0000

    ui.firstLink: www.google.com
    ui.secondLink: www.yahoo.com
    ui.thirdLink: www.w3schools.com

    myBool: False

While the first five properties are being read automatically into an unknown location, I want to access the last four properties in JavaScript. Ideally, I would like to extract the URLs from the UI links and the boolean value and store them in JS variables. Something like:

    var myLink1 = "something that accesses ui.firstLink in application.properties";

    var myLink2 = "something that accesses ui.secondLink in application.properties";

    var myLink3 = "something that accesses ui.thirdLink in application.properties";

Currently, I am retrieving this information from a JavaScript file containing a JSON object which duplicates the data from application.properties. However, I aim to eliminate this duplication and directly fetch the link values from the application properties file. How can I achieve this seamless retrieval process?

Answer №1

My preference is to avoid mixing JavaScript with server-side languages for the following reasons:

  • Complicates life for editors
  • Makes code harder to read
  • Creates unnecessary coupling between JS and server-side technology

Instead, I suggest using meta tags or data attributes for desired variable expressions that can be accessed with JS.

  • <body data-uifirstlink='<%=properties.getProperty("uifirstLink")%>';
    can be accessed with jQuery like this: $('body').data('uifirstlink');

    Note: It's best to use contextual data attributes in specific locations rather than body.

  • <meta name='uifirstlink' content='<%=properties.getProperty("uifirstLink")%>' />
    accessed with jQuery by:
    $('meta[name="uifirstlink"]').prop('content')

Using a service to retrieve properties is not recommended because:

  • You have to wait for the page to load before making the call and using the variables
  • It results in unnecessary Ajax calls
  • Increases dependency between client and server

Alternatively, you could explore utilizing cookies or headers, although it may not be as simple.

Answer №2

One way to incorporate dynamic content into your JSP file is by including the following script:

<script>
    var myLink1 = '<%=properties.getProperty("ui.firstLink")%>';
</script>

For those using Spring, you can create a PropertiesPlaceHolderConfigurer and utilize spring tags in your JSP. For more information, check out this resource.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing flickering caused by set Interval in angular 2+

Displaying dynamic latitude and longitude data on Google Maps while using setInterval() function. Code snippet below: this.timer = setInterval(()=>{this.getMapData();},30000); An issue arises where the map flickers when updating the data with this.get ...

Issues with the functionality of the Angular JS scope variable

Currently trying to understand angularJS, I am encountering an issue with the code in my index.html file. The dynamic typing is functioning correctly in the upper section, but the injection part seems to be malfunctioning. Any idea what might have gone wr ...

What is the process for adjusting the stack size of a thread within an Android application?

I'm encountering a stack overflow error in my service that is linked to my main activity. Is there a way to adjust the stack size within my service? I have heard about the Xss parameter, but it seems like it's not accessible in the VM options (He ...

What can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...

Leveraging AngularJS html5mode in conjunction with express.js

Client-side: when("/page/:id", { templateUrl: "partials/note-tpl.html", controller : "AppPageController" }); $locationProvider.html5Mode( true ); Html: <a ng-href="/page/{{Page._id}}">{{Page.name}}</a> Server-side: app.use("/pag ...

Avoiding the "urls" format using the onBeforeRequest function

chrome.webRequest.onBeforeRequest.addListener(function(details) { if (localStorage.on == '1') { return {cancel:true}; } }, {urls: ["*://*.domain1.net/*","*://*.domain2.com/*","*://*.domain3.com/*"], types: ["script","xmlhttpreques ...

Can you explain the significance of angle brackets in JavaScript?

After examining the JSX code example provided, I found it to be quite intriguing. const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer ...

MySQL not generating the table as expected in a Spring application

Despite following various solutions on StackOverflow, Spring fails to create the table specified in my @Entity class within my MySQL database. I've made changes in the application.properties file, adjusted the dialect settings, and verified my databa ...

Managing numerous ajax forms within a single page

Upon receiving advice from the following inquiry Multiple forms in a page - loading error messages via ajax, I am endeavoring to incorporate multiple forms within one page. The goal is to insert error messages into the corresponding input div classes. I pr ...

Tips for transferring a JavaScript variable to PHP with AJAX

I am encountering an issue while trying to transfer a JavaScript variable, obtained from clicking a button, to PHP in order to execute a MySQL query. Here is my code: function ajaxCall(nodeID) { $.ajax({ type: "POST", url: "tree.php", data: {activeNode ...

Java 6 Compatibility Issue with Android Calendar Serialization

I have encountered an issue while trying to establish an object serialization socket connection between a Java server and an Android client. The problem arises when attempting to transmit a Calendar object over this connection. Upon sending the Calendar o ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

Ways to display the length of text even when it exceeds the ng-maxlength limit

I am facing an issue where I cannot see the character count when the ng-maxlength limit is reached. var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { }); <script src="https://ajax.googleapis.co ...

Using checkboxes in Selenium WebDriver for selection purposes

I'm having trouble selecting a checkbox because the ID keeps changing dynamically, preventing me from clicking on it. How can I overcome this issue? <a id="ext-gen208" class="x-menu-focus" href="#" onclick="return false;" tabindex="-1"></a&g ...

What steps should be taken to fix the app processDebugResources error?

Whenever I make changes, a debug error occurs stating that the resources are not found. However, there is nothing wrong with the resource format and no errors can be found in the XML files (the drawables are present). What could be causing this issue? ERR ...

Utilizing the no-data-text attribute in v-combobox with Vuetify: Tips and tricks

My application includes a simple combobox, and I am trying to set a default text message to display when there are no entries in the items props. To achieve this goal, I utilized the no-data-text prop by passing a specific variable to it. <v-combobox ...

Avoiding to store scope changes within an angular modal is recommended

Currently, I am utilizing the Angular UI Bootstrap modal to make updates to an array within the scope. My goal is to have these changes saved only if I click the close button; otherwise, if I click the dismiss button, I do not want the array to be updated ...

Java - Unable to parse the date

I'm having trouble with parsing a date and encountering an unexpected exception. Here's the code snippet: import java.util.Date; String strDate = "Wed, 09 Feb 2011 12:34:27"; Date date; SimpleDateFormat FORMATTER = new SimpleDateFormat("EEE, ...

Ways to eliminate excess space in a string using Robot Framework

My Variable : 54, 22 What I desire : 54,22 I attempted the following methods: Executing Javascript code var a = 54, 22;var x = a.split(' ').join('');return x and Executing Javascript code var a = 54, 22;var x = a.replace(/&bso ...

Updating the model does not reflect changes made to AGM polygons' binding

<div *ngFor="let p of polys"> <agm-polygon #cmp [paths]="$any(p.getPath()).i" [fillColor]="'blue'" [draggable]="true" [editable]="true" [polyDraggable]="true" (p ...