Adding shared parameters to Servlet Context

In the previous recipe, we saw how to deploy a servlet and how to make use of the init-params. What if we have a set of servlets, servlet filters, or context listeners that makes use of the same parameters? Do we really need to initialize them in all the plugin modules?

In this recipe, we will see how we can use the Servlet Context Parameter plugin module to share parameters across servlets, filters, and listeners.

Getting ready

Create a skeleton plugin using the Atlassian Plugin SDK.

How to do it...

All we need to do is to define the shared parameters to add a servlet-context-param module for each shared parameter in the atlassian-plugin.xml file.

For example, a parameter with the key sharedText can be defined as follows:

<servlet-context-param key="jtricksContext">
    <description>Shares this param!</description>
    <param-name>sharedText</param-name>
     <param-value>This is a shared Text</param-value>
</servlet-context-param>

Tip

Make sure the module has a unique key. Here, the parameter name is sharedText and it has a value of ThisisasharedText. Once the plugin is packaged and deployed, the parameter sharedText is available across servlets, filters, and listeners.

In a servlet, we can access the parameter in the init method as follows:

@Override
public void init(ServletConfig config) throws ServletException {
   super.init(config);
   String sharedText = config.getServletContext().getInitParameter("sharedText");
}

How it works...

Once the shared text has been retrieved, we can use it anywhere, for example while constructing the HTML:

out.println("<br>Shared Text:"+sharedText);

The servlet will now print that as well, as shown in the following screenshot:

How it works...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.83.185