【问题标题】:ServletConfig with out xml configuration in jsp?在jsp中没有xml配置的ServletConfig?
【发布时间】:2014-11-18 13:07:43
【问题描述】:

如何在 index.jsp 页面中设置 ServletConfig 参数名称和值,而无需像 Servlet 中的 initParams 这样的 xml 配置?有可能吗?

<servlet>
    <servlet-name>welcome</servlet-name>
    <jsp-file>/index.jsp</jsp-file>

    <init-param>
        <param-name>website</param-name>
        <param-value>www.google.com</param-value>
    </init-param>
</servlet>

【问题讨论】:

  • 您需要以编程方式设置它吗?
  • 另一种提供参数的方法是在servlet中设置它。但我不确定这是否正是你想要做的
  • 您可以使用config 隐式对象来这样做

标签: java jsp jakarta-ee servlets servletconfig


【解决方案1】:

在 JSP 中,我们有隐式对象,其中我们有 config(这是与页面关联的 ServletConfig 对象)对象。但我想我们不能手动添加参数,因为它们不是在 ServletConfig 接口中添加 init 参数的方法。

如果您想保存任何参数,您可以保存在 4 个 JSP 范围(页面、请求、会话和应用程序)中,并在需要的任何地方使用它。

<c:set var="user" value="TestUser" scope="session"> //can set any value

【讨论】:

    【解决方案2】:

    您可以使用ServletContextListener 执行此操作。当容器启动时,它会调用 ServletContextListener 类。在那里你可以设置你的参数:

    @WebListener
    public class ContextListener implements ServletContextListener {
    
      public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
         ctx.setAttribute("website", "www.google.com");
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 2015-05-24
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多