Results 1 to 2 of 2
Thread: How redirect a request to https
- 11-11-2009, 04:56 PM #1
Member
- Join Date
- Nov 2009
- Posts
- 1
- Rep Power
- 0
- 11-12-2009, 03:26 AM #2
Something like this is likely best done in a servlet filter, that is mapped to the path(s) or path pattern(s) you wish to enforce https only acess on.
The HttpServletRequest object contains four useful methods to help us
isSecure() : returns true if the request is coming in on a https connection (thus, we would not need to do a redirect
getServerName() : returns the dns name that this request was invoked with
getRequestUri() : returns the full url path this request was invoked with
getQueryString() : returns the query parameters, if any this request was invoked with.
Putting these ideas together, the doFilter() method of your filter might look something like:
Where here I assume the redirect server name is the same as the http name and the port is the https default. if this is not the case, these could be specified as init parameters in the web.xml.Java Code:public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // if the scheme is not https if (!request.isSecure()) { // generate full URL to https StringBuilder newUrl = new StringBuilder("https://"); newUrl.append(request.getServerName()); if (httpRequest.getRequestURI() != null) { newUrl.append(httpRequest.getRequestURI()); } if (httpRequest.getQueryString() != null) { newUrl.append("?").append(httpRequest.getQueryString()); } httpResponse.sendRedirect(newUrl.toString()); } else { // already a secure connection, no redirect to https required. if (chain != null) { chain.doFilter(request, response); } } }
Similar Threads
-
How to redirect the output
By Java Tip in forum java.ioReplies: 0Last Post: 04-04-2008, 02:36 PM -
How to redirect the output
By JavaBean in forum Java TipReplies: 0Last Post: 10-04-2007, 09:30 PM -
how to redirect the browser
By simon in forum Java AppletsReplies: 1Last Post: 08-02-2007, 05:24 PM -
How can I redirect in servlet?
By Heather in forum Java ServletReplies: 1Last Post: 07-14-2007, 05:52 PM -
How to post HTTPS request from java client to server
By Desai in forum NetworkingReplies: 1Last Post: 07-14-2007, 05:15 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks