Java tutorial
/***************************************************************************************** * *** BEGIN LICENSE BLOCK ***** * * Version: MPL 2.0 * * echocat NoDoodle, Copyright (c) 2010-2012 echocat * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * *** END LICENSE BLOCK ***** ****************************************************************************************/ package org.echocat.nodoodle.server; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ServiceServlet extends GenericServlet { private static final Logger LOG = LoggerFactory.getLogger(ServiceServlet.class); public static final String SERVICE_PARAM = "service"; private HttpService _service; @Override public void init(ServletConfig config) throws ServletException { super.init(config); final WebApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(config.getServletContext()); final String serviceName = config.getInitParameter(SERVICE_PARAM); if (StringUtils.isEmpty(serviceName)) { throw new ServletException("Required initParam " + SERVICE_PARAM + " not set."); } try { _service = applicationContext.getBean(serviceName, HttpService.class); } catch (NoSuchBeanDefinitionException e) { throw new ServletException("No service '" + serviceName + "' (defined under initParam '" + SERVICE_PARAM + "') could not be found.", e); } try { _service.init(config.getServletContext()); } catch (Exception e) { throw new ServletException("Could not initiate the service: " + _service, e); } } @Override public void destroy() { try { if (_service != null) { try { _service.destroy(); } catch (Exception e) { LOG.error("Could not clean destroy the service: " + _service, e); } } } finally { super.destroy(); } } @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { final HttpService service = _service; if (service == null) { throw new ServletException("Was the init() method not called?"); } service.handle((HttpServletRequest) request, (HttpServletResponse) response); } }