Jetty(一) web

Interllj +  Jetty

1.JettyServer.java

package com.mind.server;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class JettyServer {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8030);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        // http://localhost:8030/hello
        context.addServlet(new ServletHolder(new FirstServlet()), "/hello");
        // http://localhost:8030/hello/web
        context.addServlet(new ServletHolder(new FirstServlet("this is my web")), "/hello/web");

        try {
            server.start();
            server.join();
        } finally {
            server.destroy();
        }
    }
}

2. FirstServlet.java

package com.mind.server;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {
    private String msg = " Hello World!";

    public FirstServlet() {
    }

    public FirstServlet(String msg) {
        this.msg = msg;
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        this.process(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        this.process(request, response);
    }

    private void process(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String title="Webapp Demo";
        out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />");
        out.println("<title>" + title + "</title>");
        out.println("<body>");
        out.println("<h1>" + this.msg + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

运行结果:

Jetty(一) web_第1张图片

Jetty(一) web_第2张图片

你可能感兴趣的:(Jetty(一) web)