简体   繁体   中英

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.

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 eg 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.

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