Pass JSP Input with href link - arrays

I want to pass input data with a href instead of a button. The problem is I am sending an array, my for loop the input data is being stored so It creates multiple links. What is the course of action to take to fix this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Firstjsp</title>
</head>
<body>
<% String locations[] = {"Loan 1", "33.890542", "151.274856", "Address 1","true", "-35404.34"};
for (int i =0; i<locations.length; i++)
{
%>
<form name="submitForm" method="POST" action="Mapper.jsp">
<Input type = "Hidden" name = "loc" value = "<%= locations[i] %>">
View Map
</form>
<%
}
%>
</body>
</html>

The HTTP request query string takes the form of name1=value1&name2=value2&name3=value3. So all you need to do is converting the String[] to a String in exactly that format. Additional requirement is to use URLEncoder to encode the names and values so that any special characters are been converted to %nn format for proper usage in URLs.
This should do:
StringBuilder builder = new StringBuilder();
for (String location : locations) {
if (builder.length() > 0) builder.append("&");
builder.append("loc=").append(URLEncoder.encode(location, "UTF-8");
}
String locationsQuery = builder.toString();
Then you can specify it in the link as follows:
View Map
How to obtain it in the other side has already been answered in your previous question.
Unrelated to the concrete problem, writing raw Java code in JSPs is officially discouraged since a decade. You can achieve the same on a more easy manner with JSTL <c:url>, <c:param> and <c:forEach>. Here's a kickoff example assuming that you've done a request.setAttribute("locations", locations) in your preprocessing servlet or in top of JSP:
<c:url value="Mapper.jsp" var="mapperURL">
<c:forEach items="${locations}" var="loc">
<c:param name="loc" value="${loc}" />
</c:forEach>
</c:url>
View Map

Related

How to get Text from H1 Tag which has no arguments in Web Driver?

<html>
<head>...</head>
<body>
<h1>Phonetic Translator</h1>
<br>
<link rel="stylesheet" href="/style.css" type="text/css">
<title>electRa Phonetic Translator</title>
<p>Today's password is:</p>
<h1>
MQQJXJLCQZ
<hr width="80%">
</h1>
<p>The phonetic translation is:</p>
<h3>
...
</h3>
...
</body>
<html>
Hi,
I want to get the text MQQJXJLCQZ. As there are two H1 tags after Body. I have used XPath to get the text value but unfortunately I am getting the error message Type mismatch: cannot convert from String to WebElement
The code I have written is :
String PasswordxPath = "/html/body/h1[2]/text()";
WebElement H1Element = driver.findElement(By.xpath(PasswordxPath));
WebElement getPassword = H1Element.getText();
Please, can someone correct this code or suggest another way to get the text Value ?
Thanks,
UPDATE1
I have used string to get the text value, but now i am unable to put this value in the form using sendKeys. Error log as below:
Element info: {Using=xpath, value=/html/body/h1[2]/text()} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Nativ‌​‌​e Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknow‌​‌​n Source)
I had a similar problem where getText() wasn't working.
Try using getAttribute("innerHTML")
Replace WebElement by String in the last line :
String PasswordxPath = "/html/body/h1[2]/text()";
WebElement H1Element = driver.findElement(By.xpath(PasswordxPath));
String getPassword = H1Element.getText();
As said, here is the problem
WebElement getPassword = H1Element.getText();
getText() returns the String value but not WebElement. So you need to use String here, like
String getPassword = H1Element.getText();

OWASP HTML Sanitizer allow colon in HTML

