Friday, September 16, 2016

Moving from Blogger to Medium

I have moved my blog form blogger to Medium:

https://medium.com/@daveford


Also see our web site for my new Instructor-led React Training workshop.

Thursday, September 01, 2016

Enable Cross Domain Requests on Java Web App

By default, a web page can only make AJAX requests to the same domain that the web page came from.

In other words, JavaScript in:

http://www.smart-soft.com/index.html

Can only make ajax requests to:

http://www.smart-soft.com

For example:

http://www.smart-soft.com/rest-api/products.json

If you would like to make your HTTP service callable from other domains you can achieve this by using the following servlet filter:

public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) 
    throws ServletException {
    }

    @Override
    public void doFilter(
       ServletRequest servletRequest,     
       ServletResponse servletResponse, 
       FilterChain chain) 
       throws IOException, ServletException {
           HttpServletRequest request = 
             (HttpServletRequest) servletRequest;

        HttpServletResponse resp = 
            (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "GET,POST");
        resp.addHeader("Access-Control-Allow-Headers", 
            "Origin, X-Requested-With, Content-Type, Accept");

        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {

    }
}