我的服务定义如下.
public String getData(@QueryParam("date") Date date)
我正试图java.util.Date从我的客户端(它是jaxrs:CXF的客户端,而不是通用HTTP客户端或浏览器)传递给它.
我的服务收到Thu Mar 01 22:33:10 IST 2012HTTP URL中的日期.由于CXF无法Date使用此String 创建对象,因此我的客户端收到404错误.我尝试ParameterHandler在服务端使用a ,但我仍然无法成功解析它,因为我不期望任何特定格式的日期.
根据这篇文章,传递一个Date应该是开箱即用,但我似乎无法让基本案例工作.我是否需要做任何事情才能成功地将Date对象从我的客户端传递给服务?感谢任何帮助.
谢谢
我是新手,试图阅读一些文档,但它不起作用,请耐心等待.
我创建了一个UserNotFoundMapper使用ExceptionMappers这样的:
public class UserNotFoundMapper implements ExceptionMapper<UserNotFoundException> {
@Override
public Response toResponse(UserNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
}
}
Run Code Online (Sandbox Code Playgroud)
这在我的服务中:
@GET
@Path("/user")
public Response getUser(@QueryParam("id") String id) throws UserNotFoundException{
//Some user validation code with DB hit, if not found then
throw new UserNotFoundException();
}
Run Code Online (Sandbox Code Playgroud)
这UserNotFoundException是一个User-Defined例外.
我试过这个:
public class UserNotFoundException extends Exception {
//SOME block of code
}
Run Code Online (Sandbox Code Playgroud)
但是当我调用该服务时,UserDefinedExceptionMapper不会被调用.看来我可能会遗漏一些东西UserDefinedException.那么如何定义这个异常呢?
请让我知道如何定义UserNotFoundException.
我已经读过,我可以创建一个javax.ws.rs.ext.ExceptionMapper将抛出的应用程序异常映射到Response对象的实现.
我创建了一个简单的示例,如果持久化对象时手机长度超过20个字符,则抛出异常.我期望将异常映射到HTTP 400(错误请求)响应; 但是,我收到HTTP 500(内部服务器错误),但有以下异常:
java.lang.ClassCastException: com.example.exception.InvalidDataException cannot be cast to java.lang.Error
Run Code Online (Sandbox Code Playgroud)
我错过了什么?任何意见是极大的赞赏.
异常映射器:
@Provider
public class InvalidDataMapper implements ExceptionMapper<InvalidDataException> {
@Override
public Response toResponse(InvalidDataException arg0) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
Run Code Online (Sandbox Code Playgroud)
例外类:
public class InvalidDataException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidDataException(String message) {
super(message);
}
...
}
Run Code Online (Sandbox Code Playgroud)
实体类:
@Entity
@Table(name="PERSON")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Person {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID")
private Long id;
@Column(name="NAME")
private String name;
@Column(name="PHONE")
private …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的宁静的Web服务方法:
@GET
@Path("/generateInfo")
@Produces(MediaType.APPLICATION_JSON)
public String generateInfo(
@QueryParam("a") String a,
@QueryParam("b") String b,
@QueryParam("date") Date date) {
// ...business code...
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
如何从WebBrowser中调用该方法?问题是Date当我尝试给我404找不到或500内部服务器错误时的参数.
我想使用JAX-RS REST服务作为人类使用浏览器直接使用的Web应用程序的后端.由于人类不时会犯错误,我想验证表单输入并使用验证消息重新显示表单,如果输入错误.默认情况下,如果未发送全部或错误的值,JAX-RS将发送400或404状态代码.
例如,用户在表单字段"count"中输入了"xyz":
@POST
public void create(@FormParam("count") int count) {
...
}
Run Code Online (Sandbox Code Playgroud)
JAX-RS无法将"xyz"转换为int并返回"400 Bad Request".
如何告诉用户他在字段"count"中输入了非法值?有什么比在任何地方使用字符串更方便,并手动进行对话?
我有一个在 Jboss 7 (EAP 6.4) 上运行的 EE6 JAX-RS 应用程序,并通过ExceptionMapper.
不过,在某些情况下(最明显的是当 HTTP 基本身份验证失败时),由于错误发生在调用应用程序之前,因此不会调用此方法,因此客户端会获取服务器的默认错误页面(JBWEB bla bla,具有难看的紫色的 HTML) )。
现在为了捕获这些“外部”错误,我添加了<error-page>定义,web.xml如下所示:
<error-page>
<location>/error.json</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/error401.json</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
该位置工作正常,我几乎得到了我想要的响应,但 HTTP 状态代码始终为 200。
至少可以说,这很烦人。如何让错误页面返回正确的错误代码?
我有一个休息服务,它将抛出一个异常,我想知道什么是最好的方法来处理这个.
所以我有一个休息服务,它可以抛出一个用户定义的异常,我在catch块中捕获并再次抛出异常!并使用rest框架来捕获它.同样适用于非用户定义的异常.我认为这将是好的,因为我有许多休息服务,所有userdefinedexception代码处理将在同一个地方.
我想知道这是在休息服务中处理异常的正确方法吗?
我正在使用运动衫.
// rest service
@POST
public void doSomething() {
try {
// ... some piece of code that can throw user defined exception as well as runtime exception
} catch(UserDefinedException e) {
throws new UserDefinedException(e);
} catch(Exception e) {
throws new ServiceException(e);
}
// Now I have a @Provider to catch this thrown exception
@Provider
public class UserDefinedExceptionHandler implements
ExceptionMapper {
public Response toResponse(UserDefinedException exception) {
ClientResponse clientResponse = new ClientResponse();
ResponseStatus status = new ResponseStatus();
clientResponse … 是否可以在 a 中包含一条消息,BadRequestException以便当用户看到响应代码 a 400 时,他/她也能找出原因?
场景会是这样的,经过简化:
public Entity getEntityWithOptions(@PathParam("id") String id, @QueryParam("option") String optValue) {
if (optValue != null) {
// Option is an enum
try {
Option option = Option.valueOf(optValue);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
return new Entity(option);
}
return new Entity();
}
Run Code Online (Sandbox Code Playgroud)
我知道这可以通过返回一个对象来完成Response,但我不希望这样做。
这可能吗?也许有一个ExceptionMapper<BadRequestException>?或者这不能完成,因为BadRequestException已经是泽西岛特定的例外?
有人能为我提供一些关于JAX-Rs Web服务中访问控制的指示.例如,基于用户凭证或名称或任何其他标准来限制访问.在太阳手册中找不到任何有用的信息.
先谢谢,Adhir
这是我的Java代码:
@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
public String sumPost(@QueryParam(value = "x") int x,
@QueryParam(value = "y") int y) {
System.out.println("x = " + x);
System.out.println("y = " + y);
return (x + y) + "\n";
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它:
curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x:5&y:3'
Run Code Online (Sandbox Code Playgroud)
问题是System.out.println呼叫一直张贴零零,看来我没有正确传递 x 和 y。
得到答复后,我将请求更改为:
curl -d '{"x" : 4, "y":3}' "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -H "Content-Type:application/json" -H "Accept:text/plain" --include
Run Code Online (Sandbox Code Playgroud)
服务是:
@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String sumPost(@QueryParam(value = "x") int x,
@QueryParam(value = "y") int y) {
System.out.println("sumPost");
System.out.println("x …Run Code Online (Sandbox Code Playgroud) I'm trying out some custom error handling on my webservice. In my webservice, I created a custom Exception class extending WebApplicationException as described in JAX-RS / Jersey how to customize error handling? :
public class InternalServerErrorException extends WebApplicationException {
public InternalServerErrorException(String message) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.header("errorMessage", message).type(MediaType.TEXT_PLAIN).build());
System.out.println(message);
}
}
Run Code Online (Sandbox Code Playgroud)
For testing, I have a simple Country service that gives a list of countries. I made sure that an error will occur to test the throwing of the InternalServerErrorException:
@GET
@Override …Run Code Online (Sandbox Code Playgroud) 我过去只使用 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) 我正在使用托管在Google App Engine上的Java,Jetty和Jersey 2.18(现在最新).
假设我有这样的服务
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{userId}")
public Response getUser(@PathParam("userId") String userId)
{
...
}
Run Code Online (Sandbox Code Playgroud)
当我做:
return Response.ok()
.entity(user)
.build();
Run Code Online (Sandbox Code Playgroud)
我正确地收到了application/json内容类型和正文.但当我这样做时:
return Response
.status(404)
.entity(new ResponseModel(100, "user not found"))
.build();
Run Code Online (Sandbox Code Playgroud)
与返回任何4XX或5XX状态相同,我收到text/html内容类型以及此HTML正文:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>404 Not Found</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Not Found</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
而不是我放入的对象.entity()
编辑:这是我的web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.mypackage.services;org.codehaus.jackson.jaxrs</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
org.glassfish.jersey.server.gae.GaeFeature;
org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;
org.glassfish.jersey.media.multipart.MultiPartFeature;
</param-value> …Run Code Online (Sandbox Code Playgroud) java ×12
jax-rs ×8
jersey ×7
rest ×6
web-services ×4
java-ee ×3
curl ×1
cxf ×1
forms ×1
http ×1
http-post ×1
jakarta-ee ×1
jersey-2.0 ×1
jsp ×1
redirect ×1
service ×1
servlet-3.0 ×1
validation ×1