[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

passing a Map from javascript to Java

Posted on 2014-08-08
4
Medium Priority
?
729 Views
Last Modified: 2014-09-05
Hi,
I have the following code in a jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="/WEB-INF/classes/affiliate.tld" prefix="affiliate" %>
<%@ taglib uri="/WEB-INF/yatraTagLib.tld" prefix="yatra" %>

<c:if test="${(tenantScope eq 'dom') && (pageID eq 'search') && (trackAffiliate == true)}">
	<affiliate:scriptTag affiliateurl='${trackerBaseUrl}/affiliateLogger?version=DFTL&PAGE_TYPE=CONFIRM&PRODUCT_TYPE=AIR&logger=TRUE' paramMap='${affiliationParamMap}' />					      		
</c:if>

Open in new window


Here the affiliationParamMap is being generated in java code and is passed to the jsp in a model.

Affiliate.tld :

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag 
Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.1</jsp-version>
  <short-name>yatra</short-name>
  <tag>
 	 <name>scriptTag</name>
  	 <tag-class>com.yatra.platform.commons.utils.YatraAffiliateHandler</tag-class>
 	 <body-content>empty</body-content>
  	<attribute> 
  	      <name>affiliateurl</name>
  	       <required>true</required>
  	       <rtexprvalue>true</rtexprvalue> 
    </attribute> 
	<attribute> 
  	      <name>paramMap</name>
  	       <required>false</required>
  	       <type>java.util.Map</type>
  	       <rtexprvalue>true</rtexprvalue>
  	 </attribute>
   </tag>
</taglib>

Open in new window


YatraAffiliateHandler.java
package com.yatra.platform.commons.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

import org.apache.log4j.Logger;

import com.yatra.platform.commons.property.PropertyManager;

public class YatraAffiliateHandler implements Tag{
	
	private static Logger logger = Logger.getLogger(YatraAffiliateHandler.class); 
	
	String affiliateurl;
	Map<String,String> paramMap;
	PageContext pageContext;
	
	public String getAffiliateurl() {
		return affiliateurl;
	}

	public void setAffiliateurl(String affiliateurl) {
		this.affiliateurl = affiliateurl;
	}

	public Map<String, String> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, String> paramMap) {
		this.paramMap = paramMap;
	}

	@Override
	public int doEndTag() throws JspException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int doStartTag() throws JspException {
		 try {
			 String result ="";
			 try{
				 result = YatraUtils.getURLResponse(
						 generateRequestParams(), 
						 affiliateurl, 
						 getConnectionTimeout(),
						 getCookies());
				 logger.debug("Affiliation result : "+ result);
			 }catch (Exception e) {
				logger.error("Unable to get affilation string",e);
			}
			pageContext.getOut().print(result);
	  } catch (IOException ioe) {
		  throw new JspException("Exception caught :", ioe);
	  }
	  return SKIP_BODY;
	}

	@Override
	public Tag getParent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setPageContext(PageContext pageContext) {
		this.pageContext = pageContext;
		
	}

	@Override
	public void setParent(Tag arg0) {
		// TODO Auto-generated method stub
		
	}
	
	private String generateRequestParams(){
		StringBuilder builder = new StringBuilder();
		if(paramMap!=null){
			for(Entry<String,String> entry : paramMap.entrySet()){
				builder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
			}
		}
		return builder.length()>2?builder.substring(1):"";
	}

	private int getConnectionTimeout(){
		PropertyManager propertyManager = (PropertyManager)YatraSpringFactory.getBean("propertyManager");
		return propertyManager.getPropertyAsInt("affiliate.request.time.out");
	}
	public String getCookies() {
		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
		String text="";
 	    Cookie[] cookies = request.getCookies();
		  if(cookies != null){
			  for(int i = 0; i < cookies.length;i++){
		      	if(i>0){
		      		text = text + ";";
	 	        }
			  text = text + cookies[i].getName() + "=" + cookies[i].getValue();
			}
		  }
		return text;
	}
}

Open in new window



Now i want to move the generation of affiliationParamMap to javascript.
How do i do it  and make the map work in jsp.

Thanks
0
Comment
Question by:Rohit Bajaj
  • 2
4 Comments
 
LVL 12

Accepted Solution

by:
Gibu George earned 2000 total points
ID: 40250237
You want to get the data(Map) into javascript, you cannot use the jsp custom tag as it renders the data to JSP. You can use ajax calls to a servlet which returns the required map from the jsp as json and use it in javascript. If you still want to use the custom tag, and you want the map in javascript you need to modify the custom tag to generate the javascript code as well.
0
 

Author Comment

by:Rohit Bajaj
ID: 40252581
Hi,
I can use ajax calls to a servlet which returns the map as json. But i need to fire the following url :
http://yjs.yatra.com/flights-aff-tracking/affiliateLogger?version=FLOODLIGHTTAG_PAYMENT&logger=TRUE&FLIGHT_SECTOR=DOMF

In this version, logger, FLIGHT_SECTOR are in affiliation map currently which is getting generated in java code.
Generating this map in java is requiring separate Database hits which is time consuming. We are fetching data using Xpath etc.
But we are already having all the data in Json.

But constructing a map in javascript and using it in jsp i think not possible ?
If i could make map in javascript and pass it to Jsp then my effort will be minimum.
0
 

Author Comment

by:Rohit Bajaj
ID: 40252886
Hi,
Just to clarify my question more. The whole code is written in java server side. I want to move it to client side in Javascript.
I want to generate Map in javascript and fire urls. That what my code does in jsp and java.
But i want to port the whole thing in javascript
0
 
LVL 34

Expert Comment

by:Slick812
ID: 40258571
greetings Robinsuri, , I do not do Java code at this time, but as I remember, the java Map, is just a dynamic container for Key-Values pairs, you can have a container in javascript to hold key-value pairs, as an "js object" with these pairs
    "version=FLOODLIGHTTAG_PAYMENT&logger=TRUE&FLIGHT_SECTOR=DOMF"  -

var paramMap = {version:"FLOODLIGHTTAG_PAYMENT", logger:"TRUE", FLIGHT_SECTOR:"DOMF"}

in your java code there is not much done with your paramMap, you set it with -
     setParamMap(Map<String, String> paramMap) {this.paramMap = paramMap;}

and you make a URL request string with -
generateRequestParams(){ StringBuilder builder = new StringBuilder();
  if(paramMap!=null){
    for(Entry<String,String> entry : paramMap.entrySet()){
      builder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
      }
    }
  return builder.length()>2?builder.substring(1):"";
  }

you can use the object pairs in javascript to make the same  URL request string as the java did, however, as I see it, you problem is going to be writing the of all the "INFORMATION" as data from your java page to the javascript in strings on the web page as javascript variables -

var url1 = {version:"FLOODLIGHTTAG_PAYMENT"; logger:"TRUE"; FLIGHT_SECTOR:"DOMF"}

if you do not have much javascript knowledge or experience, this may not go well for you?
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month18 days, 7 hours left to enroll

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question