Wednesday, December 19, 2012

How to share data between two diff web apps


How to share data between web-apps

way 1) Sharing data using cookies
===================

Code on WebApp1 Login Servlet
-------------------------------------------
 below code will be execute once you click on any link or button , and it will call the login servlet  
 of webApp2 and webApp2 will read the data from the cookies

userData.put("password", radiusLoginForm.getPassword());
Cookie cookie1 = new Cookie("username","admin");
cookie1.setPath("/");
Cookie cookie2 = new Cookie("password","admin");
cookie2.setPath("/");

response.addCookie(cookie1);
response.addCookie(cookie2);


code on webapp2 Login Servlet to obtain data from the cookies
-----------------------------------------------------------------------------------
        String username= "";
        String password= "";

        Cookie cookies[] = request.getCookies();
for(Cookie cookieObj : cookies){
if(cookieObj.getName().equalsIgnoreCase("username")){
username = cookieObj.getValue();
}else if(cookieObj.getName().equalsIgnoreCase("password")){
password = cookieObj.getValue();
}
}


way 2) Sharing data using ServletContext
===============================

Note : Lets assume that we are accessing webApp2 from webApp1

First open and edit the tomcat "server.xml"

Find the tag into server.xml and add the crossContext="true" attribute into both the   
        context tag

Ex:
 
 

Then add the context param into the web.xml of  webApp2
Ex:

  SharedSessiondataContext
  /webApp1

Code into the webApp1 Login servlet (this servlet you will call from the webApp1 servlet)
-----------------------------------------------------------------------------------------
below code will obtained you the data which you have shared using the webApp1 servlet context

  HashMap userData = new HashMap();
  userData.put("username", "admin");
  userData.put("password", "admin");
storeDataInContext(getServlet().getServletContext(), sessionId, userData);

public synchronized static void storeDataInContext(ServletContext context, String sessionid, HashMap
String> userData)
{
    Hashtable> shareddata = new Hashtable>();
    shareddata.put(sessionid, userData);
    context.setAttribute("sharedUserData", shareddata);
}


Code into webApp2 Login Servlet
-------------------------------------
HashMap userData = getUserRolesFromContext(getServletConfig().getServletContext(),ssoSessionid);

public static HashMap getUserRolesFromContext(ServletContext context, String ssosessionid) {
   String SignonContext = context.getInitParameter("SharedSessiondataContext");
   HashMap userData = null;
   if(SignonContext!=null){
   ServletContext ssocontext = context.getContext(SignonContext);
   if(ssocontext!=null){
   Hashtable> shareddata = ((Hashtable
HashMap>)ssocontext.getAttribute("sharedUserData"));
   if (shareddata!=null) {
       Logger.logInfo(MODULE,"SSOSESSIONID : "+ssosessionid);
       userData =(HashMap)shareddata.get(ssosessionid);        
   }
   }
   }
   return userData;
}




way 3) Sharing Data using URL parameters
=========================================

This code is for basic sso implementation using URL parameters

WebApp1 
-------------
Lets assume that you are logged-in in your WebApp1 and
calling below URL of WebApp2 using any menu-link in WebApp1 jsp page

i.e : http://localhost:8080/WebApp2/LoginServlet?sessionId=<%=request.getSession().getId()%>

once you will clicked upon this url your WebApp2's LoginServlet will get called and below code will be
        execute in your LoginServlet of WebApp2

code in LoginServlet of WebApp2:
================================
String sessionIdParam = request.getParameter("sessionId");
String userIdParam = request.getParameter("userId");

if(sessionIdParam!=null && userIdParam==null){
           counter = 0;
           tempSessionId = sessionIdParam;
           String ssoUrl = getSSOUrl(); // this method will
           if(ssoUrl!=null){
            Logger.logInfo(MODULE, "Forwarding to "+ssoUrl);
response.sendRedirect("http://localhost:8080/WebApp1/LoginServlet?                      

        sessionId="+sessionIdParam);
// from here LoginServlet of WebApp1 will be called and we will send back the same sessionId
           }else{
            System.out.println("Invalid URL");
           }
           return;
}else{
           counter++;
}

if(sessionIdParam!=null && userIdParam!=null){
        if(tempSessionId.equals(sessionIdParam) && counter==1){
// you are done with the user verification you can do here further code now
            }
}

code in LoginServlet of WebApp1:
================================

String sessionId = (String)request.getParameter("sessionId");
// userId/username you need to set in session after logged into the WebApp1, so you will get it from session
as given below
String userId = (String)request.getSession().getAttribute("userId");  
String currentSessionId = request.getSession().getId();

if(sessionId!=null && userId!=null){
           if(currentSessionId.equals(sessionId)){
response.sendRedirect("http://localhost:8081/WebApp2/LoginServlet?userId="+userId

+"&sessionId="+sessionId);
            }
           }
}

Read Me:
--------
In Above code we are verifying the sessionid with the sessionid we have received from the WebApp2's
response.sendRedirect() url and after verifying the url we are sending back the same sessionId , and this time
we are sending the userId also, so now we will have sessionId and userId in the WebApp2, so we will verify this sessionId again on the WebApp2 and check whether we have received the userId or not, and if the sessionId is not null and userId is not null then we will verify the sessionId with the tempSessionId and then its done...


Thursday, December 13, 2012

Sharing data between different java web apps on same server, using context

Visit below Link for the complete help

source : http://www.fwd.at/tomcat/sharing-session-data-howto.html

Thursday, December 6, 2012

JAVA SCRIPT to get url parameters

function getUrlParameteres() {
   var vars = {};
   var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
   });
return vars;
}
function autoLogin(){
    var username = getUrlParameteres()["username"];
   var password = getUrlParameteres()["password"];
   if(username!=null && password !=null && username!=’undefined’ &&       password!=’undefinied’){
             document.systemLoginForm.userName.value=username;
             document.systemLoginForm.password.value=password; 
             document.systemLoginForm.submit();
    }
}