2013-08-21 3 views
5

Я пытаюсь развернуть API REST на основе Джерси-весна, используя Grizzly's com.sun.grizzly.http.embed.GrizzlyWebServer. Я также хочу использовать статический контент, используя то же самое. Вот что у меня есть:GrizzlyWebServer + Весна + Джерси + служит статический контент из JAR

String host = "localhost"; 
int port = 8081; 

// For jersey + Spring 
ServletAdapter jAdapter = new ServletAdapter("jersey"); 
jAdapter.setContextPath("/api");   
jAdapter.setServletInstance(new SpringServlet()); 
jAdapter.addContextParameter("contextConfigLocation", "classpath:spring-context.xml"); 
jAdapter.addServletListener("org.springframework.web.context.ContextLoaderListener"); 
jAdapter.addServletListener("org.springframework.web.context.request.RequestContextListener");    

// create GrizzlyWebServer 
GrizzlyWebServer grizzlyServer = new GrizzlyWebServer(host, port, "webapp", false); 

// add jersey adapter 
grizzlyServer.addGrizzlyAdapter(jAdapter, new String[]{"/api"}); 

// start server 
grizzlyServer.start(); 

System.out.println("Start running server(host: " + host + ",port: " + Integer.toString(port)); 
System.out.println("Press any key to stop the server."); 

// hang on 
System.in.read(); 

// stop 
grizzlyServer.stop(); 

В «Джерси адаптер» работает нормально, но я не в состоянии получить статический контент, присутствующий в папке «WebAPP», чтобы быть подан (404 ошибка).

Моя структура папок проекта выглядит следующим образом:

GrizzlyTest 
    -- src 
    | | 
    | -- main 
    |  | 
    |  -- java 
    |  -- resources 
    |  | 
    |  -- webapp 
    |  | | 
    |  | -- index.html 
    |  -- spring-context.xml 
    | 
    -- pom.xml 

я делаю ошибку, указав путь к «веб-приложение» в строке new GrizzlyWebServer(host, port, "webapp", false); ??

Или, есть ли другой способ обслуживания статического контента?

ответ

7

Вот пример того, как служить ресурсам Jersey-Spring + статический контент из папки и из файла jar, работающего поверх Grizzly2.

https://github.com/oleksiys/samples/tree/master/jersey1-grizzly2-spring

Серверный код выглядит следующим образом:

// Initialize Grizzly HttpServer 
HttpServer server = new HttpServer(); 
NetworkListener listener = new NetworkListener("grizzly2", "localhost", 3388); 
server.addListener(listener); 

// Initialize and add Spring-aware Jersey resource 
WebappContext ctx = new WebappContext("ctx", "/api"); 
final ServletRegistration reg = ctx.addServlet("spring", new SpringServlet()); 
reg.addMapping("/*"); 
ctx.addContextInitParameter("contextConfigLocation", "classpath:spring-context.xml"); 
ctx.addListener("org.springframework.web.context.ContextLoaderListener"); 
ctx.addListener("org.springframework.web.context.request.RequestContextListener"); 
ctx.deploy(server); 

// Add the StaticHttpHandler to serve static resources from the static1 folder 
server.getServerConfiguration().addHttpHandler(
     new StaticHttpHandler("src/main/resources/webapp/static1/"), "/static"); 

// Add the CLStaticHttpHandler to serve static resources located at 
// the static2 folder from the jar file jersey1-grizzly2-spring-1.0-SNAPSHOT.jar 
server.getServerConfiguration().addHttpHandler(
     new CLStaticHttpHandler(new URLClassLoader(new URL[] { 
      new File("target/jersey1-grizzly2-spring-1.0-SNAPSHOT.jar").toURI().toURL()}), "webapp/static2/"), 
     "/jarstatic"); 

try { 
    server.start(); 

    System.out.println("In order to test the server please try the following urls:"); 
    System.out.println("http://localhost:3388/api to see the default TestResource.getIt() resource"); 
    System.out.println("http://localhost:3388/api/test to see the TestResource.test() resource"); 
    System.out.println("http://localhost:3388/api/test2 to see the TestResource.test2() resource"); 
    System.out.println("http://localhost:3388/static/ to see the index.html from the webapp/static1 folder"); 
    System.out.println("http://localhost:3388/jarstatic/ to see the index.html from the webapp/static2 folder served from the jar file"); 

    System.out.println(); 
    System.out.println("Press enter to stop the server..."); 
    System.in.read(); 
} finally { 
    server.shutdownNow(); 
} 
+0

Спасибо Алексею. У меня вопрос об аутентификации по запросам на статические ресурсы из банок, поэтому через CLStaticHttpHandler и StaticHttpHandler. Это недоказано, но похоже, что аутентификация не применяется к первому, а применяется к последнему? Эта строка в 'WebappContext' может объяснить это:' if (! (H instanceof StaticHttpHandler)) '(grizzly-http-servlet-2.3.17.jar). Мысли? Благодарю. – user598656

+0

Ну, из того, что вы нашли, похоже, могут быть некоторые проблемы. Можете ли вы PLS. поделитесь тестовой записью с github - мне будет проще сменить цвет. – alexey

Смежные вопросы