简体   繁体   中英

How to use session_id for REST calls?

I'm making a multiple service calls to a service. Let's say i have to make 10 POST calls to a service. Each service require session_id cookie. If it's not provided, then the service will generate one and use it for all the service calls.

In my app i make several consecutive service calls. I can invoke those calls again in the "loop", but i need a different session_id for a single iteration.

In the code MyService component is making a service call. Filter of that service will generate session_id. But invoke() method might be invoked multiple times and I want filter to generate a different session_id for each invocation of invoke() method. Currently, session_id is getting generated once

@Component
class MyService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * T - is a request type
     * R - is a response class type
    */
    private <T,R> Optional<R> doPost(String url, T request, Class<R> responseType) {
        return Optional.ofNullable(restTemplate.postForObject(url, request, responseType));
    }

    public void invoke() {
         doPost("url1", someRequest1, SomeResponse1.class);
         doPost("url2", someRequest2, SomeResponse2.class);
    }
}

I can create a session_id in invoke() method and make sure that a different session_id is used to make these calls. All service calls in invoke() will have the same session_id and next invocation will have a different one. But i am not sure if this approach is a right way to achieve this goal.

What can you advise me to use?

session_id is generated by each client (if you test from other web browser you will see a different session_id), the only way that receive a different for each request is invalidating the session, althoung if your require a uuid by request use a listener

public class ProjectRequestListener implements ServletRequestListener {    

 @Override
 public void requestInitialized(ServletRequestEvent requestEvent) {
     requestEvent.getServletRequest().setAttribute("requestId", UUID.randomUUID());
 }

 @Override
 public void requestDestroyed(ServletRequestEvent requestEvent) {
    requestEvent.getServletRequest().setAttribute("requestId", null);
 }
}

and add the listener to the project web.xml

<listener>
    <listener-class>
    com.project.server.ProjectRequestListener
    </listener-class>
</listener>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM