how to get full path of URL including multiple parameters in jsp - javascript

Suppose
URL: http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
<%
String str=request.getRequestURL()+"?"+request.getQueryString();
System.out.println(str);
%>
with this i get the output
http:/localhost:9090/project1/url.jsp?id1=one
but with this i am able to retrieve only 1st parameter(i.e id1=one) not other parameters
but if i use javascript i am able to retrieve all parameters
function a()
{
$('.result').html('current url is : '+window.location.href );
}
html:
<div class="result"></div>
i want to retrieve current URL value to be used in my next page but i don't want to use sessions
using any of above two method how do i retrieve all parameters in jsp?
thanks in advance

Given URL = http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
request.getQueryString();
Should indeed return id1=one&id2=two&id3=three
See HttpServletRequest.getQueryString JavaDoc
I once face the same issue, It's probably due to the some testing procedure failure.
If it happens, test in a clear environment : new browser window, etc.
Bhushan answer is not equivalent to getQueryString, as it decode parameters values !

I think this is what you are looking for..
String str=request.getRequestURL()+"?";
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements())
{
String paramName = paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++)
{
String paramValue = paramValues[i];
str=str + paramName + "=" + paramValue;
}
str=str+"&";
}
System.out.println(str.substring(0,str.length()-1)); //remove the last character from String

Related

adding parameter values inside of parenthesis while using scala.html

i would like to add dynamic parameter values (not sure if i can call it like this)
to the url in my scala html.
Using javascript, I get userId first and then would like to pass it to #routes.adminController.auth(userId).
Here is my source code,
<script type="text/javascript">
function checkboxChecked() {
var checkbox = $('td > input:checked').length;
if(checkbox == 1){
var $checked = $('td > input:checked');
var userId = $checked.parent().next().text();
** I would like to add below and make it work**
//location.href = #routes.AdmnTask.user_set(userId)
} else {
alert("Please select 1 User ID to proceed.")
}
};
</script>
After a few attempts, I noticed that I am not able to set some random variable and put into location.href as below.
var link = "#routes.AdmnTask.user_set(userId)"
location.href = link
Could anyone give me a help with this issue please?
Thank you in advance.
As I said in the comments, you can't use a Javascript variable inside a Scala function, since the Scala is executed server-side and the Javascript client-side.
There's a workaround, though.
If your #routes.AdmnTask.user_set( ... ) gives you an URL with the parameter at the end, like http://example.com/userSet/1 or http://example.com/userSet?id=1, you could create a function that transforms this URL into a more generic one :
/**
* Gets the base URL for a given route
*
* #param url Call - The route called with the parameter 0
* #return The URL base String.
*/
public static String baseUrl(play.api.mvc.Call url){
return url.toString().substring(0, url.toString().length() - 1);
}
This function will cut off the last character from your URL String, so that you can use it in your Scala template.
Then, all you need to do in your Scala / Javascript is :
location.href = '#yourClass.baseUrl(routes.AdmnTask.user_set(0))' + userId
EDIT: Here is the Scala version of the function above :
def baseUrl(url: play.api.mvc.Call): String = {
url.toString.substring(0, url.toString.length - 1)
}

How to get a specific portion of the url using javascript?

var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()

Parse URL which contain string of two URL

I've node app and Im getting in some header the following URL and I need to parse it and change the content of 3000 to 4000 ,How can I do that since Im getting "two" URLs in the req.headers.location
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node"
The issue is that I cannot use just replace since the value can changed (dynmaic value ,now its 3000 later can be any value...)
If the part of the URL you always need to change is going to be a parameter of redirect_uri then you just need to find the index of the second %3A that comes after it.
Javascript indexOf has a second parameter which is the 'start position', so you can first do an indexOf the 'redirect_uri=' string, and then pass that position in to your next call to indexOf to look for the first '%3A' and then pass that result into your next call for the %3A that comes just before your '3000'. Once you have the positions of the tokens you are looking for you should be able to build a new string by using substrings... first substring will be up to the end of your second %3A and the second substring will be from the index of the %2F that comes after it.
Basically, you will be building your string by cutting up the string like so:
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A"
"%2Flogin%2Fcallback&client_id=x2.node"
... and appending in whatever port number you are trying to put in.
Hope this helps.
This code should get you what you want:
var strURL = "http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node";
var strNewURL = strURL.substring(0,strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3) + "4000" + strURL.substring(strURL.indexOf("%2F",strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3));
Split the return string in its parameters:
var parts = req.headers.location.split("&");
then split the parts into fieldname and variable:
var subparts = [];
for (var i = 1; i < parts.length; i++)
subparts[i] = parts[i].split("=");
then check which fieldname equals redirect_uri:
var ret = -1;
for (var i = 0; i < subparts.length; i++)
if (subpart[i][0] == "redirect_uri")
ret = i;
if (ret == -1)
// didnt find redirect_uri, somehow handle this error
now you know which subpart contains the redirect_uri.
Because I dont know which rules your redirect_uri follows I can't tell you how to get the value, thats your task but the problem is isolated to subparts[ret][1]. Thats the string which contains redirect_uri.

JavaScript - splitting window.location.href returns undefined

I have the following code JavaScript:
var url = window.location.href;
var link = url.split('?link=');
link[1] = "http://goo.gl/" + link[1];
link[2] = "http://goo.gl/" + link[2];
function ad(){
window.location.href = link[1];
}
function ac(){
window.open(link[2], '_blank');
}
And there is a link:
ACCESS
The problem is that in some computers, the split is not working.
For exemple: If the link is mySite.com/link.html?link=wfijOp?link=atGdj.
It should give me goo.gl/wfijOp and goo.gl/atGdj instead of goo.gl/undefined and goo.gl/undefined.
What is the problem with those computers?
Thanks, #arcyqwerty! I did what you suggested.
Usually ? is used for separating the query string from the path (see
comment above). Try using another separator like link=abcd,efgh,ijkl.
You can use this to get the query string variable. – #arcyqwerty
Go to the answer

Java Script to MVC: Controller Variable Passing via Actionlink

Using: vs'12 Razor asp.net MVC4 Internet App Template EF Code First
My Actionlink that i am trying to manipulate
#Html.ActionLink("Download", "ShowOpenAcreageSummaryReport", new { controller = "DataToExcel" }, new { id = "AddData" })
The script to attempt this
$('#AddData').click(function (e) {
var optVal = $("#OptionsDrop").val();
var Xpro = $("#Prospects").val()
var Xcnty = $("#Countys").val()
var Xtwn = $("#TownShips").val()
var Xrng = $("#Ranges").val()
var Xsct = $("#Sections").val()
var href = "/DataToExcel/ShowLPRStandardLeaseReport/" + Xpro + Xcnty + Xtwn + Xrng + Xsct;
this.href = ""; //clears out old href for reuse
this.href = href; //changes href value to currently slected dropdown value
}
The actionResult to accept these passed values
public ActionResult ShowLPRStandardLeaseReport(string pro, string cnty, string twn, string rng, string sec)
Now i know this works with 1 variable as i have this code running on another page, however it won't work with multiple.
I have also tried adding + "/" + between the Variables, which had no effect on the outcome.
How can i change my code to be able to pass all variables??
Have you tried with GET parameters such as some-url/?param1=test&param2=test2 ? Also note that this points to the #AddData element in the click handler. If you want to change the current location, use window.location.href = 'someurl';
The ? is necessary to indicate the start of the query string parameters.
Also note that you should be encoding the values with encodeURIComponent to make sure that you are producing a valid URL.

Categories