从过滤器访问 servlet 初始化参数
我有一个像这样的 servlet:
@WebServlet("/a/path")
@WebInitParam(name="name", value="name_value")
public class MyServlet extends HttpServlet {
//...
在这个 servlet 上我放置了一个过滤器:
@WebFilter(dispatcherTypes = { DispatcherType.REQUEST }, urlPatterns = { "/a/*" })
public class MyFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//...
HttpServletRequest req = (HttpServletRequest)request;
//problem comes here
System.out.println(req.getServletContext().getInitParameter("name"));
//...
}
问题是,即使我在 MyServlet 中设置 @WebInitParameter,程序也会打印出一个空字符串(请参阅注释行//问题出现在MyFilter中。我验证并看到 servlet 中的 init() 方法在 doFilter() 之前执行。 那么有人可以告诉我这个问题吗?如果initParameter“name”设置为一个值,为什么它为空?
谢谢!
I have a servlet like this:
@WebServlet("/a/path")
@WebInitParam(name="name", value="name_value")
public class MyServlet extends HttpServlet {
//...
On this servlet I have put a filter:
@WebFilter(dispatcherTypes = { DispatcherType.REQUEST }, urlPatterns = { "/a/*" })
public class MyFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//...
HttpServletRequest req = (HttpServletRequest)request;
//problem comes here
System.out.println(req.getServletContext().getInitParameter("name"));
//...
}
The problem is, that even if I set the @WebInitParameter in MyServlet, the programs prints out a null string (see the commented line //problem comes here in MyFilter). I verified and saw that init() method from servlet is executed before of doFilter().
So can anyone light me on this issue? Why the initParameter "name" is null, if it is set up to a value?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 WebInitParam 正在为 servlet 而不是整个应用程序上下文定义初始化参数,因此如果您想通过 ServletContext 对象访问参数,请在 web.xml 部署描述符中定义上下文参数。
I think WebInitParam is defining init parameters for servlet and not for whole application context, so if you want acces parameters through ServletContext object, then define context params in you web.xml deployment descriptor.