How can I allow : sign in sanitized HTML? I am using it to sanitize HTML code in generating java mail. This code has an inline image content id like <img src=\"cid:image\" height=\"70\" width=\"70\" />. Upon sanitizing, the src attribute is not included in the sanitized html.
PolicyFactory IMAGES = new HtmlPolicyBuilder().allowUrlProtocols("http", "https")
.allowElements("img")
.allowAttributes("src").matching(Pattern.compile("^cid[:][\\w]+$"))
.onElements("img")
.allowAttributes("border", "height", "width").onElements("img")
.toFactory();
String html = "<img src=\"cid:image\" height=\"70\" width=\"70\" />";
final String sanitized = IMAGES.sanitize(html);
System.out.println(sanitized);
The output of above code is:
<img height="70" width="70" />
Why it isn't working
Or rather, why it's working "too well"
By default, HtmlPolicyBuilder disallows URL protocols in src elements. This prevents injections such as
<img src="javascript:alert('xss')"/>
which could potentially lead to the execution of the script after javascript: (in this case, alert('xss'))
There are other protocols (on other elements) that can lead to similar issues:
Even though it doesn't use the javascript protocol, it's still possible to inject a base64-encoded XSS injection:
<object src="data:text/html;base64,PHNjcmlwdD5hbGVydCgneHNzJyk8L3NjcmlwdD4="/>
or
Click me
Because of this, HtmlPolicyBuilder assumes that any attribute value containing a colon (in certain attributes) should be treated as dangerous.
How to fix it:
You have to explicitly tell the HtmlPolicyBuilder to allow the cid "protocol", using the allowUrlProtocols method:
PolicyFactory IMAGES = new HtmlPolicyBuilder().allowUrlProtocols("http", "https")
.allowElements("img")
.allowUrlProtocols("cid") // Specifically allow "cid"
.allowAttributes("src").matching(Pattern.compile("^cid[:][\\w]+$"))
.onElements("img")
.allowAttributes("border", "height", "width").onElements("img")
.toFactory();
String html = "<img src=\"cid:image\" height=\"70\" width=\"70\" />";
final String sanitized = IMAGES.sanitize(html);
System.out.println(sanitized);
Output:
<img src="cid:image" height="70" width="70" />

Pass Array .jsp to .jsp

I am wondering how to pass an array or a list from one .jsp page to another. I want to then take the values from this array and assign them to a javascript array. I think I have the source jsp page configured correctly, but was wondering how to get the values in the second .jsp page.
This is my source .jsp file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Firstjsp</title>
</head>
<body>
<Form Method = "Post" Action = "Mapper.jsp">
<% String locations[] = {"Loan 1", "33.890542", "151.274856", "Address 1","true", "-35404.34"};
for (int i =0; i<locations.length; i++)
{
%>
<Input type = "Hidden" name = "loc" value = "<%= locations[i] %>">
<%
}
%>
</Form>
</body>
</html>
You can get them using HttpServletRequest#getParameterValues(). This returns a string array of all parameter values which have the same parameter name. In your case, you have generated several hidden HTML input elements with the same name loc in the first JSP, so the following in the second JSP (or, preferably, a servlet) should do:
String[] locations = request.getParameterValues("loc");
The easiest way i think is to put the variable (it works even as a pointer) as a session variable.This way you can access it everywhere as long as the code is running under the same session.
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
This example also uses request.The difference is that session stands out.For example if you set a variable in session then even if you close the browser and restart it , it will still be there.Think of it as a global variable.Request is best used when you send data from one jsp/servlet to another jsp/servlet.It basically has a lifespan of 1.The moment when you redirect a page it disappears.
You can use session.setParameter(name_of_the_variable,the_variable) and session.getParameter(name_of_the_variable). As a hint that was useful to me,always make sure that you test the returned parameter, in the case above "name" if it's not NULL.If there is no variable on the session with that name, it will return NULL, and most likely crash.Hope this helps!

easy php array of images, from a WordPress custom field

I'm trying to use 1 custom field for a bunch of images - to do the same thing to all the images. I can store them in the custom field however is advisable, but I thought this format would be best, since I think that's what a PHP array goes into:
'http://images.domain.com/image1-Th.jpg',
'http://images.domain.com/image1-Th.jpg',
'http://images.domain.com/image3-Th.jpg'
So, once I have my custom field values entered for a post, here's my non-working PHP code:
<?php //og images
$ogimagepre = '<meta property="og:image" content="';
$ogimagepost = '"/>';
global $wp_query; $postID = $wp_query->post->ID;
$photosfull = array(get_post_meta($postID, 'custom_field_name', true));
echo $ogimagepre.$photosfull.$ogimagepost
?>
You can see I'm trying to get this result:
<meta property="og:image" content="http://images.domain.com/image1-Th.jpg"/>
<meta property="og:image" content="http://images.domain.com/image2-Th.jpg"/>
<meta property="og:image" content="http://images.domain.com/image3-Th.jpg"/>
That's Step1. Ideally, I'd be able to do other things using the same array. Such as replace "-Th.jpg" with "-X3.jpg", since that's a larger size of the same image. And other stuff; need to get past Step1 first.
Thanks!
I had a similar problem where I wanted images under a single meta key to be returned as unique elements. Try this:
$ogimagepre = '<meta property="og:image" content="';
$ogimagepost = '"/>';
global $wp_query; $postID = $wp_query->post->ID;
$photos =get_post_meta($postID, 'custom_field_name', true);
foreach ($photos as $photo){
echo $ogimagepre.$photo.$ogimagepost
}

