Configuring jetty webserver in embedded mode

Here's how to configure Jetty Webserver in embedded mode to obtain

  • Servlet holder
  • memory based sessions
  • cookie based session tracking
  • server for static files
  • common filter (class Authenticationfilter, see below) for servlets and static files
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
 
import javax.servlet.DispatcherType;
import javax.servlet.SessionTrackingMode;
 
[...]
 
	private static void startServer(Configuration config) throws Exception {
 
		Server server = new Server(8080);
 
		//Init servlet context
		ServletContextHandler context = new ServletContextHandler(
				ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		context.addFilter(AuthenticationFilter.class, "/*",
				EnumSet.of(DispatcherType.REQUEST));
 
 
		//Memory based session handling
		SessionHandler sessionHandler = new SessionHandler();
		sessionHandler.setSessionTrackingModes(EnumSet
				.of(SessionTrackingMode.COOKIE));
 
		context.setSessionHandler(sessionHandler);
 
		// if needed use this to set Attributes on servlet context
		// context.setAttribute(CONNECTION_POOL, connectionPool);
 
		// Jetty should also serve static files
		ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
		staticHolder.setInitParameter("resourceBase", "WebContent"); // static content is in Directory "WebContent"
		staticHolder.setInitParameter("pathInfoOnly", "true");
		staticHolder.setInitParameter("dirAllowed", "false");
		// register staticHolder with same context as servlets so that 
		// Authenticationfilter is also invoked
		context.addServlet(staticHolder, "/*"); 	
 
                // I have plugins which have their own static files. 
                // Here's how i setup their webcontent directories:
		for (Plugin plugin : ModuleManager.getPlugins()) {
 
			staticHolder = new ServletHolder(new DefaultServlet());
			staticHolder.setInitParameter("resourceBase", plugin
					.getWebContentDir().toAbsolutePath().toString());
			staticHolder.setInitParameter("pathInfoOnly", "true");
			staticHolder.setInitParameter("dirAllowed", "false");
			context.addServlet(staticHolder,
					"/modules/" + plugin.getIdentifier() + "/*");
 
		}
 
		// Examples for registering servlets.
		context.addServlet(LoginServlet.class, "/login/*");
		context.addServlet(MainFrameServlet.class, "/main/*"); 
		context.addServlet(ProgressServlet.class, "/progress");
		context.addServlet(DefinitionsServlet.class, "/definitions");
		context.addServlet(HtmlFragmentServlet.class, "/fragments/*");
 
		// register servlets of modules and plugins
		ModuleManager.addServlets(context);
 
		// Add default servlet for 404 Error messages
		context.addServlet(DefaultServlet.class, "/");
 
		server.setHandler(context);
 
		server.start();
		server.join();
 
	}

Here's the sceleton of my Authenticationfilter class:

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;
import javax.servlet.http.HttpSession;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 
public class AuthenticationFilter implements Filter {
 
	@Override
	public void destroy() {
 
	}
 
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
 
		long time = System.currentTimeMillis();
 
		// Before servlet
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
 
		boolean allowedRequest = false;
 
		String pathInfo = request.getPathInfo();
		String servletPath = request.getServletPath();
		// System.out.println("pathInfo:" + pathInfo);
 
                // static files in folder /public and servlet with path /login are served without valid session:
		if (pathInfo != null && pathInfo.startsWith("/public/")
				|| servletPath != null && (servletPath.equals("/login"))) {
			allowedRequest = true;
		} else {
 
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
 
                        allowedRequest = ... test if user has valid credentials ...
 
		}
 
		if (allowedRequest) {
			// Invoke servlet
			chain.doFilter(request, response);
 
			time = System.currentTimeMillis() - time;
			Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);
			logger.info("Request " + request.getRequestURI() + ": " + time
					+ " ms");
 
			// After servlet
		} else {
			response.sendRedirect("/login");
		}
 
	}
 
	@Override
	public void init(FilterConfig arg0) throws ServletException {
 
	}
 
}
Drucken/exportieren
QR-Code
QR-Code programmieren:java:webserver:jetty:start (erstellt für aktuelle Seite)