Tuesday, 7 January 2014

Sample Onlinetest Project using Servlet and JSP

Online test consist of three screens
1. LoginPage.jsp
2. Exam.jsp
3. scoreDisplay.jsp

After successfull Login Questions will be displayed 5 questions atlast we can submit the exam.The scoreDisplay screen is shown with correct answers.

Database Screen shots:onlinetest
users
question

answer
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 >
  <welcome-file-list>
    <welcome-file>LoginPage.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Sample</servlet-name>
    <servlet-class>com.DAO.LohinServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Sample</servlet-name>
    <url-pattern>/loginverify</url-pattern>
  </servlet-mapping>
   <servlet>
    <servlet-name>Sample1</servlet-name>
    <servlet-class>com.DAO.AnsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Sample1</servlet-name>
    <url-pattern>/arrverify</url-pattern>
  </servlet-mapping>
</web-app>
 
LoginPage.jsp 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Login Page</title>
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript"> 
  $(document).ready(function(){
 localStorage.clear();
 })
 </script>
</head>

<body bgcolor="#E6E6FF">
<h3>
<center>
<h2>Login</h2>
<form action="loginverify" method="get">
<br/> Username:<input type="text"  name="uname"/>
<br/>Password:<input type="password"  name="pswd"/>
<br/><input type="submit" value="submit" />
<br/><a href="register.jsp" >Register Here</a>
</form>
</center>
</h3>
</body>
</html>
 
LohinServlet.java 
package com.DAO;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Beans.Users;

public class LohinServlet extends HttpServlet {

/**
 * 
 */
 private static final long serialVersionUID = -6423051009614465001L;
   /**
   * Constructor of the object.
   */
   public LohinServlet() {
 super();
   }
   /**
   * Destruction of the servlet. <br>
   */
   public void destroy() {
 super.destroy(); // Just puts "destroy" string in log
 // Put your code here
   }
   /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
   public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
   throws ServletException, IOException {
   response.setContentType("text/html");  
         PrintWriter out = response.getWriter();  
  Users users=new Users();
  users.setUsername(request.getParameter("uname"));
  users.setPassword(request.getParameter("pswd"));
  Integer bvalue=0;
 try {
   bvalue = LoginDAO.validateLogin(users);
 } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
 if(bvalue!=0){
  users.setUserId(bvalue);
  Integer uidVal=users.getUserId();
  HttpSession session=request.getSession();
  session.setAttribute("CurrentSessionUser", users);
  response.sendRedirect("Exam.jsp?i=0&uidVal="+uidVal); 
 }else{
   out.print("<center>");  
          out.print("Sorry UserName or Password Error!");  
   RequestDispatcher rd=
          request.getRequestDispatcher("/LoginPage.jsp");  
   rd.include(request, response);  
   //response.sendRedirect("LoginPage.jsp?");
 }
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
  System.out.println("In Inits");
 }

}


LoginDAO.java 

package com.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.Beans.Users;
import com.Connection.ConnectionProvider;


public class LoginDAO {

 public static Integer validateLogin(Users users) throws Exception{
  Connection con=ConnectionProvider.getConn();
  Boolean exist;
  int uid=0;
  try {
    java.sql.PreparedStatement ps=
     con.prepareStatement(
     "select * from Users where username=? and password=?");
    ps.setString(1,users.getUsername());
    ps.setString(2,users.getPassword());
    ResultSet rs=ps.executeQuery();
    while(rs.next()){
    uid=rs.getInt("USER_ID");
    }
    return uid;
  }catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   throw e;
  }
}
}
 
 Exam.jsp
<%@ page language="java"
  contentType="text/html; 
  charset=windows-1256" 
  pageEncoding="UTF-8"
  import="com.DAO.QuestionDAO" 
  import="com.Beans.Users" %>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Exam</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
 <script type="text/javascript"> 
 var myAns = new Array();
var ival="<%= request.getParameter ("i") %>";
var uidVal="<%= request.getParameter ("uidVal") %>";
$(document).ready(function(){

if(ival=="0")
   document.getElementById('butPrevious').disabled = true; 
else if(ival=="4")
  document.getElementById('butNext').disabled = true; 
if(ival>=0 && ival<5){
    var cell = document.getElementById(localStorage.getItem(ival));
    cell.style.background = "green";
 }
    var selectedOpt="selectedOpt";
    var val=localStorage.getItem(ival);
    document.getElementById(selectedOpt+val.charAt(3)).checked = true;
})

