【问题标题】:Jetty '{servlet}/{parameter}' url routingJetty '{servlet}/{parameter}' url 路由
【发布时间】:2013-06-06 14:44:55
【问题描述】:

我正在使用码头 9.0.3。

如何将诸如 www.myweb.com/{servlet}/{parameter} 的 URL 映射到给定的 servlet 和参数?

例如,URL '/client/12312' 将路由到 clientServlet,其doGet 方法将接收 12312 作为参数。

【问题讨论】:

  • 您需要使用过滤器来提取部分网址。
  • 在 web.xml 或 servlet 中使用模式?有什么例子吗?
  • 我没有例子。在 web.xml 中可以映射/client/*。对于12312,您需要从路径中提取它。

标签: java url dictionary routing jetty


【解决方案1】:

你需要担心两个部分。

  1. WEB-INF/web.xml 中的 pathSpec
  2. 您的 servlet 中的 HttpServletRequest.getPathInfo()

路径规范

在您的WEB-INF/web.xml 中,您必须声明您的 Servlet 和您的 url 模式(也称为 pathSpec)。

例子:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   metadata-complete="false"
   version="3.0"> 

  <display-name>Example WebApp</display-name>

  <servlet>
    <servlet-name>clientServlet</servlet-name>
    <servlet-class>com.mycompany.ClientServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>clientServlet</servlet-name>
    <url-pattern>/client/*</url-pattern>
  </servlet-mapping>
</web-app>

这会在名称 clientServlet 上设置实现为类 com.mycompany.ClientServlet 的 servlet,然后为传入的请求 URL 指定 /client/* 的 url 模式。

url-pattern 末尾的额外/* 允许接受以/client/ 开头的任何传入模式,这对于 pathInfo 部分很重要。

路径信息

接下来我们进入我们的 Servlet 实现。

在 ClientServlet 上的 doGet(HttpServletRequest req, HttpServletResponse resp) 实现中,您应该访问 req.getPathInfo() 值,它将接收请求 URL 中位于您的 url 模式上的 /client 之后的部分。

例子:

Request URL        Path Info
----------------   ------------
/client/           /
/client/hi         /hi
/client/world/     /world/
/client/a/b/c      /a/b/c

此时,您可以针对路径信息中的信息执行任何您想要的逻辑

【讨论】:

  • 谢谢!我做了类似的事情,但在 servlet 中我使用了 'req.getRequestURI().split("/(.*?)")[2];'而是过滤uri字符串。我将实现'getPathInfo()',它更干净。
【解决方案2】:

您可以使用Jersey 并在ResourceConfig 包中注册以下类,该类处理../worker/1234 url 模式。

阅读更多:When to use @QueryParam vs @PathParam

@Path("v1/services/{entity}")
@GET
public class RequestHandler(@PathParam("entity")String entity, @PathParam("id")String id){
   @path({id})
   public Entity handle(){

   }
}

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 2021-05-01
    • 2015-09-24
    • 2015-12-20
    • 2016-12-24
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多