Is there a way to assign the value of a textfield to a session attribute in JSP prior to rendering?

Imagine I have the following code snippet:

<html>
<head>
    <script>
        function setSession()
        {
            var roll=document.getElementById("rollno").value;
            session.setAttribute("rollno", roll);
        }
    </script>
</head>
<body>
    <form action="process.jsp">
        RollNO: <input type="text" name="rollno" id="rollno" onblur=setSession()>
        Admission no <input type="text" name="anum" id="anum">
        <input  type="submit" value="Next"/>
    </form>
</body>
</html>

I am looking for an alternative solution to setting a session attribute when input is entered into the text field before form submission. Is there another way to store this information without submitting the form?

Answer №1

It's not possible to achieve your goal directly as the user session is not maintained on the client side after the JSP page rendering, due to HTTP being a stateless protocol.

A common solution is to use a Servlet to handle session data. By submitting your form to this servlet using a POST request, you can access the HttpSession from the HttpRequest parameter in the doPost method and store your variable there. You can then redirect the client to a target JSP page with a GET request.

If you prefer to avoid form submission, AJAX can be used. For example, jQuery's $.ajax function:

var params = {
    rollno: document.getElementById("rollno").value
};
$.ajax({
    url: 'myServlet?' + $.param(params),
    type: 'post'
});

The servlet implementation would look like this:

@WebServlet(name="myServlet", urlPatterns={"/myServlet"})
public class MyServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        // store the request parameter in the session
        session.setAttribute("rollno", req.getParameter("rollno"));
        // redirect user if not using AJAX
        // resp.sendRedirect("myOtherPage.jsp");
    } 
}

Answer №2

Easiest method to configure a servlet without the need to submit/render a form directly using the servlet.

Sample code snippet for creating a TextField:

Roll Number: <input type="text" name="rollno" id="rollno" onblur="setSession(this.value)">

Javascript code for the file that contains the textfield:

function setSession(roll)
{   
    var req = getRequestObject();
    req.onreadystatechange = function(){ handleServerResponse(req); };
    req.open("GET", "set_session.jsp?rollno=" + roll, true);
    req.send(null);   
}

function handleServerResponse(req)
{ 
    if(req.readyState == 4)
    {
        alert("Session has been successfully established.");
    }
}

function getRequestObject()
{
    if(window.XMLHttpRequest)
    {
        return(new XMLHttpRequest());
    }
    else if(window.ActiveXObject)
    {
        return(new ActiveXObject("Microsoft.XMLHTTP"));
    }
    else
    {
        return(null);
    }
}

Contents of file set_session.jsp:

<%
    String rollno = request.getParameter("rollno");
    session.setAttribute("roll", rollno);
%>

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

Is there a way for me to automatically generate and send a random collection each time a GET request is made on my Node.js

I have been developing a typing application that utilizes an API to fetch random quotes from . I successfully created an API using MongoDB, Node.js, and Express which functions well. However, I encountered an issue when trying to send a random collection ...

A guide to categorizing and tallying JSON data based on multiple keys within the past 30 days using JavaScript/jQuery

I am facing an issue while trying to display a chart and extract specific data from an array. My goal is to generate a chart based on three columns in a JSON array: Source, Campaign, and Date. The process involves grouping the data, counting it, and then ...

Adjust SVG size to fit parent container/division

I am trying to make the SVG completely fill the containing TD. I don't care about preserving the proportions of the SVG. Instead, I want the height of the SVG to be the same as its width when the height should be larger than the width. There is paddin ...

The scroll event listener activates based on the distance I have scrolled

const processChatRead = useCallback(() => { const chatWindow = refEntries.current; if ( chatWindow.scrollTop > chatWindow.scrollHeight - 800 && activeRoom && conversations?.content?.length > 0 && ...

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

One particular Django template is failing to load the CSS, while the rest of the templates are

In my folder, I have two Django templates. One template is for the URL localhost:8000/people and it correctly fetches CSS from /m/css/style.css. The problem arises with the second template meant for the URL localhost:8000/people/some-name. This template f ...

ReactJS not responding to Bootstrap toggler button

My Bootstrap toggler button is not working in ReactJS. I did not include the jQuery scripts because I imported Bootstrap at the top. The button should only appear and function on small devices. import React from 'react'; import 'bootstrap/d ...

Two-way data bindings trigger the digest() function to iterate 10 times

I'm facing issues with angular binding and my experience level in this area is limited. I will be posting all related questions here. I have a piece of angularjs code that is triggering 10 digest() cycle reached errors. After researching similar posts ...

Selecting a event from Google Places Autocomplete using a mouse click

I have successfully implemented Google's autocomplete API as per the documentation. However, I am facing an issue with a form that is submitted via Ajax every time it changes. The problem arises when using the autocomplete feature for location selecti ...

"Utilize Bootstrap's responsive 3-column grid layout for a sleek design, complete with hidden col-12 elements below each grid

Looking to create a 100% width column below an element within a column of a bootstrap grid. For better understanding, here is what I'm aiming for: https://i.stack.imgur.com/pl1Fi.png On selecting one of the images (from 1 to x), a hidden div with di ...

When package.json is imported, files are not compressed

Currently, I am working on developing a cli package and when it comes to displaying the version, I am utilizing the version imported from package.json. Upon running tsc, the structure of the dist folder appears as follows: /dist --/package.json --/README. ...

Trouble with Loading Google Place Autocomplete API in HTML

I utilized the Google MAP Place Autocomplete API for a web project. Click here to view the code and output. <form> <input id="origin-input" type="text" class="form-control" placeholder="From"/> <br/> <input id="de ...

Unable to load CSS background image and update code

After writing the code in my CSS file, /*The code I initially wrote*/ .wrapper::before { content: ""; position: absolute; bottom: -30%; left: 0; height: 100%; width: 100%; background: url(../img/homeTrans2.svg) no-repe ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...

Changing form position dynamically based on selection can be achieved by following these steps

I am creating a website that functions as a compact Content Management System, enabling users to effortlessly modify most of the site's content. Within my rails application, I have established two models: Category and Subcategory. A Category has mult ...

Convert the string to a time format of hours and minutes (hh:mm)

I am currently working with an input field that requires a time value to be entered. The format for the Time field is in hh:mm on the 24-hour clock format, such as 7:30, 11:45, 16:10, 19:11, or 22:43. <input id="szReminderTime" type="text" value="" max ...

Using AngularJS to make repeated API calls with modified parameters

Issue - My task involves consolidating the response array into one. I am making consecutive calls to the same API, with a dynamic 'skip' parameter based on the last response. Call #1 - api(id, skip=0) Call #2 - api(id, skip+1) ... Below is the ...

The presence of a white block as the background on a webpage in Ubuntu

Currently working on a website in Ubuntu 14.10. Encountering an issue with Chrome not rendering the background correctly. The footer displays fine, covering the entire width, but the content div background remains white. Check out the image for visual re ...

Struggling to navigate the world of JavaScript and find the sum of odd numbers?

Currently facing a roadblock with a codewars exercise and in need of some assistance. The exercise involves finding the row sums of a triangle consisting of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 ...