Predz
Predz

Reputation: 201

getting a HttpServletRequest response address

Im using an ajax script to send a request to a servlet which in turn sends a request to a database and then when the database returns some data to the servlet, the servlet returns the result back to the web page. The problem is, this same script is used again on another page to do exactly the same thing except the output needs to be different.

My idea was to determine what page the request came from and format the response using this information.

Ive tried HttpServletRequest req.(almost everything the API allows) to try and get the required information but it doesn't appear to return what i need. I can get it to return the servlet address using request.getRequestURL but I need the webpage this request originated from, not where it was sent.

Am I missing something obvious here ?

Upvotes: 0

Views: 513

Answers (1)

Jan
Jan

Reputation: 2478

There is an HTTP Header called "Referer" that contains the information from which page the request was triggered. For AJAX requests, this header normally contains the URL of the page in which the AJAX request was triggered. You can get this header using request.getHeader("Referer"), so you could try if that is what you need.

But it's up to the client to send that header, so you cannot be sure that it will always be there. And this approach may also lead to maintainability issues, e.g. if you move you web page to a different URL. So it may be the better design to parameterize your JavaScript and you servlet, i.e. the client adds a parameter to the URL that tells the servlet from which context the request is coming from or what the expected output format is.

Upvotes: 3

Related Questions