How to receive string array from servlet request in java [duplicate] - java

How can i send an Array with a HTTP Get request?
I'm Using GWT client to send the request.

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]
Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.
foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]
The request.getParameter("foo") will also work on it, but it'll return only the first value.
String foo = request.getParameter("foo"); // value1
And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.
foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true
In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.
$foo = $_GET["foo"]; // value1
echo is_array($foo); // false
Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.
String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

Related

How to replace a query string in an Apache Velocity template?

In my web application I'm trying to prevent users from inserting JavaScript in the freeText parameter when they're running a search.
To do this, I've written code in the header Velocity file to check whether the query string contains a parameter called freeText, and if so, use the replace method to replace the characters within the parameter value. However, when you load the page, it still displays the original query string - I'm unsure on how to replace the original query string with my new one which has the replaced characters.
This is my code:
#set($freeTextParameter = "$request.getParameter('freeText')")
freeTextParameter: $freeTextParameter
#if($freeTextParameter)
##Do the replacement:
#set($replacedQueryString = "$freeTextParameter.replace('confirm','replaced')")
replacedQueryString after doing the replace: $replacedQueryString
The query string now: $request.getQueryString()
The freeText parameter now: $request.getParameter('freeText')
#end
In the code above, the replacedQueryString variable has changed as expected (ie the replacement has been carried out as expected), but the $request.getQueryString() and $request.getParameter('freeText') are still the same as before, as if the replacement had never happened.
Seeing as there is a request.getParameter method which works fine for getting the parameters, I assumed there would be a request.setParameter method to do the same thing in reverse, but there isn't.
The Java String is an immutable object, which means that the replace() method will return an altered string, without changing the original one.
Since the parameters map given by the HttpServletRequest object cannot be modified, this approach doesn't work well if your templates rely on $request.getParameter('freeText').
Instead, if you rely on VelocityTools, then you can rather rely on $params.freeText in your templates. Then, you can tune your WEB-INF/tools.xml file to make this parameters map alterable:
<?xml version="1.0">
<tools>
<toolbox scope="request">
<tool key="params" readOnly="false"/>
...
</toolbox>
...
</tools>
(Version 2.0+ of the tools is required).
Then, in your header, you can do:
#set($params.freeText = params.freeText.replace('confirm','replaced'))
I managed to fix the issue myself - it turned out that there was another file (which gets called on every page) in which the $!request.getParameter('freeText')" variable is used. I have updated that file so that it uses the new $!replacedQueryString variable (ie the one with the JavaScript stripped out) instead of the existing "$!request.getParameter('freeText')" variable. This now prevents the JavaScript from being executed on every page.
So, this is the final working code in the header Velocity file:
#set($freeTextParameter = "$!m.request.httpRequest.getParameter('freeText')")
#if($freeTextParameter)
#set($replacedQueryString = "$freeTextParameter.replace('confirm','').replace('<','').replace('>','').replace('(','').replace(')','').replace(';','').replace('/','').replace('\"','').replace('&','').replace('+','').replace('script','').replace('prompt','').replace('*','').replace('.','')")
#end

Getting multiple parts from URL inside of controller

