ServletConfig with out xml configuration in jsp?

249 Views Asked by At

How to set ServeltConfig param name and value in index.jsp page with out xml configuration like initParams in Servlet ? is Possible ?

<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>
2

There are 2 best solutions below

0
Shoaib Chikate On

In JSP, we have implicit objects, in which we have config (This is the ServletConfig object associated with the page) object. But I guess we can't add parameters manually as their is not method for adding init parameter in ServletConfig interface.

If you want to save any parameters you can save in 4 scopes of JSP (page,request,session and application) and use it wherever you needed.

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

You can do this with ServletContextListener. When the container starts up, it will call the ServletContextListener class. There you can set your params:

@WebListener
public class ContextListener implements ServletContextListener {

  public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext ctx = servletContextEvent.getServletContext();
     ctx.setAttribute("website", "www.google.com");
  }
}