function openPrevoius()
 {
 if(ival>0){
   ival--;
   window.location.href = 
   "http://localhost:8400/OLTest/Exam.jsp?i="+ival+"&uidVal="+uidVal;
  }
 }
 function openNext()
 {
   if(ival<5){
   ival++;
   }
   if(ival!=null){
     if(ival<5)
     window.location.href = 
    "http://localhost:8400/OLTest/Exam.jsp?i="+ival+"&uidVal="+uidVal;
    }
}

function openSubmit(id)
{
   var theOpts = document.getElementsByName("selectedOpt");
   for(var i=0;i<theOpts.length;i++){
   if(theOpts[i].checked){
     theOpts[i].value;
     var cell = document.getElementById(id);
     cell.style.background = "green";
     if(ival=="0"){
       localStorage.clear();
     }
     localStorage.setItem(  ival,id );
     if(ival=="4"){
     for(var i=0;i<5;i++){
       myAns[i]=localStorage.getItem(i);
     }
  }
  }else{
     theOpts[i].value;
     var opt="opt";
     var cell = document.getElementById(opt+i);
     cell.style.background = "#E6E6FF";
  }
 }
}
function clickSubmit(){


var uidVal="<%= request.getParameter ("uidVal") %>";
var arr=new Array();

for(var i=0;i<5;i++){
arr[i]=localStorage.getItem(i);
}
    arr;
    var json = arr;
$.ajax({
            url:"arrverify",
            type:"POST",
            dataType:'json',
            data: {json:json,uid:uidVal},
            success: function(data){
             window.location.href = "scoreDisplay.jsp";
            } 


        });
  
}

</script>

</head>

<body bgcolor="#E6E6FF">
<center>
 
 <% Users currentUser =
 (Users)(session.getAttribute("CurrentSessionUser"));%> 
 <br/>Welcome <%= currentUser.getUsername() %>
 <%= currentUser.getUserId() %>

<form method="post" id="frm">
  <center>
  <table border="1" width="30%" cellpadding="5" id="tableId">
  <jsp:useBean id="Quest" class="com.Beans.Question" scope="application"/>
  <jsp:useBean id="QuestDAO" class="com.DAO.QuestionDAO" scope="application" />
  <jsp:useBean id="AnswerDAO" class="com.DAO.AnswerDAO" scope="application" />
   <% java.util.List<com.Beans.Question> list =  
   new java.util.ArrayList<com.Beans.Question>(); %>
   <%  int i= Integer.parseInt(request.getParameter("i"));
   if(i==0){
 list=QuestDAO.getQuestions();
 session.setAttribute("list",list);
   }else{
  list= (java.util.List<com.Beans.Question>)session.getAttribute("list");
    }
    %>
         
  <thead>
  <tr>
      <th id="ram"  ><%= request.getParameter("i") %></th>
      <th ><%=  list.get(i).getQuestion() %></th>
  </tr>
  </thead>
  <tbody>
  <tr>
      <td id="opt0" onclick="openSubmit('opt0')">
      <input type="radio" id="selectedOpt0" name="selectedOpt" > 
      <%=  list.get(i).getOpt1() %>
      </td>
      <td id="opt1" onclick="openSubmit('opt1')">
      <input type="radio" id="selectedOpt1" name="selectedOpt" > 
      <%=  list.get(i).getOpt2() %>
      </td>
   </tr>
   <tr>
      <td id="opt2" onclick="openSubmit('opt2')">
     <input type="radio" id="selectedOpt2" name="selectedOpt" > 
      <%=  list.get(i).getOpt3() %>
      </td>
      <td id="opt3" onclick="openSubmit('opt3')">
     <input type="radio" id="selectedOpt3" name="selectedOpt" > 
     <%=  list.get(i).getOpt4() %>
     </td>
   </tr>
   </tbody>
   </table>
   </center>
</form>
    <input type="button" value="Previous" name="Previous" 
          id="butPrevious" onclick="openPrevoius()" >
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" value="Submit" name="Submit" 
         id="butSubmit" onclick="clickSubmit()" >
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" value="Next" id="butNext" name="Next" 
           onclick="openNext()" />
        