HTML Input field force numbers

Is it possible to create an input field that sets the default input character set to numbers on a mobile phone (so the NUMERICAL KEYBOARD POPS UP)?
For example to make it easier type in a telephone number into a HTML form.
To make inputing numbers easier, use <input type="number">. To make entering phone numbers easier, use <input type="tel">. Not all phone will support them, but the iPhone at least will give you a numeric keypad by default instead of the normal keyboard. See the spec and Dive Into HTML5 for more information.
It is possible to limit entry on a "mobile phone"
The mobile phone form entry uses
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">
input here can be limited using format="*N"
You can use <input type='tel'>. This is a new HTML5 feature. Older browsers will simply default to a text input field.
So you can use either type="tel" or type="numbers".
The difference is that one tries to bring up your phone dial keyboard and other simply switches to the numbers input of your mobile keyboard.
Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . Code example:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Input Key Filter Test</title>
<meta name="author" content="Andrej Hristoliubov anhr#mail.ru">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<!-- For compatibility of IE browser with audio element in the beep() function.
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
</head>
<body>
<h1>Phone number</h1>
Please type a phone number in the +**(***)***-**-** format. Example: +1(23)456-78-90
<br/>
<input id="PhoneNumber" value="+()--">
<script>
function getArrayPhoneNumber(value){
if (typeof value == 'undefined')
value = document.getElementById("PhoneNumber").value;
return value.match(/^(\+?\d*)\((\d*)\)(\d*)-?(\d*)-?(\d*)$/);
}
function getPhoneNumber(){
var arrayPhoneNumber = getArrayPhoneNumber();
if(!arrayPhoneNumber)
return "";
var phoneNumber = arrayPhoneNumber[1] + arrayPhoneNumber[2] + arrayPhoneNumber[3] + arrayPhoneNumber[4] + arrayPhoneNumber[5];
return phoneNumber;
}
inputKeyFilter.Create("PhoneNumber", function(event){//onChange event
inputKeyFilter.RemoveMyTooltip();
var arrayPhoneNumber = getArrayPhoneNumber();
if(!arrayPhoneNumber || (arrayPhoneNumber.length != 6)){
document.getElementById("NewPhoneNumber").innerHTML = "Incorrect format of the phone number";
return;
}
var elementNewPhoneNumber = document.getElementById("NewPhoneNumber");
var phoneNumber = getPhoneNumber();
if(inputKeyFilter.isNaN(phoneNumber, this)){
elementNewPhoneNumber.innerHTML = "";
return;
}
elementNewPhoneNumber.innerHTML = phoneNumber;
}
, function(elementInput, value){//customFilter
var arrayPhoneNumber = getArrayPhoneNumber(value);
if(arrayPhoneNumber == null){
inputKeyFilter.TextAdd(isRussian() ?
"Недопустимый формат телефонного номера. Например: +1(234)56-78-90"
: "Incorrect format of the phone number. Example: +1(234)56-78-90"
, elementInput);
if(elementInput.value == "")
elementInput.value = elementInput.defaultValue;
return false;
}
return true;
}
//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
, function(event){ inputKeyFilter.isNaN(parseInt(getPhoneNumber()), this); }
);
</script>
New phone number: <span id="NewPhoneNumber"></span>
</body>
</html>
Also see my page "Custom filter:" example of the input key filter
Here's an example with Javascript. This will only allow numbers from the numpad/numbers on top of the keypad, and formatters (shift/backspace/etc). You may also consider adding a setTimeout(), with a couple seconds timeout, for the onchange event to check in case someone pastes non numbers into the field as well as server side validation.
Example
http://jsfiddle.net/vce9s/
for my testing of "you can use either type="tel" or type="numbers"."
on iPhone type="tel" brings up the numbers only keypad (like phone) and type="numbers" brings up the numeric keypad switched to numbers and symbols, so both work, just depends on your application. For me I only need numbers so I used type="tel" for ease of use and it worked great!

Resources