我正在尝试在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;
}
}
有没有人知道任何方法或某些事情来实现同样的目标?
答案 0 :(得分:40)
如果出现错误,如果要发送自定义响应,则需要抛出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;
}