Jersey 2 请求过滤器在此代码中不起作用

我已经使用 Jersey 2 实现了一个注释,但不知何故代码没有达到那个点。


这些是我的课程:


有保障


import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Target;


import javax.ws.rs.NameBinding;


@NameBinding

@Retention(RUNTIME)

@Target({ElementType.METHOD, ElementType.TYPE})

public @interface Secured { }

安全实施:


import javax.annotation.Priority;

import javax.ws.rs.Priorities;

import javax.ws.rs.WebApplicationException;

import javax.ws.rs.container.ContainerRequestContext;

import javax.ws.rs.container.ContainerRequestFilter;

import javax.ws.rs.core.Response.Status;

import javax.ws.rs.ext.Provider;


@Secured

@Provider

@Priority(Priorities.AUTHENTICATION)

public class SecureImplementation implements ContainerRequestFilter

{

  @Override

    public void filter(ContainerRequestContext requestContext) throws 

  IOException {

        System.out.println("Inside Something");

        throw new WebApplicationException(Status.UNAUTHORIZED);

}

}

测试类


@Path("/checkClass")

public class TestingClass{


    @Secured

    @Path("/checkFilter")

    @POST

    @Produces(MediaType.APPLICATION_JSON)

    @Consumes(MediaType.APPLICATION_JSON)

    public Map<String, String> testing(Input input)

            throws Exception {

        Map<String, Object> responseMap = new HashMap<String, Object>();

        responseMap.put("result","Success");

        return responseMap;

   }

  }

它给了我一个响应,而不是给我一个 401 错误。那么,我在这里做错了什么?


绝地无双
浏览 133回答 1
1回答

慕姐8265434

通常TestingClass应该与过滤器一起在应用程序类中注册,例如:@ApplicationPath("checkClass")public class MyApplication extends ResourceConfig {&nbsp; &nbsp; public MyApplication () {&nbsp; &nbsp; &nbsp; &nbsp; register(TestingClass.class);&nbsp; &nbsp; &nbsp; &nbsp; register(SecureImplementation.class);&nbsp; &nbsp; }}@Path("/checkFilter")public class TestingClass{&nbsp; &nbsp; @Secured&nbsp; &nbsp; @POST&nbsp; &nbsp; @Produces(MediaType.APPLICATION_JSON)&nbsp; &nbsp; @Consumes(MediaType.APPLICATION_JSON)&nbsp; &nbsp; public Map<String, String> testing(Input input)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java