如何在 Jersey 1.11 筛选器中添加自定义响应和中止请求

2022-09-02 02:58:40

我正在尝试在 Jersey 1.11 筛选器中为 rest 调用实现用户身份验证。

这就是我尝试过的

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;
    }

}

有没有人知道任何方法或其他东西来实现相同的目标?


答案 1

如果出现错误,如果要发送自定义响应,则需要抛出 WebApplicationException。创建一个响应对象,并使用以下异常构造函数将其发送回去:

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;
}

答案 2

推荐