Dr Joe
Dr Joe

Reputation: 760

How to serve non html content from a Vaadin UI?

Is it possible to serve non-html content from a UI?

public class ObjectResource extends UI {

    public static class Servlet extends VaadinServlet { }

    @Override
    public void init(VaadinRequest request) {
        VaadinService.currentResponse.setContentType("someother/mimetype");
        response.getWriter().append("my content");
    }
}

This clearly doesn't work. I can get the kind of output behaviour I want by using a ContentHandler, however not I've worked out how to utilise that functionality directly so that it fires when the app is fire run, rather than in a subsequent request.

Is this possible?

The reason I need something like this, is that I want to support an end point that serves content to an external browser which doesn't support java script. The main app sets up some content (backed by a database), and the slave browser can consume it with a single HTTP request.

Upvotes: 0

Views: 95

Answers (1)

Dr Joe
Dr Joe

Reputation: 760

It turns out to be possible, through the use of a global RequestHandler:

public static class Servlet extends VaadinServlet {
    @Override
    protected void service(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

        getService().addSessionInitListener(new SessionInitListener() {
            @Override
            public void sessionInit(SessionInitEvent event) throws ServiceException {
                event.getSession().addRequestHandler(makeGlobalRequestHandler())
            }
        });
        super.service(request, response)
    }
}

The request handler is then available to handler the same request, and bypass the normal vaadin application handling if so desired:

RequestHandler globalRequestHandler() {
    new RequestHandler() {
        @Override
        public boolean handleRequest(VaadinSession session, VaadinRequest vaadinRequest, VaadinResponse response) {
            if ("/staticResource".equals(vaadinRequest.getPathInfo())) {
                response.setContentType("application/some-mimetype")
                response.getWriter().append("some content")
                true
            } else
                false
        }
    }
}

Upvotes: 0

Related Questions