我正在尝试在jersey 1.11过滤器中实现对休息电话的用户身份验证。
这就是我尝试过的
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;
}
}
有人知道有什么方法或方法可以达到相同目的吗?
最佳答案
发生错误时,如果要发送自定义响应,则需要引发WebApplicationException。创建一个Response对象,并使用以下异常构造函数将其发送回:
WebApplicationException(Response response)
Construct a new instance using the supplied response
尝试这个:
@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;
}
关于java - 如何在jersey 1.11过滤器中添加自定义响应和中止请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17143514/