</center>

</body>
</html>
  
 
 
AnsServlet:
package com.DAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import com.Beans.ResultDisplay;

/**
 * Servlet implementation class AnsServlet
 */

public class AnsServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#HttpServlet()
  */
  public AnsServlet() {
     super();
     // TODO Auto-generated constructor stub
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, 
     HttpServletResponse response)
   */
   protected void doPost(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,IOException{
 // TODO Auto-generated method stub
     PrintWriter out=response.getWriter();
     String uid=request.getParameter("uid");
     String[] answers = request.getParameterValues("json[]");
     List<ResultDisplay> lisResult=new ArrayList<ResultDisplay>();
     try {
         lisResult=AnswerDAO.insertAns(answers,Integer.parseInt(uid));
     }catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
     }
     if(lisResult.size()>1){
 HttpSession session=request.getSession();
 session.setAttribute("resultOfUser", lisResult);
     try {
 JSONObject jobj = new JSONObject();
 String urlToRedirect = "scoreDisplay.jsp";
 jobj.put("url",urlToRedirect);
 response.getWriter().write(jobj.toString());
     }catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
     }
     }else{
 out.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");  
        out.print("Sorry some error occured we will recover soon");  
 RequestDispatcher rd=request.getRequestDispatcher("/Exam.jsp");  
 rd.include(request, response);  
     }
     }
}
AnswerDAO.java 
package com.DAO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.Beans.ResultDisplay; import com.Beans.Users; import com.Connection.ConnectionProvider; import com.mysql.jdbc.PreparedStatement; public class AnswerDAO { public static List<ResultDisplay> insertAns(String[] answers,int uid) throws Exception{ Connection con=ConnectionProvider.getConn(); String[] ans=new String[]{}; ans=answers; int result=0; String resultVal=""; List<ResultDisplay> lis=new ArrayList<ResultDisplay>(); try { for(int i=0;i<ans.length;i++){ String selectTableSQL = "SELECT "+ans[i]+" FROM question where QUESTION_ID=?"; java.sql.PreparedStatement preparedStatement1 = con.prepareStatement(selectTableSQL); preparedStatement1.setInt(1,(i+1)); ResultSet rs = preparedStatement1.executeQuery(); while (rs.next()) { resultVal = rs.getString(ans[i]); if(i==0){ String deleteTableSQL = "DELETE FROM answer where USER_ID=?"; java.sql.PreparedStatement preparedStatement2 = con.prepareStatement(deleteTableSQL); preparedStatement2.setInt(1,uid); int rs1 = preparedStatement2.executeUpdate(); } } String insertTableSQL = "INSERT INTO answer(ANSWER, QUESTION_ID, USER_ID) VALUES(?,?,?)"; java.sql.PreparedStatement preparedStatement = con.prepareStatement(insertTableSQL); preparedStatement.setString(1,resultVal); preparedStatement.setInt(2,(i+1)); preparedStatement.setInt(3,uid); result +=preparedStatement.executeUpdate(); System.out.println("Result"+result); if(result==5){ lis=AnswerDAO.result(uid); } } return lis; } catch (Exception e) { // TODO Auto-generated catch block throw e; } } public static List<ResultDisplay> result(int uid) throws Exception{ Connection con=ConnectionProvider.getConn(); List<ResultDisplay> resD=new ArrayList(); try { String qry= "select q.question,q.correctanswer,a.answer,a.user_id"+ "from question q,answer a where q.question_id=a.question_id and a.user_id=?"; java.sql.PreparedStatement preparedStatement=con.prepareStatement(qry); preparedStatement.setInt(1,uid); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()){ ResultDisplay rd= new ResultDisplay(); rd.setQuestion(rs.getString("question")); rd.setCorrectanswer(rs.getString("correctanswer")); rd.setAnswer(rs.getString("answer")); rd.setUsers(rs.getInt("user_id")); resD.add(rd); } return resD; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } } } 
 
 scoreDisplay.jsp
 
<%@page import="java.util.List"%>
<%@ page language="java"
  contentType="text/html; 
  charset=windows-1256" 
  pageEncoding="UTF-8"
  import="com.Beans.ResultDisplay" %>
<html>
<body bgcolor="#E6E6FF">
<center>
<% java.util.List<com.Beans.ResultDisplay> list = 
new java.util.ArrayList<com.Beans.ResultDisplay>(); %>
<%  list = (List<ResultDisplay>)(session.getAttribute("resultOfUser"));%> 
<table border="1" width="30%" cellpadding="5" id="tableId">
<thead>
   <tr>
   <th id="ram"  >Question</th>
   <th >Correct Answer</th>
   <th >Your Answer</th>
   </tr>
</thead>
<tbody>
  <tr>
  <td id="q0" ><%=  list.get(0).getQuestion() %></td>
  <td id="ca0" ><%=  list.get(0).getCorrectanswer()%></td>
  <td id="a0" ><%=  list.get(0).getAnswer() %></td>
  </tr>
  <tr>
  <td id="q1" ><%=  list.get(1).getQuestion() %></td>
  <td id="ca1" ><%=  list.get(1).getCorrectanswer() %></td>
  <td id="a1" ><%=  list.get(1).getAnswer() %></td>
  </tr>
  <tr>
  <td id="q2" ><%=  list.get(2).getQuestion()%></td>
  <td id="ca2" ><%=  list.get(2).getCorrectanswer() %></td>
  <td id="a2" ><%=  list.get(2).getAnswer()  %></td>
  </tr>
  <tr>
  <td id="q3" ><%=  list.get(3).getQuestion() %></td>
  <td id="ca3" ><%=  list.get(3).getCorrectanswer() %></td>
  <td id="a3" ><%=  list.get(3).getAnswer()  %></td>
  </tr>
  <tr>
  <td id="q4" ><%=  list.get(4).getQuestion() %></td>
  <td id="ca4" ><%=  list.get(4).getCorrectanswer() %></td>
  <td id="a4" ><%=  list.get(4).getAnswer()  %></td>
  </tr>
 </tbody>
</table>
</center>
</body>
</html>

Wednesday, 1 January 2014

Create Executable .jar files (Java Archive)

Jar stands for Java Archive.

It is java binary file available in "jdk/bin" folder.
It is used to compress or group Files and Folders.
Hence ''.jar " file is compressed file that is created by using "jar" command that contains java library files.


Difference between "zip" and "jar" extension files

zip is a platform dependent compressed file it works only in windows,where as jar is platform independent compressed file that can work in any OS,because it is created by using JAVA.



How can we create jar file using jar command?

Step:1 Open commandprompt.
Step:2 Type jar press Enter you will find usage of jar command with various options.
            The import options are
             -c create archive.
             -v shows the files adding to this archive. 
             -f  specify file name
             -x extract the files from jar.
             -e  (for 'entrypoint') creates or overrides the manifest's Main-Class attribute.
It can be used while creating or updating a jar file. Use it to specify the application entry point without editing or creating the manifest file.
For example, this command creates app.jar where the Main-Class attribute value in the manifest is set to MyApp

Step:3 Type jar -cfe app.jar MyApp MyApp.class

MyApp.class file only is added to jar file from current dierctory.
jar -cfe app.jar MyApp *.class
All .class files are added to this jar file.

How an executable jar file is made?

The jar that allows us to execute a main method class available in it is called executable jar file.
In every jar,zip file we have META-INF folder created by jar command.
To develop executable jar file we must configure main method class name in its "manifest.mf" file it is available in META-INF folder created automatically in every jar file.
File is properties files contains (key,value) pair.
All keys are predefined by SUN those keys value must be assigned by developer.
The required key and its associated value both must be placed by developer, like how we are writing main method and its logic in a class.
The key for configuring the class name is "Main-Class".


For Example:

Main-Class:Test

How can we execute jar file?

java -jar Test.jar

Sample of Creating jar file and executing it:

Step:1 Create a folder Test
E:/Test

Step:2 Create Test.java file and save it in folder
Test.java

public class Test{
  public static void main(String[] args){
     Addition.add(10,20) ;
}
}

Addition.java

public class Addition{
 public static void add(int a,int b){
   System.out.println("a+b:"+(a+b));
  }

}

Step:3 Compile java files
D:\Test>javac *.java

Step:4 Creating jar file
jar -cfe Test.jar Test *.class
Test.jar -->jar name
Test-->Class name which contains main method
*.class-->To include all .class files.
Step:5 Execution
java -jar Test.jar

output:
a+b:30

Hard to remember all commands so we create batch file on it if we double click it run.

Open normal text file
Type java -jar Test.jar
Save it in D:\Test folder with name Test.bat

Open Command prompt

E:\Test>Test.bat

Output:
E:\Test>java -jar Test.jar
a+b:30

If we want to make independent of Directories set Classpath

classpath=E:\Test\Test.jar;

Now we can access from any directory.






   

Friday, 27 December 2013

Java Versions, Features and History

Java Version SE 7

Code named Dolphin and released on July 28, 2011.

New features in Java SE 7

  • Strings in switch Statement
  • Type Inference for Generic Instance Creation
  • Multiple Exception Handling
  • Support for Dynamic Languages
  • Try with Resources
  • Java nio Package
  • Binary Literals, underscore in literals
  • Diamond Syntax
  • Automatic null Handling.

Java Version SE 6

Code named Mustang and released on December 11, 2006.

New features in Java SE 6

  • Scripting Language Support
  • JDBC 4.0 API
  • Java Compiler API
  • Pluggable Annotations
  • Native PKI, Java GSS, Kerberos and LDAP support.
  • Integrated Web Services.
  • Lot more enhancements.

J2SE Version 5.0

Code named Tiger and released on September 30, 2004.

New features in J2SE 5.0

  • Generics
  • Enhanced for Loop
  • Autoboxing/Unboxing
  • Typesafe Enums
  • Varargs
  • Static Import
  • Metadata (Annotations)
  • Instrumentation

J2SE Version 1.4

Code named Merlin and released on February 6, 2002 (first release under JCP).

New features in J2SE 1.4

  • XML Processing
  • Java Print Service
  • Logging API
  • Java Web Start
  • JDBC 3.0 API
  • Assertions
  • Preferences API
  • Chained Exception
  • IPv6 Support
  • Regular Expressions
  • Image I/O API

J2SE Version 1.3

Code named Kestrel and released on May 8, 2000.

New features in J2SE 1.3

  • Java Sound
  • Jar Indexing
  • A huge list of enhancements in almost all the java area.

J2SE Version 1.2

Code named Playground and released on December 8, 1998.

New features in J2SE 1.2

  • Collections framework.
  • Java String memory map for constants.
  • Just In Time (JIT) compiler.
  • Jar Signer for signing Java ARchive (JAR) files.
  • Policy Tool for granting access to system resources.
  • Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
  • Java Plug-in
  • Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
  • Audio support in Applets.

JDK Version 1.1

Released on February 19, 1997.

New features in JDK 1.1

  • JDBC (Java Database Connectivity)
  • Inner Classes
  • Java Beans
  • RMI (Remote Method Invocation)
  • Reflection (introspection only)

JDK Version 1.0

Codenamed Oak and released on January 23, 1996.






Wednesday, 18 December 2013

Reading properties file in Spring

weekendplan_prod.properties
activation.user.notvalid.msg  = Requested user is not authorized.
 
applicationContext.xml
 
<bean id="kleverlinksProperties" 
class="com.kleverlinks.common.utils.KleverlinksPropertyutil"> <property name="systemPropertiesModeName" 
value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
          <property name="ignoreResourceNotFound" value="true"/>
          <property name="locations">
            <list>
              <value>classpath:weekendplan_prod.properties</value>
            </list>
          </property>
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
        </bean>
weekendplan_prod.properties is name of the property file.
 
KleverlinksPropertyutil.java
package com.kleverlinks.common.utils;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * 
 * Loads properties from the property file.
 * 
 */
public class KleverlinksPropertyutil extends PropertyPlaceholderConfigurer{
  private static Log log = LogFactory.getLog(KleverlinksPropertyutil.class);
  static Properties proeprties;
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
  throws BeansException
   {
       try
       {
        proeprties = mergeProperties();
        convertProperties(proeprties);
        processProperties(beanFactory, proeprties);
       }
       catch(IOException ex)
       {
        log.error("Exception while reading the properties file " +ex);
       }
    }
     public static String getStringValue(String key) {
      return proeprties.getProperty(key);
     }

}
How to use properties in property file
System.out.println( KleverlinksPropertyutil.getStringValue("activation.user.notvalid.msg"));  
OUTPUT:
Requested user is not authorized.
Another way to configure property file:
<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="location">
      <value>database.properties</value>
    </property>
  </bean>