sriram
sriram

Reputation: 9052

Change the servlet header and redirect to other url in a filter

I'm very new to servlet and I wish to do the following.

I have a filter set up in my place:

void doFilter( ServletRequest request, 
               ServletResponse response, 
               FilterChain chain ) throws IOException, ServletException 
{
}

these filters will be called when certain url matches with the pattern.

Inside this method, I wish to do this:

  1. Change the incoming request header by putting the authenticaton key which I know

  2. And with that authentication header in place redirect the request to other url like www.test.com so that the response of that particular request will be the result of the www.test.com

Is it possible to do so?

I tried these:

response.setHeader("WWW-Authenticate","Basic MyKey")
response.setHeader("Location","www.google.com")

But after this what should I do? How do I redirect the page to google.com?

Thanks in advance.

Upvotes: 2

Views: 4832

Answers (1)

BalusC
BalusC

Reputation: 1109532

That's (fortunately) not possible. It would be a huge security breach if you could as being the web server control the headers of HTTP requests fired by the web client to arbitrary domains. It would make among others phishing very easy.

To achieve what you need, your best bet is to act as a proxy. Create and fire the HTTP request yourself programmatically using e.g. URLConnection or Apache HTTPComponents Client and pipe its response to the servlet response. Do however note that the URL in the browser address bar stays the URL of your web server.

Here's a kickoff example using URLConnection:

URLConnection connection = new URL("http://other.com").openConnection();
// Set headers if necessary via setRequestProperty().

InputStream input = connection.getInputStream();
OutputStream output = response.getOutputStream();
// Copy response body from input to output.

Upvotes: 1

Related Questions