我正在使用Jersey学习JAX-RS(又名JSR-311)。我已经成功地创建了一个根资源,并正在摆弄参数:
@Path("/hello")
public class HelloWorldResource {
@GET
@Produces("text/html")
public String get(
@QueryParam("name") String name,
@QueryParam("birthDate") Date birthDate) {
// Return a greeting with the name and age
}
}
这工作得很好,并处理当前区域内Date(String)构造函数能理解的任何格式(如YYYY/mm/dd和mm/dd/YYYY)。但如果我提供的值无效或无法理解,就会得到404响应。
例如:
GET /hello?name=Mark&birthDate=X
404 Not Found
如何自定义此行为?也许是一个不同的响应代码(可能是“400个坏请求”)?记录一个错误怎么样?也许可以在自定义报头中添加问题的描述(“糟糕的日期格式”)以帮助排除故障?或者返回一个完整的带有详细信息的Error响应,以及一个5xx状态码?
如果你想打开浏览器登录窗口,就把@史蒂文拉文的答案作为一个扩展。我发现很难从过滤器中正确返回响应(MDN HTTP身份验证),如果用户还没有经过身份验证
这帮助我构建响应来强制浏览器登录,注意头的额外修改。这将把状态代码设置为401,并设置导致浏览器打开用户名/密码对话框的报头。
// The extended Exception class
public class NotLoggedInException extends WebApplicationException {
public NotLoggedInException(String message) {
super(Response.status(Response.Status.UNAUTHORIZED)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.header("WWW-Authenticate", "Basic realm=SecuredApp").build());
}
}
// Usage in the Filter
if(headers.get("Authorization") == null) { throw new NotLoggedInException("Not logged in"); }
如果你想打开浏览器登录窗口,就把@史蒂文拉文的答案作为一个扩展。我发现很难从过滤器中正确返回响应(MDN HTTP身份验证),如果用户还没有经过身份验证
这帮助我构建响应来强制浏览器登录,注意头的额外修改。这将把状态代码设置为401,并设置导致浏览器打开用户名/密码对话框的报头。
// The extended Exception class
public class NotLoggedInException extends WebApplicationException {
public NotLoggedInException(String message) {
super(Response.status(Response.Status.UNAUTHORIZED)
.entity(message)
.type(MediaType.TEXT_PLAIN)
.header("WWW-Authenticate", "Basic realm=SecuredApp").build());
}
}
// Usage in the Filter
if(headers.get("Authorization") == null) { throw new NotLoggedInException("Not logged in"); }