简体   繁体   中英

Weird Behavior: Angular Js - Spring Rest Service

I am using Angular JS and Spring 4 rest service in middle layer. I am experiencing a weird behavior in request header. My application displays a basic dashboard of users information. First time when user logs in, the Angular JS makes a AJAX call to a rest service with user name in request header and displays data. The user can now search for another user and upon selection Angular JS now makes AJAX call to same rest service but with different user name in request header and displays the data.

But above behavior is not occurring for me. Say when XXX user logs in, rest service is getting called with User Name "XXX" and now when the user searches and tried to pull data for another user say "YYY", in IE / Chrome I see in request header "YYY" is passed as user name. But on the Spring Rest side, inside the filter method, I always see (first time user name) "XXX" in all requests.

It looks weird that this is not happening in all environments. Though I see in request header correct user name is passed but in filter method logs are printing the old / logged in user name. Below is the filter function code,

@Provider
@Priority(Priorities.HEADER_DECORATOR)
public class UserInterceptor implements ContainerRequestFilter {

    private static final Logger logger = Logger.getLogger(UserInterceptor .class.getName());
    
    
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        logger.info("requestContext.getHeaders() "+requestContext.getHeaders()); //always prints "XXX"

I did some research, but I dint find any relevant information.

I believe you are missing some annotation here. If I am reading the documentation for ContainerRequestFilter correctly you need to add '@PreMatching' annotation to your class here.

According the documentation:

In case the filter should be applied at the pre-match extension point, ie before any request matching has been performed by JAX-RS runtime, the filter MUST be annotated with a @PreMatching annotation.

JAX-RS is the process that matches an HTTP request to a particular method. I believe your issue here is that you are trying grab the header before your request has been matched to a particular path.

@Provider
@PreMatching
@Priority(Priorities.HEADER_DECORATOR)
public class UserInterceptor implements ContainerRequestFilter {

    private static final Logger logger = Logger.getLogger(UserInterceptor.class.getName());


    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        logger.info("requestContext.getHeaders() "+requestContext.getHeaders());
    }
}

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