I know how to make sure if a specific parameter exists in the url.
I would like to make sure there is not any parameter in the url not just a specified one. How can I accomplish this? I have a long list of parameters and it looks like inefficient to have a list of conditions for all of them.
Sample URL is: www.domain.com/Product/UniqueId
As each product has many unique parameters, users might reach product pages through, unique code,unique supplier, unique sig, unique pod etc of the products.
For example:
www.domain.com/Product/UniqueId?code=uniqueCode
www.domain.com/Product/UniqueId?sig=uniqueSig
www.domain.com/Product/UniqueId?pod=uniquepod
www.domain.com/Product/UniqueId?circle=circleNumber&location=Location&color=Color
The questions that I found relevant but not useful in my case were 1,2,3,4
I need to do such testing in JSP not Java.
This works out a bit easier with the URI class:
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
public class UrlTest2
{
public static void main( String[] args )
throws MalformedURLException, URISyntaxException
{
URI url = new URI( "www.domain.com/Product/UniqueId" );
System.out.println( url.getQuery() ); // prints "null"
URI url2 = new URI( "www.domain.com/Product/UniqueId?pod=uniquepod" );
System.out.println( url2.getQuery() ); // prints "pod=uniquepod"
}
}
So if getQuery() returns null there are no parameters. Otherwise, there are.
Regarding your edit: Well, I don't really recommend putting code inside a JSP. It's consider bad practice nowadays.
But if you must, it looks like you can ask for all of the parameters and if the result is 0, there weren't any.
<%
Map params = request.getParameterMap();
boolean noParams = (params.getSize() == 0);
%>
JSP code is untested, but should give you the idea. You can then use the boolean noParams later in the JSP code.
Followup
With the new requirement that it has to be done in JSP, even though the Spring handler code listed in the original answer below could add a Model attribute with the relevant information, here is how to do that.
Similar two ways as below:
<!-- Use the parameter Map -->
<c:if test="${empty param}">
<!-- no query parameters given -->
</c:if>
<!-- Use the request object -->
<c:if test="${pageContext.request.queryString == null}">
<!-- no query parameters given -->
</c:if>
Original Answer
You tagged spring-mvc, so that means you have something like this (would have been nice if you had posted it):
#Controller
public class ProductController {
#RequestMapping("/Product/UniqueId")
public String uniqueId(Model model,
#RequestParam(path="code" , required=false) String code,
#RequestParam(path="sig" , required=false) String sig,
#RequestParam(path="pod" , required=false) String pod,
#RequestParam(path="circle" , required=false) String circle,
#RequestParam(path="location", required=false) String location,
#RequestParam(path="color" , required=false) String color) {
// code here
}
}
Here are two ways of checking for "no query parameters":
// Get all parameters in a Map
public String uniqueId(Model model,
...,
#RequestParam Map<String, String> allParams) {
if (allParams.isEmpty()) {
// no query parameters given
}
// code here
}
// Use the request object
public String uniqueId(Model model,
...,
HttpServletRequest request) {
if (request.getQueryString() == null) {
// no query parameters given
}
// code here
}
You might want to check this link for all the various types of parameters that Spring can give you:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-arguments
try this http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence).
I gave you code just to find is there any parameters passed in url. It won't give the number of parameters like that..
String stringObj ="www.domain.com/Product/UniqueId";
(stringObj.contains("?"))?true: false;
Not sure what you mean by "to make sure there is not any parameter".. you just can't, clients can use whatever URL they want to hit your server. You can only choose to process based on the URL string your server code receives.
Otherwise, here is two pointers:
Are you trying to check or parse the URL ? If so you can do:
url.indexOf('?') < 0 , assuming url varialble has the entire url
string...
Also see Java URL api to get query string, etc.
JSP hold an implicit object a paramValue that maps the request parameters to an array. You can use this object, and JSTL length function to learn the number of parameters directly in jsp, something like
<c:if test="${fn:length(paramValues) gt 0}">...</c:if>
make sure to include the following taglibs at the beginning of your jsp page
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
We can easily check for parameters using Regex. Lets say you have the following URLs:
www.domain.com/Product/UniqueId?foo=bar
www.domain.com/Product/UniqueId
Now, the actual URL can be anything. We can mark it as .*, which means anything. (Dot = any character, * = Zero or more times. There are more complex regexes to check for URLs but you said you are given URLs hence they aren't relevant).
After you matched your URL, you want to check for parameters.
Parameters are in the syntax of:
?key=value&key=value&key=value...
So we want to check for a question mark followed by a combination of keys and values. The regex would be:
\?((.*=.*)(&?))+
That matches a question mark, followed by: a key (.), an equals sign, a value(.) and a possible & (&?), 1 or more times (+)
So you can put it in a method like so:
public boolean hasParameters(String url){
return url.matches(".*\\?((.*=.*)(&?))+");
}
www.domain.com/Product/UniqueId?foo=bar would match the regex, and www.domain.com/Product/UniqueId wouldn't, because it isn't followed by the parameters.
P.S: The double slash before the question mark is in sake of java, not in sake of regex.
Link: Regex checker with the following regex & example
If you want to use it in JSP, simply put this method in a scriplet (started with <% and ended with %>), or anywhere else in your code actually.
Use the methods of java.net.URI to get all you need about the URL.
Related
I am trying to show through JSP code the value of some variables stored in in ArrayList money.
I am using Java for this project.
The thing is that when I try to do:
<c:forEach var="pos" items="${yourGame.money}">
<c:out value="${pos.nombre}"/>
${pos.nombre}: <b>${pos.precio}</b>
<br/>
</c:forEach>
It shows nothing, and I have made sure that yourGame.money isn't empty so I don't know what's going on. I am new to JSP and have run out of ideas; could anyone please help me?
This are the structures I am using:
public class Juego{
String nombre;
String plataforma;
String edicion;
ArrayList<Precios> money = new ArrayList();
}
public class Precios{
String precio;
String url;
String nombre;
}
The JSP class recieves a "Juego" object, and I am trying to print the values of the "money" atribute. I know the class JSP is recieving the "Juego" object fine since I have already printed some other variables of this class such as :
<h3>The ultimate edition: ${yourGame.edicion}</h3>
And it works just fine ...enter code here
Please modify your variables to use private access and generate get and set methods for all of them. The issue will be resolved.
Can you cross check your controller/Action classes and ensure you are setting money attribute in this yourGame bean and this bean is stored in request or session properly.
This is the only place where I suspect, you might have missed something. Apart from this you jsp looks fine to me.
One more point to check, can you try to print like this
<c:out value="${yourGame.edicion}"/>
just wanted to make sure the core tag is working fine in your jsp.
I'm looking for a way to get the value of the class (for my example "AAABC") stored in a variable. I tried different key words with the getAttribute method, but none were successful. Key word "class" obviously gave me "gwt-Label", all the other key words gave me "null".
Using getAttribute is not necessary, if you can think of an other elegant way.
Example:
<div class="gwt-Label">AAABC</div>
driver.findElement(By.xpath("//div[#class='gwt-Label']")).getText();
This is solve your issue.
First you need to do the following to get the string from your class object:-
String example = object.toString();
// here in msg you will get the whole string < div class="gwt-Label"> AAABC< /div>
Now you can use approach like below to get your string:-
example = example.substring(example.indexOf(">") + 1);
As per the HTML to retrieve the class attribute you can use the following line of code :
String myClass = driver.findElement(By.xpath("//div[text()='AAABC']")).getAttribute("class");
I want to verify below text(HTML code) is present on page which as // characters , etc using selenium /jav
<div class="powatag" data-endpoint="https://api-sb2.powatag.com" data-key="b3JvYmlhbmNvdGVzdDErYXBpOjEyMzQ1Njc4" data-sku="519" data-lang="en_GB" data-type="bag" data-style="bg-act-left" data-colorscheme="light" data-redirect=""></div>
Appreciate any help on this
I believe you're looking for:
String textToVerify = "some html";
boolean bFoundText = driver.getPageSource.contains(textToVerify)
Assert.assertTrue(bFoundText);
Note, this checks the page source of the last loaded page as detailed here in the javadoc. I've found this to also take longer to execute, especially when dealing with large source codes. As such, this method is more prone to failure than validating the attributes and values and the answer from Breaks Software is what I utilize when possible, only with an xpath selector
As Andreas commented, you probably want to verify individual attributes of the div element. since you specifically mentioned the "//", I'm guessing that you are having trouble with the data-endpoint attribute. I'm assuming that your data-sku attribute will bring you to a unique element, so Try something like this (not verified):
String endpoint = driver.findElement(
new By.ByCssSelector("div[data-sku='519']")).getAttribute("data-endpoint");
assertTrue("https://api-sb2.powatag.com", endpoint);
I'm looking for possibility to add anchor to url returned in controller:
public static Result open(String id) {
// here I want to add acnhor like #foo to the produced url
return redirect(routes.MyPage.show(id));
}
I found that it was possible in play 1 using addRef method, but I couldn't find any replacement of the method in play 2.
Of course I can use concatenation like:
public static Result open(String id) {
// here I want to add acnhor like #foo to the produced url
return redirect(routes.MyPage.show(id).url + "#foo");
}
But it seems ugly.
Thank you for any help! Have a good day!
Before trying to answer that question.
I should recommend you change whatever behavior you're currently setting.
Because, an URL fragment's purpose is client side only. Such fragment is never sent to the server, so that it's cumbersome to do the opposite.
However, here is the embryo of a (quite?) elegant solution that you could follow.
What I'll try to do is to leave the browser deal with the fragment, in order to keep potential behaviors (f.i. go to ID or even deal with history...).
To do so, you could add an implicit parameter to your main template which will define the fragment that the URL should have:
#(title: String)(content: Html)(urlFragment:Option[UrlFragment] = None)
As you can see I wrapped the parameter in an Option and default'ed it to None (in order to avoid AMAP pollution).
Also, it simply wraps a String but you could use String alone -- using a dedicated type will enforce the semantic. Here is the definition:
case class UrlFragment(hash:String)
Very simple.
Now here is how to tell the browser to deal with it. Right before the end of the head element, and the start of body, just add the following:
#urlFragment.map { f =>
<script>
$(function() {
//after everything is ready, so that other mechanism will be able to use the change hash event...
document.location.hash = "#Html(#f.hash)";
});
</script>
}
As you can see, using map (that is when the urlFragment is not None) we add a script block that will set the hash available in urlFragment.
This might be a start, however... Think about another solution for the whole scenario.
As of Play 2.4, it's possible to use Call.withFragment().
routes.Application.index.withFragment("some-id").absoluteURL(request)
This was added by PR #4152.
We're using fortify to scan java source code & it is complaining below error:
Method abc() sends unvalidated data to a web browser on line 200, which can result in the browser executing malicious code.
We've below code on line 200:
Product
And Util.java hsa below code in getProduct method:
String prod = request.getParameter("prod");
Can any one tell me how to fix this XSS vulnerability?
Thanks!
You need to escape the output of Util.getProduct(request). Typically this is done using JSTL and a <c:out> tag and EL:
Product
N.B. you'll have to use a fairly up-to-date implementation of EL (as per JSTL or JSP 2.0 EL for getter with argument and Parameters in EL methods) in order to pass an argument to the getter method.
Since the code in your question contains scriptlets, I will strongly suggest that you read How to avoid Java code in JSP files? This question covers reasons to use JSTL+EL instead of scriptlets, as well as a bit of information about what those two acronyms actually refer to.
In case you don't have JSTL for this website, you can fix the problem by making sure you only print valid products:
public String getProduct( String prod ) throws InputValidationException {
if ( prod.equals( "myProduct1" )
|| prod.equals( "myProduct2" )
|| prod.equals( "myProduct3" )
// etc.
) {
return "/foo/page.jsp?product=" + safeProduct;
}
else {
throw new InputValidationException( "Invalid product key provided." );
}
}