Tuesday, 7 October 2014

Setting environment variable in web.xml then accessing in portlet jsp

Step 1 :- Open your web application and double click on web.xml and then add any entry for environment as given below

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>TrainingJ2eeApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<env-entry> 
    <env-entry-name>Key</env-entry-name> 
    <env-entry-type>java.lang.String</env-entry-type> 
    <env-entry-value>value</env-entry-value> 
</env-entry>

</web-app>


Step 2 :- Now create a asp and place below content in it to access the env value

<%!
public void jspInit() {
    System.out.println("env entries are being read and set..");
String rootPageName = null;
   String commonsHostURL = null;
   Context env = null;
   
try {
// Get a handle to the JNDI environment naming context
env = (Context)new InitialContext().lookup("java:comp/env");
} catch(javax.naming.NamingException e) {
e.printStackTrace();
}

try {
rootPageName = (String)env.lookup("key");
} catch(javax.naming.NamingException e1) {
e1.printStackTrace();
}
getServletContext().setAttribute("key", rootPageName);
}

%>

Step 3 :- Now you can access it were ever you need


No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...