16 January 2016

Html5Mode in angular js for Java

Here's a sample Servlet filter implementation to allow return pages from the server with the / pattern.

Note: I've marked angularjs requests with "source" header set to "ng".

@WebFilter(urlPatterns = { "/*" })
public class Html5ModeFilter implements Filter {

@Override
public void destroy() {

}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {

HttpServletRequest request = ((HttpServletRequest) req);
boolean notNgRequest = !"ng".equalsIgnoreCase(request.getHeader("source"));
String servletPath = request.getServletPath();

if (notNgRequest && !servletPath.contains(".")) { // skip .js, .css,
// .png, etc...
if (!"/".equalsIgnoreCase(servletPath)) {
((HttpServletResponse) res).sendRedirect("/?next=" + servletPath.substring(1));
return;
}
}

chain.doFilter(req, res);
}

@Override
public void init(FilterConfig arg0) throws ServletException {

}


}
Post a Comment