java 如何在 jersey 1.11 过滤器中添加自定义响应和中止请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17143514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add custom response and abort request in jersey 1.11 filters
提问by Ankur
I am trying to implement user authentication for rest calls in jersey 1.11 filters.
我正在尝试在 jersey 1.11 过滤器中为休息调用实现用户身份验证。
This is what i have tried
这是我尝试过的
package com.ilrn.session.webservices.rest.filter;
import com.ilrn.entity.User;;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
public class CustomFilter implements ContainerRequestFilter{
@Override
public ContainerRequest filter(ContainerRequest request) {
User user = Helper.getCurrentUser();
if(user == null){
//Need to add custom response and abort request
}
return request;
}
}
Does anyone know any method or something to achieve the same?
有谁知道任何方法或实现相同的东西?
回答by Juned Ahsan
In case of error, if you want to send a custom response then you need to throw a WebApplicationException. Create a Response object and send it back using the following exception constructor:
如果出现错误,如果您想发送自定义响应,则需要抛出 WebApplicationException。创建一个 Response 对象并使用以下异常构造函数将其发送回:
WebApplicationException(Response response)
Construct a new instance using the supplied response
Try this:
试试这个:
@Override
public ContainerRequest filter(ContainerRequest request) {
User user = Helper.getCurrentUser();
if(user == null){
ResponseBuilder builder = null;
String response = "Custom message";
builder = Response.status(Response.Status.UNAUTHORIZED).entity(response);
throw new WebApplicationException(builder.build());
}
return request;
}