开发者

Jetty: declare servlets in java in stead of web.xml when using maven

Is it possible to use the embedded java code to add servlets:

Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.getInitParams().put("useFileMappedBuffer", "false");
context.addServ开发者_运维技巧let(new ServletHolder(new MyServlet()), "/myurl");
....
server.start();
server.join();

in stead of the lengthy web.xml way:

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>package.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>MyServlet</servlet-name>
  <url-pattern>/myurl</url-pattern>
</servlet-mapping>

I know this is posible in a non-maven project, but it seems the Maven Jetty plugin requires this web.xml method.


In servlet 3.0 - yes, regardless of maven and jetty:

  • Use ServletContext.addServlet(..) where you specify the servlet name, and its class/instance/class name (3 overloaded methods)

  • Then call addMapping(..) on the returned ServletRegistration to map it to url-pattern(s)


In Servlet 3.0, servlets can be declared and mapped using the @WebServlet annotation. There is no configuration in the web.xml required, and no boilerplate Java code.

@WebServlet("/myurl")
public class MyServlet extends HttpServlet { ... }

However, the current release of Jetty (7.x) only supports Servlet 2.5. Jetty 8.x is currently in development and supports Servlet 3.0. Unless you can use Jetty 8.x, or another servlet container that supports Servlet 3.0, you may need to continue using the web deployment descriptor for defining and mapping servlets.

I believe the maven-jetty-plugin currently only supports Jetty 7 and therefore may require the web.xml as you've found. You might check to see if there is a snapshot of the maven-jetty-plugin available that uses the experimental Jetty 8.x.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