Java tutorial
/* * Copyright 2016 biendltb. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.biendltb.main_server; import java.io.IOException; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.springframework.core.io.ClassPathResource; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; /** * * @author biendltb * @email biendltb@gmail.com * @version 1.0 */ public class TripMapServer { private static final int DEFAULT_PORT = 8080; private static final String CONTEXT_PATH = "/"; private static final String MAPPING_URL = "/*"; private static final String CONFIG_LOCATION = "com.biendltb.config"; private static final String DEFAULT_PROFILE = "dev"; public static void main(String[] args) throws Exception { new TripMapServer().startJetty(getPortFromArgs(args)); } private static int getPortFromArgs(String[] args) { if (args.length > 0) { try { return Integer.valueOf(args[0]); } catch (NumberFormatException ignore) { } } return DEFAULT_PORT; } private void startJetty(int port) throws Exception { Server server = new Server(port); server.setHandler(getServletContextHandler(getContext())); server.start(); server.join(); } private static ServletContextHandler getServletContextHandler(WebApplicationContext context) throws IOException { ServletContextHandler contextHandler = new ServletContextHandler(); contextHandler.setErrorHandler(null); contextHandler.setContextPath(CONTEXT_PATH); contextHandler.addServlet(new ServletHolder("default", new DispatcherServlet(context)), MAPPING_URL); contextHandler.addEventListener(new ContextLoaderListener(context)); contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString()); return contextHandler; } private static WebApplicationContext getContext() { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setConfigLocation(CONFIG_LOCATION); context.getEnvironment().setDefaultProfiles(DEFAULT_PROFILE); return context; } }