我正在尝试使用Tomcat7获得RESTful Web服务(JAX-RS).我尝试了3种不同的实现(Jersey,RESTeasy和Restlet)但没有成功.这应该很容易,但不知何故不是.我正在寻找注释,web.xml和示例代码的最新教程/文档.
我有一个相当典型的REST API,除了资源的id不是整数,而是字符串,通常包含/字符.因此,如果客户的ID是string/with/slashes该客户的URI应该是http://localhost/customers/string%2Fwith%2Fslashes.返回客户列表时,我想用UriBuilder构造URI,这样我就可以把它放在ATOM风格的链接元素的href中.但它不太有效; 这是一个小测试类,显示我的意思:
@Path("/customers")
public class JerseyTest {
@Path("{id}")
public Customer getCustomer(@PathParam("{id}") String id) {
return null;
}
public static void main(String[] args) {
buildURI("string#with#hashes"); // => http://localhost/customers/string%23with%23hashes
buildURI("string/with/slashes"); // => http://localhost/customers/string/with/slashes
}
public static void buildURI(String id) {
UriBuilder builder = UriBuilder.fromUri("http://localhost");
builder.path(JerseyTest.class).path(JerseyTest.class, "getCustomer");
URI uri = builder.build(id);
System.out.println(uri);
}
}
Run Code Online (Sandbox Code Playgroud)
该#太棒了,我们编码为我所期望的,但/我们做不.我尝试使用builder.build(URLEncoder.encode(id)),但随后UriBuilder编码了%,所以你得到了.../string%252Fwith%252Fslashes!
在我看来,不一致的,它编码#和%而不是/,但我怀疑是有很好的理由对此我没有看到.所以我的问题是:
.../string%2Fwith%2Fslashes …当使用Jersey客户端将大文件作为InputStream 放置时,看起来文件的整个内容在被发送到服务器之前被缓冲到内存中.这会导致大文件出现问题,因为JVM的堆空间不足.如何在Jersey客户端中阻止此行为?服务器端的JAX-RS资源方法在发送数据时似乎没有这个问题.
例如:
WebResource dataUploadResource = buildDataUploadResource();
dataUploadResource.type(getMimeType()).put(getLargeInputStream());
Run Code Online (Sandbox Code Playgroud) 我正在使用JAX-RS/Jersey开发WebService.
我已经设置了一个ContainerRequestFilter,其目的是验证用户身份.我只需要通过身份验证保护一些路径,其余的都可以供所有人使用.
我想通过我的ContainerRequestFilter中的ExtendedUriInfo检索matchedResources/matchedResults,以便我可以检查路径是否应该受到保护.有没有办法创建一个在填充ExtendedUriInfo之后但在调用匹配的资源类和方法之前调用的过滤器?
我想DateTime在泽西岛使用Joda的查询参数,但泽西开箱即用不支持.我假设实现一个InjectableProvider是添加DateTime支持的正确方法.
可有人点我一个很好的实现的InjectableProvider对DateTime?或者是否有值得推荐的替代方法?(我知道我可以转换Date或String在我的代码,但是这似乎是一个更小的解决方案).
谢谢.
解:
我在下面修改了Gili的答案,使用@ContextJAX-RS中的注入机制而不是Guice.
更新:如果未在服务方法参数中注入UriInfo,则可能无法正常工作.
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
/**
* Enables DateTime to be used as a QueryParam.
* <p/>
* @author Gili Tzabari
*/
@Provider
public class DateTimeInjector extends PerRequestTypeInjectableProvider<QueryParam, DateTime>
{
private final UriInfo uriInfo;
/**
* Creates a new …Run Code Online (Sandbox Code Playgroud) 如何允许CDI将资源注入到宁静的Web服务资源中?我使用焊接2(cdi),泽西(jaxrs)和灰熊(网络服务器)在标准java上运行.这是我简单的网络资源:
import training.student.StudentRepository;
import javax.inject.Inject;
import javax.ws.rs.*;
@Path("student")
public class StudentWebResource {
@Inject
private StudentRepository studentRepository;
@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public Integer getCount() {
return studentRepository.studentCount();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我如何焊接启动我的简单Web服务器:
public class Main {
public static void main(String[] args) throws Exception {
startCdiApplication();
}
public static void startCdiApplication() throws Exception {
Weld weld = new Weld();
try {
WeldContainer container = weld.initialize();
Application application = container.instance().select(WebServer.class).get();
application.run();
}
finally {
weld.shutdown();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我怀疑的代码需要修改,以通知球衣使用焊接CDI注入分辨率:
...
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature; …Run Code Online (Sandbox Code Playgroud) 我正在开发一个RESTful Web服务项目,我正在使用Apache Tomcat和JAX-RS.
我想接受来自客户端的DELETE请求,但每当我从Advanced REST客户端Chrome插件发送DELETE请求时,它都会给出响应代码403 Forbidden.
那么我怎样才能让Apche Tomcat接受DELETE请求呢?
我试图找到一些手册如何POST使用jersey框架测试方法,只获得GET方法的例子.
这是一个例子:
@POST
@Path("add")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response addUser(JAXBElement<User> user) {
int code = userService.addUser(user.getValue());
if (code == 500) {
return Response.status(500).build();
}
return Response.status(code).entity(user).build();
}
Run Code Online (Sandbox Code Playgroud)
你能发一些POST方法测试例吗?先感谢您.
我无法使用Jersey 2(2.7)和Jersey内置的HK2依赖注入来实现一个非常基本的单例类实现.我在Tomcat上运行它.
我的目标是创建将由各种Web服务方法使用的支持类的单例实例.我没有强烈的偏好在构造函数注入,方法注入和注释类成员之间(如下所示).
这是我要成为的单身人士课程:
package singletest;
import javax.inject.Singleton;
@Singleton
public class JustOne {
private int secretNumber = 0;
public void hitMe(int input) {
secretNumber += input;
}
@Override
public String toString() {
return String.format("{ \"secretNumber\": %s }", secretNumber);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的应用程序类:
package singletest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/*")
public class MainApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(TestResource.class);
return classes;
}
@Override
public Set<Object> getSingletons() {
Set<Object> singletons = …Run Code Online (Sandbox Code Playgroud) 使用JAX-RS和java.time.LocalDate(java8)的问题.
我想使用JSON将这样的对象传递给JAX-RS方法:
Person {
java.time.LocalDate birthDay;
}
Run Code Online (Sandbox Code Playgroud)
我得到的例外是:
com.fasterxml.jackson.databind.JsonMappingException:找不到类型[simple type,classjava.time.LocalDate]的合适构造函数:无法在[来源:io.undertow.servlet.spec.ServletInputStreamImpl@21cca2c1; 来自JSON对象(需要添加/启用类型信息?)实例化)line:2,column:3]
我怎样才能创建一种将json-dates映射到的拦截器java.time.LocalDate?我试过实现了一个MessageBodyReader,但如果LocalDate是另一个类中的一个字段,我必须MessageBodyReader为每个持有a的类写一个LocalDate(据我所知).
(Java EE7(仅使用javaee-api,不需要任何第三方依赖),JAX-RS,Java 8,Wildfly 8.2)
有什么建议?
jax-rs ×10
java ×7
jersey ×6
rest ×3
tomcat7 ×2
annotations ×1
cdi ×1
grizzly ×1
hk2 ×1
http-delete ×1
jackson ×1
java-8 ×1
jersey-2.0 ×1
jodatime ×1
json ×1
singleton ×1
unit-testing ×1
urlencode ×1