[Server] Redirect HTTP to HTTPS using Servlet Filter

1. Write a filter to redirect from http to https


package vn.nvanhuong.servlet;

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;

public class HTTPSFilter implements Filter {

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;

String uri = req.getRequestURI();
String getProtocol = req.getScheme();
String getDomain = req.getServerName();
String getPort = Integer.toString(req.getServerPort());

if (getProtocol.toLowerCase().equals("http")) {

// Set response content type
response.setContentType("text/html");

// New location to be redirected
String httpsPath = "https" + "://" + getDomain + ":" + getPort
+ uri;

String site = new String(httpsPath);
res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
res.setHeader("Location", site);
}

// Pass request back down the filter chain
chain.doFilter(req, res);

}

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

@Override
public void destroy() {
// TODO Auto-generated method stub

}

}

2. Compile above filter and create following entries in web.xml


<!-- HTTPS Redirect -->
<filter>
<filter-name>HTTPS</filter-name>
<filter-class>vn.nvanhuong.servlet.HTTPSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HTTPS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

References
[1]. http://www.tutorialspoint.com/servlets/servlets-page-redirect.htm
[2]. http://www.easywayserver.com/blog/jsp-get-url/

Advertisements

Posted on 07/12/2013, in Network and tagged , , . Bookmark the permalink. Bạn nghĩ gì về bài viết này?.

Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất / Thay đổi )

Connecting to %s

Advanced programming

Tự học lập trình Android, android wear - lập trình smartwatch, Windows phone, Web service, C++, C#, java, Swift, Python, kotlin...

Tôi IT - Change the world

Research + Technical -> Programming,

juliansherman.net/

Building A Business While Having A Life

VN.NVANHUONG

No Pain No Gain

Study and Share's Blog

Việt Nam tươi đẹp...

Broly

One of the best way to learn is by writing to the paper.

%d bloggers like this: