A common practice is to check with request.isSecure () whether the request came through https or not. If not, send the redirect to the browser to the same URL, but with the https protocol prefix.
Here is an example servlet filter:
import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SecurityFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse servletResponse = (HttpServletResponse) response; if (!request.isSecure()) { HttpServletRequest servletRequest = (HttpServletRequest) request; String target = "https://" + request.getLocalName() + servletRequest.getRequestURI(); servletResponse.sendRedirect(target); return; }
To enable the filter worldwide, add the following to you web.xml:
<filter> <filter-name>securityFilter</filter-name> <filter-class>SecurityFilter</filter-class> </filter> <filter-mapping> <filter-name>securityFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The string servletResponse.addHeader("Strict-Transport-Security", ... is optional. If you put it in the code, your browser will never try to connect to http again over the next 30 days, but it will use https itself. This will happen if your browser supports the HSTS RFC6797 standard . It makes sense if your application should only be accessible via https. However, I think this is only possible with the standard https port 443. See below.
There is a tiny trap in your current tomcat configuration. Cannot start http and https on the same port. You need to have two separate sockets for http and one for https.
For this to happen, add the maven tomcat plugin configuration:
<plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <httpsPort>8443</httpsPort> . . .
You also need to add the correct protocol for the redirection purpose in the SecurityFilter code (or make it a parameter):
String target = "https://" + request.getLocalName() + ":8443" + servletRequest.getRequestURI();
Port 8080 and 8443 are for experimental local web servers only, real applications should be on ports 80 and 443.
What is it. Good luck and good luck!