Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[jetty-users] Single page application routing

Hey everybody, i am beginner. Can somebody advise me on how to manage single page application routing? 

I need DefaultServlet to work as it works now - serve static content, handle ETags and do other stuff. 
Since JS will handle routing, on unknown route to Jetty, Jetty will throw 404 and i need to intercept these 404 errors
to output content of index.html and let JS do the work. 

What is the best way to do that? 

Launcher.java
-----------------------------------------------------------------------------
public static void main(String[] args) throws Exception
{
	Server server = new Server();

	// Remove Server:Jetty(9...) from Response Headers
	HttpConfiguration httpConfig = new HttpConfiguration();
	httpConfig.setSendServerVersion(false);
	HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);

	ServerConnector connector = new ServerConnector(server, httpFactory);
	connector.setPort(8080);
	server.addConnector(connector);

	WebAppContext context = new WebAppContext("webapp", "/");
	context.addServlet(new ServletHolder(new DefaultServlet()), "/*");

	// Map WebSocket to listen on `/ws`
	Broker broker = new Broker();
	context.addServlet(new ServletHolder( new Servlet(broker)), "/ws");

	// Setting up browser caching. Binds params for org.eclipse.jetty.servlet.DefaultServlet.init()
	context.setInitParameter("org.eclipse.jetty.servlet.Default.etags", "true");
	context.setInitParameter("org.eclipse.jetty.servlet.Default.cacheControl", "public, max-age=0");

	// Disallow directory listing
	context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

	// Search for index.html/index.jsp pages
	context.setInitParameter("org.eclipse.jetty.servlet.Default.welcomeServlets", "true");

	// Fix for Windows, so Jetty doesn't lock files
	if (System.getProperty("os.name").toLowerCase().contains("windows")) {
		context.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
	}

	// Will throw an exception when will be unable to start server for some reason
	context.setThrowUnavailableOnStartupException(true);

	server.setHandler(context);
	server.start();
}
—————————————————

I also have jersey mapping in web.xml

<servlet-mapping>
    <servlet-name>jersey-api-v1</servlet-name>
    <url-pattern>/api/v1/*</url-pattern>
</servlet-mapping>

Back to the top