Java服务器端编程Java学习笔记

jettey内嵌启动webapp项目

2017-03-21  本文已影响103人  camlboy

jettey内嵌启动app:

首先来说jersey启动代码:

public class JettyServer {
    private void start() throws Exception {
        int port = 8080;
        Server server = new Server(port);
        ServletContextHandler context = new ServletContextHandler(
                ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        ServletHolder sh = new ServletHolder(ServletContainer.class);
        sh.setInitParameter(
                "com.sun.jersey.config.property.resourceConfigClass",
                "com.sun.jersey.api.core.PackagesResourceConfig");
        sh.setInitParameter("com.sun.jersey.config.property.packages",
                "com.gmobile.api"); //包名为jersey的路由Resource所在目录,如下代码展示
        context.addServlet(sh, "/*");
        server.start();
    }

    public void stop() throws Exception {

    }

    public static void main(String[] args) throws Exception {
        JettyServer server = new JettyServer();
        server.start();
    }
}
此处是jersey的基于注解的路由分发类:
@Path("/")
public class WelcomeResource {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/hello")
    public Viewable sayHello() throws IOException {
        return new Viewable("/index.jsp", this);
    }

    @GET
    @Path("/index")
    public String index() {
        return "hello world!!!";
    }

    @POST
    @Path("/login")
    public String login() {
        return "login";
    }

}
上一篇下一篇

猜你喜欢

热点阅读