是否有一种静态方法来获取当前请求的HttpServletRequest

时间:2009-02-26 19:51:02

标签: spring servlets request

我正在使用Spring注释,我可以将HttpRequestContext从Controller传递给服务。

我正在寻找一种静态方式或更好的解决方案,而不是传递RequestContext

6 个答案:

答案 0 :(得分:48)

如果您使用的是弹簧,则可以执行以下操作:

public static HttpServletRequest getCurrentHttpRequest(){
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request;
    }
    logger.debug("Not called in the context of an HTTP request");
    return null;
}

答案 1 :(得分:3)

作为参考,这是科特林的方式:

def post_detail(request, pk):
    template_name = 'books/post-detail.html'
    book = get_object_or_404(Book, pk=pk)
    comments = book.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():

            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.comment = book
            new_comment.username = request.user
            # Save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()

    context = {'book': book,
                'comments': comments,
                'new_comment': new_comment,
                'comment_form': comment_form}

    return render(request, template_name, context)

答案 2 :(得分:2)

还是java8方式

public static Optional<HttpServletRequest> getCurrentHttpRequest() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
        .filter(requestAttributes -> ServletRequestAttributes.class.isAssignableFrom(requestAttributes.getClass()))
        .map(requestAttributes -> ((ServletRequestAttributes) requestAttributes))
        .map(ServletRequestAttributes::getRequest);
}

答案 3 :(得分:0)

为响应“或Java 8方式”上方的@andrebrait评论,这些方法位于ServletRequestAttributes.class

    public static Optional<HttpServletRequest> getCurrentHttpRequest() {
        return
            Optional.ofNullable(
                RequestContextHolder.getRequestAttributes()
            )
            .filter(ServletRequestAttributes.class::isInstance)
            .map(ServletRequestAttributes.class::cast)
            .map(ServletRequestAttributes::getRequest);
    }

答案 4 :(得分:-1)

这对我有用:

HttpServletRequest request = 
    ((ServletRequestAttributes) Objects.requireNonNull(
        RequestContextHolder.getRequestAttributes()))
    .getRequest();

答案 5 :(得分:-6)

我不认为这是个好主意。服务层不应该知道或关心它是否正在处理HTTP客户端。

静态听起来也不是正确的想法。 HttpRequestContext应该与HttpRequest实例相关联,而不是特定的类。

在我看来,更好的设计可以从上下文中获取服务所需的任何内容并将其传入。不需要将服务耦合到HTTP或Web层。