Java 在 servlet 中获取过滤器初始化参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1461335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:31:12  来源:igfitidea点击:

Get filter init parameters in a servlet

javainit-parameters

提问by JeffJak

I have a filter that looks like this:

我有一个看起来像这样的过滤器:

   <filter>
      <filter-name>TestFilter</filter-name>
      <filter-class>org.TestFilter</filter-class>
      <init-param>
         <param-name>timeout</param-name>
         <param-value>30</param-value>
      </init-param>
   </filter>

Since we are talking ServletFilter and Servlets. Essentially, I am already in my servlet and have executed the first part of the doFilter. So the container must know the init-parameter. I don't have access to change the Filter class.

因为我们在谈论 ServletFilter 和 Servlets。本质上,我已经在我的 servlet 中并且已经执行了 doFilter 的第一部分。所以容器必须知道 init 参数。我无权更改 Filter 类。

Is it possible to get the init-parameter value given an HttpServletRequest object?

是否可以获取给定 HttpServletRequest 对象的 init 参数值?

The only solution I can think of is to read the web.xml as a resource and try to find the value manually. But it feels like there is a better solution.

我能想到的唯一解决方案是将 web.xml 作为资源读取并尝试手动查找值。但感觉有更好的解决方案。

采纳答案by ChssPly76

Why would you need it in your servlet to begin with? Filter parameter belongs to filter. Your options are:

为什么首先需要在 servlet 中使用它?过滤器参数属于过滤器。您的选择是:

  1. Move said parameter to context init parameter; you'll be able to access it from both filter and servlet.
  2. In your filter's doFilter method set an attribute (on request) with parameter value, have you servlet read it.
  1. 将所述参数移动到上下文初始化参数;您将能够从过滤器和 servlet 访问它。
  2. 在您的过滤器的 doFilter 方法中,使用参数值设置一个属性(根据请求),让您的 servlet 读取它。

Context parameter example.

上下文参数示例。

web.xml:

网页.xml:

  <context-param>
    <param-name>param1</param-name>
    <param-value>value</param-value>
  </context-param>

your code:

你的代码:

String paramValue = getServletContext().getInitParameter("param1");

and the filter would have access to the same param value using:

并且过滤器可以使用以下方法访问相同的参数值:

String paramValue = filterConfig.getServletContext().getInitParameter("param1");

回答by ZZ Coder

If the filter is not declared final, you can extend it. For example,

如果过滤器未声明为 final,您可以扩展它。例如,

public class MyFilter extends TheirFilter {
    public void init(javax.servlet.FilterConfig filterConfig) 
        throws javax.servlet.ServletException {
        super(filterConfig);
        // Retrieve the parameter here
    }
}

Then change the web.xml to change the filter class to yours.

然后更改 web.xml 以将过滤器类更改为您的。