2010-08-11 14 views
6

Para mi unidad de pruebas que utilizan un simple análisis de servidor basada en el embarcadero:Servlet 3.0 en apoyo embarcadero incrustado 8,0

package eu.kostia.textanalysis.webservices.jetty; 

import java.awt.Desktop; 
import java.net.URI; 

import org.eclipse.jetty.server.Server; 
import org.eclipse.jetty.webapp.WebAppContext; 

public class TestServer { 
static private final String CONTEXT_PATH = "/webservice"; 
static private final String PROJECT_HOME = System.getenv("MY_WORKSPACE_HOME") + "/WebServices"; 
static public final int PORT = 8080; 

private Server server; 
private Exception startException; 

private static class SingletonHolder { 
    private static final TestServer INSTANCE = new TestServer(); 
} 

/** 
    * Returns the singleton instance of the test server. 
    * 
    * @return the singleton instance of the test server. 
    */ 
public static TestServer getInstance() { 
    return SingletonHolder.INSTANCE; 
} 

private TestServer() { 
    server = new Server(PORT); 

    WebAppContext context = new WebAppContext(); 

    context.setDescriptor(PROJECT_HOME + "/web/WEB-INF/web.xml"); 
    context.setResourceBase(PROJECT_HOME + "/web"); 
    context.setContextPath(CONTEXT_PATH); 
    context.setParentLoaderPriority(true); 


    server.setHandler(context); 
} 

/** 
    * Start the test server. This method returns only when the server is 
    * complete started. There is no effect when you invoke this method and the 
    * server is already running. 
    */ 
public void start() { 
    if (!server.isRunning()) { 
    startException = null; 
    new Thread("TestServer") { 
    public void run() { 
    try { 
     server.start(); 
     server.join(); 
    } catch (Exception exc) { 
     startException = exc; 
    } 
    } 
    }.start(); 

    while (true) { 
    if (startException != null) { 
    throw new Error(startException); 
    } 

    // Block this method call until the server is started 
    if (server.isStarted()) { 
    return; 
    } 
    } 
    } 
} 

/** 
    * Stop the test server. 
    */ 
public void stop() { 
    try { 
    if (server.isRunning()) { 
    server.stop(); 
    } 
    } catch (Exception e) { 
    throw new Error(e); 
    } 
} 

/** 
    * Returns {@code true} is the server is running. 
    * 
    * @return {@code true} is the server is running. 
    */ 
public boolean isRunning() { 
    return server.isRunning(); 
} 

public static void main(String[] args) throws Exception { 
    TestServer.getInstance().start(); 
    Desktop.getDesktop().browse(new URI("http://localhost:8080/webservice/")); 
} 

} 

Funciona muy bien para el servlet en web.xml configurado pero me gusta ahora utilizar la nueva sintaxis de anotación introducida por el servlet especificación 3.0, por ejemplo:

@WebServlet(urlPatterns = {"/hello"}) 
public class HelloServlet extends HttpServlet { 
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
       PrintWriter writer = response.getWriter(); 
       writer.print("<h1>HttpServlet using Servlet 3.0</h1>"); 
     } 
} 

¿Cómo puedo configurar SHAUD embarcadero en mi clase TestServer para procesar los servlets también a base de anotación?

Respuesta

0

Jetty 8 está implementando la especificación de servlet 3.0 pero todavía es experimental.

También podría usar el complemento glassfish 3 incrustado para ejecutar sus pruebas. Consulte los siguientes enlaces para algo de información: http://wikis.sun.com/display/GlassFish/3.1EmbeddedOnePager http://ocpsoft.com/java/using-embedded-glassfish-with-maven/ http://embedded-glassfish.java.net/

Me di cuenta al momento de escribir esto que no hay recurso autorizado para utilizando el plugin Glassfish de la manera en que se usa Jetty. Sin embargo, funciona de manera similar.

Espero que esto ayude al menos un poco.

8

Añadir a su código

context.setConfigurations(new Configuration[] { 
       new AnnotationConfiguration(), new WebXmlConfiguration(), 
       new WebInfConfiguration(), new TagLibConfiguration(), 
       new PlusConfiguration(), new MetaInfConfiguration(), 
       new FragmentConfiguration(), new EnvConfiguration() }); 

Sólo es necesario ajustar la AnnotationConfiguration para conseguir la detección automática de clases anotadas a trabajar. El resto de las configuraciones son para que pueda habilitar otros aspectos del contenedor. Supuestamente, deberías poder hacer esto desde la línea de comando, usando OPTIONS = anotaciones, jsp, (etc ...), pero nunca funcionó. Al menos de esta manera debería recoger sus clases anotadas adecuadamente en el entorno incrustado.

También como nota al margen, parece que el proyecto Eclipse embarcadero tiene la anotación desactivada de forma predeterminada, mientras que la corriente cruzada afirma tenerlas activadas por defecto. Supongo que esta es una diferencia en los archivos de configuración.

+0

Me di cuenta de que la publicación es antigua, pero descubrí que tenía los mismos problemas con el servidor incorporado incluso un año después de esta publicación. –

+1

Encontré que el AsyncContext no funcionaba del todo bien en Jetty. Lo abandoné por el momento a favor de Embedded Tomcat 7. Lo que parece estar funcionando bien por el momento. –

1

Respondiendo un año más tarde.

En la versión actual del embarcadero (8.1) se puede lograr exactamente lo que quiere con la línea de comandos:

java -jar start.jar OPTIONS=annotations,plus etc/jetty-plus.xml 

invocado desde el directorio de amarre casa.

Cuestiones relacionadas