Access Java-generated cookies in JavaScript

I'm currently working on setting cookies using Java as demonstrated here.

My goal is to utilize this cookie in JavaScript (it's necessary to do it this way due to certain limitations). However, I'm unable to detect any set cookies (using the web developer addon for Firefox).

Is there a solution for this? Can cookies be used in this manner?

Here is the Java code snippet:

try {
            // instantiate CookieManager
            CookieManager manager = new CookieManager();
            CookieHandler.setDefault(manager);
            CookieStore cookieJar =  manager.getCookieStore();

            // create cookie
            HttpCookie cookie = new HttpCookie("UserName", str);

            // add cookie to CookieStore for a
            // specific URL
            URL url = new URL("http://host.example.com");
            cookieJar.add(url.toURI(), cookie);
            System.out.println("Added cookie using cookie handler");
        } catch(Exception e) {
            System.out.println("Unable to set cookie using CookieHandler");
            e.printStackTrace();
        }

And here is the JavaScript snippet:

function Cookie(cname){
    alert("in getcookie function");
    var name = cname + "=";
    var ca = document.cookie.split(';');

    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) 
            document.getElementById("result").innerHTML=c.substring(name.length,c.length);
    }
    console.log(document.cookie);
    //document.getElementById("result").innerHTML="somewhere something went wrong!";
}

</script>

<div id="result">
    <p onclick="Cookie('JSESSIONID')">Click me</p>
</div>

The console.log did not show any output.

Answer №1

Have you considered attempting the following approach:

    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletResponse;

    Cookie newCookie = new Cookie("fileIdentifier" + fileIdentifier, fileIdentifier);
    newCookie.setMaxAge(60 * 10);
    newCookie.setPath("/");
    newCookie.setSecure(false);
    response.addCookie(newCookie);

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

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

To retrieve a property in Vue, you can use either the "this" keyword

Exploring Vue for the first time and navigating through accessing viewmodel data has me puzzled. When should I utilize this.property versus vm.$data.property. In this scenario with a table where I can select rows, there are methods in place to select all ...

Snapping a photo from the webcam for your profile picture

Is there a way to capture images using a webcam and upload them to a server in a PHP & Mysql application? I've been searching on Google but only find outdated code that is not supported in all browsers. Here are some links you can check out for more ...

Using JavaScript, extract individual objects from a JSON object

Recently, I've been tasked with displaying items from a JSON-file in a well-organized manner. However, the format of the JSON file is unfamiliar to me. The code snippet provided below pertains to this task: function readFile(file) { var rawFile = ...

Ways to update vuex state using mutations

Currently, I am facing an issue while working on an app where I'm attempting to change the Vuex state using mutations but it's not functioning as expected. Initially, the state.status is set as an empty string, and my goal is to update it to the ...

How about "Incorporate Google Auth into your Vue.js project with modular

I'm on the search for a project that showcases using Vue.js and the Google client library to authenticate with JavaScript, but without the need for transpilers, bundlers, or Node/npm. Does anyone know of such an example out there? I simply want to cre ...

Issue with visibility of pagination in AngularJS ui

I am facing an issue with pagination in my AngularJS UI application. I have a dataset that requires server-driven pagination due to its size. The problem I'm encountering is that the pagination element is not displaying on the page, even though I hav ...

Implementing Next.js with Firebase's onAuthStateChanged method allows seamless user

const checkUserAuth = () => { const [user, setUser] = useState(''); useEffect(() => { auth.onAuthStateChanged(function handleAuth(user) { if (user) { setUser(user); } else { setUser(null); } }) ...

JavaScript, change syntax from arrow to regular

Currently I'm in the process of learning and grasping JavaScript. In a tutorial video that I'm following, the instructor utilized this specific code snippet: app.post('/content/uploads', (req,res) => { upload(req, res, (err) => ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...

Updating an existing value with a cascading dropdown list

My JavaScript code dynamically populates a dropdown list called District based on the selection made by the user in another dropdown list called Department. Here is the snippet of the code: Firstly, I populate the Department dropdownlist and add a ' ...

Troubleshooting the issue of onclick not functioning in JavaScript

My attempt to utilize onclick to trigger a function when the user clicks the button doesn't seem to be successful. For instance: function click(){ console.log('you click it!') } <input type='button' id='submitbutto ...

When triggering the fireEvent.mouseOver event, it seems that document.createRange is not a valid

Having trouble using fireClick.mouseOver(tab) to test tooltip functionality on tab hover. Here's a snippet of the code: it('should handle change on hover of tab', () => { const {getByTestId, getByRole} = renderComponent('Dra ...

JavaScript Lint Warning: Avoid declaring functions inside a loop - unfortunately, there is no way to bypass this issue

In my React JS code snippet, I am attempting to search for a value within an object called 'categories' and then add the corresponding key-value pair into a new map named sortedCategories. var categoriesToSort = []; //categoriesToSort contains ...

``There is an issue with the Nodejs required module variable not updating even after deleting

Feeling puzzled about the situation. Module 2 is supposed to require a variable from module 1, but even after deleting the cache, the variable in module 2 refuses to update when changes are made. Sample Module 1 var num = 6 function changeNum(){ num = ...

Exploring Angular 1.5: A guide to binding a transcluded template to a component's scope

Currently, I am utilizing a form component that includes common validation and saving functions. Inputs are injected into the form as transcluded templates in the following manner: <form-editor entity="vm.entity"> <input ng-model="vm.dirt ...

Breaking down a JSON Object in Angular 4: Step-by-step Guide

I am working on integrating a JSON API with an Angular 4 frontend, and my goal is to display the data from this JSON Object. Here is the code I have used: <div *ngFor="let Questionnaire of struc.data"> <span>{{Questionnaire.attributes.con ...

VueJS fails to display table information

I am facing an issue with rendering data from my API using VueJS 2. Although the backend services are successfully sending the data, the HTML table does not display it. There are no errors shown in the debug console, and even the Vue Debug extension for Fi ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...