我有一个令人遗憾的任务,试图在url参数(传统应用程序)中传递斜杠。
我已经阅读了关于如何在2.0+中解决此问题的答案:JAX-RS @PathParam How to pass a String with slashes, hyphens & equals too
但是以下解决方案在1.9中不起作用: @Path(" {id} / {emailAddress:(。+)?}")
测试路径:5/emailpart1/part2@example.org
这会返回404,说它无法找到匹配的路线。
仅供参考,这是通过URL编码发送的,但我们的容器(Tomcat)会在Jersey处理之前自动解码。
编辑:结果是整个请求被Apache的AllowEncodedSlashes
指令阻止了。
相关:Need to allow encoded slashes on Apache
答案 0 :(得分:2)
每次评论发布测试(注意:使用独立的灰熊容器,而不是tomcat)
@Path("/email")
public class EmailResource {
@GET
@Path("{id}/{emailAddress : (.+)?}")
public Response getEmail(@PathParam("id") String id,
@PathParam("emailAddress") String email) {
StringBuilder builder = new StringBuilder();
builder.append("id: ").append(id).append("\n");
builder.append("email: ").append(email).append("\n");
return Response.ok(builder.toString()).build();
}
}
独立服务器
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import org.glassfish.grizzly.http.server.HttpServer;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;
public class Main {
private static int getPort(int defaultPort) {
//grab port from environment, otherwise fall back to default port 9998
String httpPort = System.getProperty("jersey.test.port");
if (null != httpPort) {
try {
return Integer.parseInt(httpPort);
} catch (NumberFormatException e) {
}
}
return defaultPort;
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/api").port(getPort(8080)).build();
}
public static final URI BASE_URI = getBaseURI();
protected static HttpServer startServer() throws IOException {
ResourceConfig resourceConfig
= new PackagesResourceConfig("jersey1.stackoverflow.standalone");
System.out.println("Starting grizzly2...");
return GrizzlyServerFactory.createHttpServer(BASE_URI, resourceConfig);
}
public static void main(String[] args) throws IOException {
// Grizzly 2 initialization
HttpServer httpServer = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nHit enter to stop it...",
BASE_URI));
System.in.read();
httpServer.stop();
}
}
注意:资源类位于jersey1.stackoverflow.standalone
。要运行服务器,只需运行Main
类。资源类将基于new PackagesResourceConfig("jersey1.stackoverflow.standalone")
使用此依赖
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>${jersey-version}</version> <!-- 1.9 -->
</dependency>
可以从
中检索Maven archytypeGroup id: com.sun.jersey.archetypes
Artifact id: jersey-quickstart-grizzly2
Version: 1.9
卷曲
curl -v http://localhost:8080/api/email/5/emailpart1/part2@example.org
结果:
id: 5
email: emailpart1/part2@example.org