XterS
XterS

Reputation: 11

How to control a session creation within java servlet?

I make a few requests from a client-side of web application, which are received by servlet.

Here is a code piece in doPost method of my MainServlet:

String requestData = req.getReader().lines().collect(Collectors.joining());
HttpSession session = req.getSession(false);
if (session == null) {
    session = req.getSession(true);
}
System.out.println("Session's id: " + session.getId());
session.setAttribute("jsonData", requestData);

There is also a LoginServlet, which sets attributes to current session.

Then, I send a request again to MainServlet, but when the doPost method is invoked again, every time a new session is created.

As I understand, it should not work like this, since if a session already exists, it should be returned anyway.

I need to preserve a session created during very first doPost call. How can I do that?

EDIT: a js fetch API request:

const sendRequest = async (data) => {
        
await fetch('http://localhost:8080/', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
         'Detail': 'requisites',
         'Content-type': 'application/json; charset=UTF-8',
         },
    })
    .catch((err) => console.log(err.message));
}

Upvotes: 0

Views: 51

Answers (0)

Related Questions