我有一个令人遗憾的任务,试图在url参数(旧版应用)中传递斜杠。
我已经阅读了有关如何在2.0+中解决此问题的答案:JAX-RS @PathParam How to pass a String with slashes, hyphens & equals too
但是,以下解决方案在1.9中不起作用:
@Path(“ {id} / {emailAddress:(。+)?}”)
测试路径:5/emailpart1/[email protected]
这会返回404,表示找不到匹配的路由。
仅供参考,它是通过URL编码发送的,但是我们的容器(Tomcat)在它被Jersey处理之前会自动对其进行解码。
编辑:结果整个请求被Apache的AllowEncodedSlashes
指令阻止。
相关:Need to allow encoded slashes on Apache
最佳答案
每个评论都可以发布测试(注意:使用独立的grizzly容器,而不是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原型可以从
Group id: com.sun.jersey.archetypes
Artifact id: jersey-quickstart-grizzly2
Version: 1.9
卷曲
curl -v http://localhost:8080/api/email/5/emailpart1/[email protected]
结果:
id: 5
email: emailpart1/[email protected]