我正在开发两种类型的REST服务。
我不想在每个REST方法中包含@HeaderParam。我想首先拦截它,并根据我想检查会话的有效性。请让我知道
感谢。
答案 0 :(得分:8)
我使用PreProcessInterceptor
解决了这个问题@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Securable {
String header() default "session-token";
}
@Provider
@ServerInterceptor
public class ValidationInterceptor implements PreProcessInterceptor, AcceptedByMethod {
@Context
private HttpServletRequest servletRequest;
@Override
public boolean accept(Class clazz, Method method) {
return method.isAnnotationPresent(Securable.class);
}
@Override
public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure,
WebApplicationException {
Securable securable = resourceMethod.getMethod().getAnnotation(Securable.class);
String headerValue = servletRequest.getHeader(securable.header());
if (headerValue == null){
return (ServerResponse)Response.status(Status.BAD_REQUEST).entity("Invalid Session").build();
}else{
// Validatation logic goes here
}
return null;
}
}
注释@Securable将用于需要验证的REST服务。
@Securable
@PUT
public Response updateUser(User user)
答案 1 :(得分:3)
有两种方法
使用JAX-RS interceptors - 您可以访问拦截器中的请求对象,因此您可以读取标题
使用好的旧JavaServlet过滤器 - 使用JAX-RS不是问题,您也可以过滤REST请求。与拦截器类似,过滤器可以访问请求对象,该对象具有标题信息
在这两种情况下,您都可以检查HttpSession是否存在(request.getSession()
方法)并且它具有必需属性。
您可以在配置中以编程方式或以编程方式在Java代码中包含/排除请求,查看请求路径。