如何从嵌入式Jetty URL中删除尾部斜杠?

时间:2016-05-22 04:03:25

标签: embedded-jetty jetty-9

我使用Scala的嵌入式Jetty 9.3.8.v20160314(Scala是偶然的,这是一个纯粹的Jetty问题),配置如下:

val loginService = new RepoLoginService(usersRepository, signInsRepo)

val server = new Server(8080)
server.addBean(loginService)

val security = new ConstraintSecurityHandler()
server.setHandler(security)

val constraint = new Constraint()
constraint.setName("auth")
constraint.setAuthenticate(true)
constraint.setRoles(Array[String]("user", "admin"))

val mapping = new ConstraintMapping()
mapping.setPathSpec("/*")
mapping.setConstraint(constraint)

security.setConstraintMappings(Collections.singletonList(mapping))
security.setAuthenticator(new BasicAuthenticator())
security.setLoginService(loginService)

val mapper = prepareJacksonObjectMapper

val listAccountsController = new ContextHandler("/api/accounts")
listAccountsController.setHandler(new ListAccountsController(mapper, accountsRepository))

val importBankAccountsController = new ContextHandler("/api/bank-account-transactions/import")
importBankAccountsController.setHandler(new ImportBankAccountTransactionsController(mapper, bankAccountTransactionsRepo))

val contexts = new ContextHandlerCollection()
contexts.setHandlers(Array(listAccountsController, importBankAccountsController))

security.setHandler(contexts)

server.start()
server.join()

请注意listAccountsController/api/accounts的上下文。当我卷曲/api/accounts时,我会收到重定向到/api/accounts/(请注意尾随斜杠):

$ curl --silent --verbose --user francois:francois http://localhost:8080/api/accounts
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
* Server auth using Basic with user 'francois'
> GET /api/accounts HTTP/1.1
> Host: localhost:8080
> Authorization: Basic ZnJhbmNvaXM6ZnJhbmNvaXM=
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Date: Sun, 22 May 2016 03:54:44 GMT
< Location: http://localhost:8080/api/accounts/
< Content-Length: 0
< Server: Jetty(9.3.8.v20160314)
<
* Connection #0 to host localhost left intact

我尝试添加对clearAliasChecks()的调用,我不确定是否与此相关。我也尝试将mapping.setPathSpec("/*")更改为mapping.setPathSpec("/"),因为我读了answer on Tomcat not adding the trailing slash,但这可能不适用于我。

我必须更改什么才能防止斜杠?

1 个答案:

答案 0 :(得分:4)

您定义上下文的方式就是这个原因。

ContextHandler是&#34; root&#34;到一组资源,并且root被定义为始终是资源目录(在结构中)。

由于您定义了ContextHandler("/api/accounts")并访问了/api/accounts,因此实施&#34;帮助&#34;通过使/api/accounts/成为正确的上下文根。

想象一下......

  • 您有val b = ContextHandler("/a/b")
  • 您拥有val a = ContextHandler("/a") - 实现(内部)对子资源/b的支持
  • 如果您请求/a/b,您在哪个上下文? - 根据规范,您处于上下文a
  • 如果您请求/a/b/,那么您处于上下文b