My servlet is mapped with <url-pattern> /controller/*/* </url-pattern> my url is like this controller/12341/ABC123 will always like this but values can be changed.
I am trying to get value of first * and second * which presents serial & mac
I write following code but it return only last part ACB123
String mac= request.getPathInfo().replace("/", "");
How can I get both vaules?
If I read the servlet spec correctly you cannot have multiple wildcards. Try
<url-pattern>/controller/*</url-pattern>
And then:
String[] parts = request.getPathInfo().split("/");
String serial = parts[1]; // before last index
String mac = parts[2]; // last index
Of course you will need some error handling for this.
On a related note: Pure servlet API is a pain to work with. If you have just this only servlet or are constrained somehow, this might be OK. However if you have more servlets and even need HTTP request parameter handling, parsing etc., using a framework like Spring WebMVC might be more appropriate.

Calling JavaScript function in Java

I'm trying to send an email using a javascript code in a Java project. Database connection works fine, I already tested it. I got the error:
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing ) after formal parameters (#1) in at line number 1
The only information of relevance is not readily reported: the final JavaScript string executed. Make sure to look at relevant data when debugging. After inspecting the final string it will be apparent why it is incorrect and trivial to "fix".
Hint: it will look something like function sendMail(userblah, foo#bar.qux) { .., which is indeed invalid JavaScript.
The problem and solution should be self-evident from that - use fixed parameters (variable names) in the function declaration and supply arguments (values) via the invokeFunction call.
Solution:
// The following parameter names are JAVASCRIPT variable names.
String script = "function sendMail(username, email, body) { ..";
// And pass correct arguments (values), in order. The variables used
// here are JAVA variables, and align by-position with the JS parameters.
inv.invokeFunction("sendMail", username, email, "EMAIL SENT!!!!");
In addition, the getElementById (invalid ID) is wrong, the body parameter is never used, and encodeURIComponent should be used (instead of escape).
Not sure if this is a typo or not:
result = request.executeQuery("SELECT user.login, user.email "
+ "FROM user " + );
It looks like you are missing the end of your statement.
Hmmmm, your function definition:
function sendMail("username","email") {...}
doesn't look like valid JavaScript to me, apart of that, you never call the function.
Pseudocode, how to do it:
function sendMail(username, email) {
var link = "jadajada" + email; // .... etc
}
sendMail("+username+","+email+");

Displaying struts validations message

I want to display errors detected in an action class, I use:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("some_string_in_properties_file"));`
and it works fine. However, I have written some generic error messages, and I would like to reuse them, so I am trying to do this:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("string1_in_properties_file", "string2_in_properties_file"));
where string1 = <li>{0} is required.</li>.
Then it is displaying string2 is required. It is not replacing string2 with its value.
I even tried
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("string1_in_properties_file",
new ActionMessage("string2_in_properties_file")));
then it is displaying string2[] is required. It is not replacing string2.
I know it can be done by hard-coding the value, but is there any other way?
Since you want to to fetch two key's value from Property file, and put it in global error key,
I would say, retrieve each value separately using
String sValue1 = getResources(request).getMessage(locale, "key1");
String sValue2 = getResources(request).getMessage(locale, "key2");
and then put it in your global error
errors.add(ActionErrors.GLOBAL_MESSAGE,sValue1+"<br/>"+sValue2);
Hope it help....
It's hard to tell you exactly what to do, since O don't know the code behind errors and ActionMessage. But you can, however, use String.format. Your code would look something like this
public class ActionErrors {
public static final String INVALID_INPUT "'%s' is not valid input.";
...
}
and
String input = "Cats";
String message = String.format(ActionErrors.INVALID_INPUT, input);
System.out.println(message);
The above will print
'Cats' is not valid input.
In Struts ActionMessage, you can specify value for your parameters {0}, {1}, {2}, {3} specified in your properties file, as follows:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("some_string_in_properties_file", "value1"));
Alternately:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("some_string_in_properties_file", "value1", "value2", "value3"));
value1..value3 can be of any type (as Struts expects an Object).
so your property:
string1 = <li>{0} is required.</li>
Will be replaced to:
<li>value1 is required.</li>
(If you specify your key as string1).
Let's say you have a properties file that defines some keys for messages, like so:
string1: <li>{0} is required.</li>
string2: Username
The ActionMessage class has a number of constructors that take a varying number of arguments. The first is a string representing the key that refers to a message - in your case, the key is string1 which corresponds to the message <li>{0} is required.</li>; with the {0} being a placeholder for some dynamic content.
The remaining possible arguments are Objects that represent the actual values you want to replace those placeholders. If you do new ActionMessage("string1", "string2") you're passing in the literal value string2, and you'll end up with output of <li>string2 is required.</li>.
What you need to do is replace "string2" with a method call that will get the value that corresponds to the key string2. This is where my knowledge of the problem runs out, though, so you'll need to do some research on this part for yourself.

Java -> Apache Commons StringEscapeUtils -> escapeJavaScript

For a very simple ajax name lookup, I'm sending an id from the client webpage to the server (Tomcat 5.5, Java 5), looking it up in a database and returning a string, which is assigned to a javascript variable back in the client (and then displayed).
The javascript code that receives the value is pretty standard:
//client code - javascript
xmlHttp.onreadystatechange=function() {
if (xmlHttp.readyState==4) {
var result = xmlHttp.responseText;
alert(result);
...
}
...
}
To return the string, I originally had this in the server:
//server code - java
myString = "...";
out.write(myString.getBytes("UTF-8"));
Which worked perfectly, if unsafe. Later, I replaced it with:
import org.apache.commons.lang.StringEscapeUtils;
...
myString = "...";
out.write(StringEscapeUtils.escapeJavaScript(myString).getBytes("UTF-8"));
But while safer, the resulting string can't be properly displayed if it contains special chars like "ñ".
For instance, using:
escapeJavaScript("años").getBytes("UTF-8");
sends:
an\u00F1os
to the client.
The question: is there a simple way to parse the resulting string in Javascript or is there an alternate escape function I can use in java that would prevent this issue?
The following works in every browser I've tried:
javascript:alert("a\u00F1os");
Perhaps your string is being escaped twice by mistake.
Actually, now that I read it over, I think I actually don't need to escape the string I'm sending back at all... That is, StringEscapeUtils.escapeJavaScript would be useful if the resulting value was printed in the page, like:
//javascript code with inline struts
var myJavasriptString = "<%=myJavaString%>";
Or am I missing something and there would still be a valid reason to do the escape in the original case? (when it is returned as a series of bytes back to an ajax onreadystatechange handler and assigned to a js variable)

Categories

Resources