Read property file Of WEBINF folder In servlet context example

Click here to download eclipse supported ZIP file



This is input.html JSP file and it is used display the output for the application.




<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Context Param</title>
</head>
<body>
<form  method="POST" action="ContextParamServlet">  
    <br><br>
    <center>
        <input type="SUBMIT" value="Please Click here">
    </center>  
</form>
</body>
</html>




This is app.properties properties file and these properties are used in the application.




proeprty1 = value1
proeprty2 = value2
proeprty3 = value3


This is ContextParamServlet.java file having the source code to execute business logic.



 

    
package com.cv.servlet.context.listeners;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 *
 */
public class ContextParamServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(ContextParamServlet.class);

  public void doGet(HttpServletRequest request, HttpServletResponse responsethrows IOException, ServletException {
    LOGGER.info("Entered into doGet(--) of ContextParamServlet class... ");
    response.setContentType("text/plain");
    PrintWriter printWriter = response.getWriter();
    ServletContext context = getServletContext();
    String realPath = context.getRealPath("/app.properties");
    LOGGER.info("Getting realPath : : " + realPath);
    printWriter.print("Getting realPath : : " + realPath+"\n");    
    printWriter.print("\nPlease look at the start up logs...");
  }

  /**
   @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doPost(--) of ContextParamServlet class... ");
    doGet(request, response);
  }

}




This is ServletContextListenerImpl.java file having the source code to execute business logic.



 

    
package com.cv.servlet.context.listeners;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 *
 */
public class ServletContextListenerImpl implements ServletContextListener {

  private static final Logger LOGGER = Logger.getLogger(ServletContextListenerImpl.class);
  
  @Override
  public void contextDestroyed(ServletContextEvent event) {

    LOGGER.info("ServletContextListenerImpl... ServletContextEvent... contextDestroyed...");
  }

  @Override
  public void contextInitialized(ServletContextEvent event) {
    LOGGER.info("ServletContextListenerImpl class of contextInitialized(ServletContextEvent)...");
    ServletContext servletContext = event.getServletContext();
    String contextPath = servletContext.getContextPath();
    String realPath = servletContext.getRealPath("/app.properties");
    String result = "";
    int lastIndexOf = realPath.lastIndexOf("\\");
    String firstStr = realPath.substring(0, lastIndexOf);
    String lastStr = realPath.substring(lastIndexOf, realPath.length());
    result = firstStr + "\\WEB-INF" + lastStr;
    Properties props = new Properties();
    try {
      props.load(new FileInputStream(result));
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }
    
    LOGGER.info("Value of contextPath is : " + contextPath + " set as contextPath...");
    LOGGER.info("Value of realPath is : " + result + " set as realPath...");
    LOGGER.info("Value of properties is : " + props);
  }
}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.servlet.context.listeners</groupId> <artifactId>ReadPropertyFileOfWEBINFFolderInServletContext</artifactId> <version>1.0</version> <packaging>war</packaging> <properties> <log4j-version>1.2.16</log4j-version> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> </project>


This is web.xml deployment descriptor file and it describes how the web application should be deployed.



	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>ReadPropertyFileOfWEBINFFolderInServletContext</display-name>
<context-param>
<param-name>contextParam</param-name>
<param-value>JokeyIsTheFirstPetName</param-value>
</context-param>
<servlet>
<servlet-name>ContextParamServlet</servlet-name>
<servlet-class>com.cv.servlet.context.listeners.ContextParamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextParamServlet</servlet-name>
<url-pattern>/ContextParamServlet</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.cv.servlet.context.listeners.ServletContextListenerImpl</listener-class>
</listener>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment