砂拉豆 发表于 2017-2-26 10:13:43

第一次使用jetty

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 test;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.FilterHolder;
public class JettyTest {
Server server;
FilterHolder dispatchFilter;
public JettyTest(String context, int port) {
this.init(context, port);
}
public JettyTest(String context, int port, String solrConfigFilename) {
this.init(context, port);
dispatchFilter.setInitParameter("solrconfig-filename",
solrConfigFilename);
}
private void init(String context, int port) {
server = new Server(port);
server.setStopAtShutdown(true);
Context root = new Context(server, context, Context.SESSIONS);
root.addServlet(Servlet404.class, "/e");
root.addServlet(Respones.class, "/r");
}
public void start() throws Exception {
if (!server.isRunning()) {
server.start();
}
}
public void stop() throws Exception {
if (server.isRunning()) {
server.stop();
server.join();
}
}
public int getLocalPort() {
Connector[] conns = server.getConnectors();
if (0 == conns.length) {
throw new RuntimeException("Jetty Server has no Connectors");
}
return conns.getLocalPort();
}
public static class Servlet404 extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.sendError(200, "Can not find: " + req.getRequestURI());
}
}
public static class Respones extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.getWriter().write("welcome");
}
}
public static void main(String[] args) {
try {
JettyTest jetty = new JettyTest("/solr", 3456);
jetty.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
页: [1]
查看完整版本: 第一次使用jetty