我过去只使用 Tomcat 和 JSP 页面来执行查询,然后将查询结果分配到数组或对象中,然后通过响应将该数据传递到客户端。
request.setAttribute("errorMessage", "this is error!!");
request.getRequestDispatcher("report.jsp").forward(request, response);
Run Code Online (Sandbox Code Playgroud)
在客户端 jsp 代码中,我可以执行以下操作:
${错误消息}
然后“这是错误!!” 消息就会出现。
我想对 REST JAX-RS GlassFish v3 做同样的事情。
@Path("schedule/test")
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/vnd.ms-excel")
public Object tmpTest(String content) {
try {
//just my method to execute query and get result
Vector out = (Vector)QueryManager.executeQuery;
//if query result is empty, I want user to redirect to report.jsp page
if(out.isEmpty()) {
request.setAttribute("errorMessage", "This is error!!");
request.getRequestDispatcher("report.jsp").forward(request, response);
return null;
}
....continue code......
}
Run Code Online (Sandbox Code Playgroud)
这会导致我从未见过的神秘异常。
java.lang.ClassCastException: $Proxy109 cannot be cast …Run Code Online (Sandbox Code Playgroud) 我正在使用 Jersey 和 JAX-RS 来实现 REST POST 端点。实际的 servletweb.xml是com.sun.jersey.spi.spring.container.servlet.SpringServlet. 然后,我使用 JAX-RS 来注释我的端点:
@POST
@Path("foo")
public Response foo(Reader input) throws IOException {
BufferedReader lineReader = new BufferedReader(input);
String line;
while ((line = lineReader.readLine()) != null) {
System.out.println(line);
}
return Response.ok("{}", MediaType.APPLICATION_JSON).build();
}
Run Code Online (Sandbox Code Playgroud)
当我到达端点并提供一个文本文件时,换行符会丢失,并且会作为一行读入。例子:
line 1
line 2
line 3
Run Code Online (Sandbox Code Playgroud)
打印出:
line 1line 2line 3
Run Code Online (Sandbox Code Playgroud)
我尝试使用注释@Consumes("text/plain")并将请求标头设置为,Content-Type:text/plain但这没有帮助。为什么换行序列被删除?
*我刚刚开始探索 RESTful 服务,我发现 rest 使用基于资源的 URI,所以我只是想知道它们之间有什么区别,基于资源的 URI 是否比基于动作的 URI 有任何优势 *
Intellij 告诉我这updateTime是不正确的参数类型。我不熟悉这个错误和@EnumDateFormat.
@DELETE
@Path("groups/{groupId}/samples/{testYear}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({Profile.MP_USER_ROLE})
public Response deleteGroupSamples (@PathParam("groupId") Long groupId, @PathParam("testYear") Long testYear, @QueryParam("updateTime") @EnumDateFormat( FormatEnum.WITH_HHMMSS ) DateTime updateTime, TreatmentGroupTest sample) throws ValidationException{
manager.deleteGroupSample( this.getUser(), sample.getTestSampleId(), updateTime );
ResponseBuilder builder=null;
builder = Response.ok( );
return builder.build();
}
Run Code Online (Sandbox Code Playgroud)
该错误还表明:
检查参数@PathParam、@QueryParam 等的类型。带注释的参数、字段或属性的类型必须是
是原始类型
有一个接受单个字符串参数的构造函数
有一个名为 valueOf 或 formString 的静态方法,它接受单个 String 参数(例如,参见 Integer.valueOf(String))
拥有 ParamConverterProvider JAX-RS 扩展 SPI 的注册实现,该实现返回能够进行该类型“表单字符串”转换的 ParamConverter 实例
是 List、Set 或 SortedSet,其中 T 满足上述 2、3 或 4。结果集合是只读的
我有一个端点:
@Path("/products")
@Produces({ MediaType.APPLICATION_JSON })
public interface Products {
@PUT
@Path("/{productId}")
....
}
Run Code Online (Sandbox Code Playgroud)
我为这个服务实现了一个 jax-rs 客户端,并将它导入到我从中调用它的另一个服务中。
所以我从我的第二个服务中调用客户端如下
public String updateProduct(String productId){
..
return client.target(this.getBaseUrl()).path("products/").path(productId).request(MediaType.APPLICATION_JSON_TYPE).put(Entity.json(""), String.class);
}
Run Code Online (Sandbox Code Playgroud)
如果我有一个带有斜杠的产品,上面写着“控制/注册应用程序”,该服务似乎不太好。我确实在调用服务之前对 productId 进行了编码,然后在收到后对其进行解码。但这似乎不起作用,我找不到 404。有任何想法吗?提前致谢
我是开发 Web 服务的初学者,我有一个 jaxrs Web 服务,它具有以下配置:
@Configuration
@ComponentScan("com.example.service")
@ComponentScan("com.example.services")
@ImportResource({
"classpath:/META-INF/cxf/cxf.xml",
"classpath:/META-INF/cxf/cxf-servlet.xml"
})
public class AppConfig {
@Bean(destroyMethod = "shutdown")
public SpringBus cxf() {
return new SpringBus();
}
@Bean
public Server jaxRsServer() {
//Define swagger feature
Swagger2Feature feature = new Swagger2Feature();
//REST Factory with all services,providers and features
JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint(jaxRsApiApplication(), JAXRSServerFactoryBean.class);
factory.setServiceBeans(Arrays.asList(baseRestService(), materialsRestService(), batchRestService(), billingRestService(), locationRestService(), customerRestService(), equipmentRestService(), projectRestService(), reservationRestService(), waferRestService()));
factory.setAddress(factory.getAddress());
factory.setProviders(Arrays.asList(jsonProvider(), authenticationService()));
factory.getFeatures().add(feature);
return factory.create();
}
@Bean
public JaxRsApiApplication jaxRsApiApplication() {
return new JaxRsApiApplication();
}
@Bean …Run Code Online (Sandbox Code Playgroud) 我有一个使用 Spring Boot(2.0.0) 和 Jersey 的非常基本的应用程序。不幸的是,当我尝试调用暴露的端点时,我收到错误 404。
我的代码如下所示:
主要类:
public class App {
public static void main( String[] args ) {
SpringApplication.run(App.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
泽西配置:
@Component
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig{
public JerseyConfig() {
register(FileResource.class);
}
}
Run Code Online (Sandbox Code Playgroud)
资源:
@Component
@Consumes(MediaType.APPLICATION_JSON)
public class FileResource {
@POST
@Path("/uploadfile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void upload(@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition disposition) {
System.out.println(disposition.getName());
}
@GET
@Path("/foo")
public String foo() {
return "foo";
}
}
Run Code Online (Sandbox Code Playgroud)
Maven 依赖项:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> …Run Code Online (Sandbox Code Playgroud) 任何 Body 解释我为什么 ConstraintValidator 类的 isValid() 方法被调用两次?
例如,这是我的示例代码:
@POST
@Path("/json/dog")
@Produces("application/json")
@Consumes("application/json")
public Response getDogByJson(@ValidAnimal JsonObject jsonObject) {
return Response.ok("ok").build();
}
@Constraint(validatedBy = {AnimalValidation.class})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ValidAnimal {
String message() default "This is not valid !";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
public class AnimalValidation implements ConstraintValidator<ValidAnimal, JsonObject> {
@Override
public void initialize(ValidAnimal constraintAnnotation) {
}
@Override
public boolean isValid(JsonObject jsonObject, ConstraintValidatorContext context) {
System.out.println(">>>>>> : " + jsonObject);
return true; …Run Code Online (Sandbox Code Playgroud) 当我将 Javascript 日期传递给 JAX-RS 服务时,我收到:
我传递给后端的信息来自我映射到 javascript Date 对象上的 Angular Material Datepicker 组件。
我知道该字符串具有后端不相关的信息,但我不知道如何在调用 POST 之前传递正确/修改的值。
我应该传递 String 而不是 Date 对象吗?这是正确的方法吗?
有没有办法将格式为“2018-06-04T22:00:00.000Z”或“2018-06-05T00:00:00.000Z”的日期传递给LocalDate和LocalDateTime?
我使用 LocalDate 和 LocalDateTime 因为我不想处理时区。即使我更改时区,该值也应该始终相同。
在我遇到问题之前,因为服务器和客户端之间存在 1 小时的差异。因此,当我过去从 Web 服务器选择日期时,客户端可能会在组件上看到前一天,因为它从午夜开始返回 1 小时。
我们正在运行 DropWizard 并尝试删除导致抛出 404 响应的 URL 的日志记录
我们有一个包罗万象的异常映射器,它接收一个NotFoundException. 令人沮丧的是,该异常没有携带导致它被抛出的 URL 的上下文。
示例应用在这里:https : //github.com/pauldambra/not.found.example
我们正在使用一个 ExceptionMapper
public class NotFoundLogger implements ExceptionMapper<NotFoundException> {
ExampleLogger logger = new ExampleLogger();
@Override
public Response toResponse(final NotFoundException exception) {
logger.error(urlFrom(exception), exception);
return Response.status(404).build();
}
private String urlFrom(final NotFoundException exception) {
return "why is this not a property on the exception?!";
}
private class ExampleLogger {
void error(final String notFoundUrl, final NotFoundException exception) {
System.out.println("someone tried to load " + notFoundUrl);
System.out.println(exception.getMessage());
} …Run Code Online (Sandbox Code Playgroud) jax-rs ×10
java ×7
rest ×5
jersey ×3
web-services ×2
angular ×1
datetime ×1
dropwizard ×1
jakarta-ee ×1
java-ee-8 ×1
javascript ×1
javax.ws.rs ×1
jersey-2.0 ×1
jetty ×1
jsp ×1
open-liberty ×1
redirect ×1
spring ×1
spring-bean ×1