I am a beginner in JSP programming and I would like to know which
code ( program ) I must write to get the Unicode value from queryString
Thank you very much for your help !
For getting unicode value this code may help you.
if(request.getCharacterEncoding() == null)
request.setCharacterEncoding("UTF-8");
for more information see this :
Click Here
The HttpServletRequest#getQueryString() returns an URL-encoded query string. You should rather prefer to use getParameter(), getParameterValues() or getParameterMap() methods to retrieve respectively a single parameter, multiple parameters or the entire parameter map. Using those methods, the container will automatically URL-decode the parameter names and values for you. Inside a JSP those values are available by ${param.name}, ${paramValues.name} and ${pageContext.request.parameterMap} respectively.
If you really insist in parsing and fiddling the raw query string yourself for some unobvious reason, then you have to split them on & and = to get the individual parameters and the name=value parts respectively and finally URL-decode each part yourself. Splitting can be done using String#split() and URL-decoding can be done using URLDecoder#decode().
Here's a kickoff example:
String charset = request.getCharacterEncoding();
if (charset == null) charset = "UTF-8";
String queryString = request.getQueryString();
for (String parameter : queryString.split("&")) {
String[] parts = parameter.split("=");
String name = URLDecoder.decode(parts[0], charset);
String value = URLDecoder.decode(parts[1], charset);
// ...
}
The default charset should at least be the same as you've used to return the HTTP response. For example, when it's a JSP, it should be the same as you've specified in the pageEncoding:
<%#page pageEncoding="UTF-8" %>
Related
The request parameter is like decrypt?param=5FHjiSJ6NOTmi7/+2tnnkQ==.
In the servlet, when I try to print the parameter by String param = request.getParameter("param"); I get 5FHjiSJ6NOTmi7/ 2tnnkQ==. It turns the character + into a space. How can I keep the orginal paramter or how can I properly handle the character +.
Besides, what else characters should I handle?
You have two choices
URL encode the parameter
If you have control over the generation of the URL you should choose this. If not...
Manually retrieve the parameter
If you can't change how the URL is generated (above) then you can manually retrieve the raw URL. Certain methods decode parameters for you. getParameter is one of them. On the other hand, getQueryString does not decode the String. If you have only a few parameters it shouldn't be difficult to parse the value yourself.
request.getQueryString();
//?param=5FHjiSJ6NOTmi7/+2tnnkQ==
If you want to use the '+' character in a URL you need to encode it when it is generated. For '+' the correct encoding is %2b
Use URLEncoder,URLDecoder's static methods for encoding and decoding URLs.
For example : -
Encode the URL param using
URLEncoder.encode(url,"UTF-8")
Back in the server side , decode this parameter using
URLDecoder.decode(url,"UTF-8")
decode method returns a String type of the decoded URL.
Allthough the question is some years old, I'd like to write down how I fixed the problem in my case: the download link to a file is created in a GWT page where
com.google.gwt.http.client.URL.encode(finalurl)
is used to encode the URL.
The problem was that the "+" sign a customer of us had in the filename wasn't encoded/escaped. So I had to remove the URL.encode(finalurl) and encode each parameter in the url with
URL.encodePathSegment(fileName)
I know my question is bound to GWT but it seems, URLEncoder.encode(string, encoding) should be applied to the parameter only aswell.
First, sorry for my english it's not my native language.
So, I am working on an application in JSP and in one of my forms I have a field "comments". When I submit this form, the value of this field is sent to my servlet by an ajax request.
var request = 'mainServlet?command=SendRequest';
request += ('&comments=' + $('#comments').val());
But when there is a "<" or ">" in the field, $('#comments').val() translate them into "<" or "&gl". For exemple, is converted to < ;test&gl ;
And when I want to recover the value in my servlet, I do:
String comments = request.getParameter("comments");
But the url looks like : mainServlet?command=SendRequest&comments=< ;test&gl ;
So request.getParameter("comments"); returns an empty string.
I thought that I could replace the string like < by my own code and then replace it again in my servlet, but is there a simpler way to do this?
Thanks.
Edit: After, I reuse the comments in an other jsp.
I believe what you need is the encodeURIComponent function. It will convert any string into a format that you can use inside a URI.
Just remember to decode it on the receiving end, I believe the URLDecoder class can do this for you.
I am trying to call a URL from Java code in the following way:
userId = "Ankur";
template = "HelloAnkur";
value= "ParamValue";
String urlString = "https://graph.facebook.com/" + userId + "/notifications?template=" +
template + "&href=processThis.jsp?param=" + value + "&access_token=abc123";
I have the following problems in this:
When I do println(urlString), I see that the urlString only has the value upto and before the first ampersand (&). That is, it looks as: https://graph.facebook.com/Ankur/notifications?template=HelloAnkur and rest of it all (which should have been &href=processThis.jsp?param=ParamValue&access_toke=abc123) gets cut off. Why is that and how can I get and keep the full value in urlString? Does & needs to be escaped in a Java String, and if yes, how to do it?
Notice that I am trying to pass a (relative) URL as a parameter value in this query (the value of href as processThis.jsp?param=ParamValue. How can I pass this type of value of href without mixing it up with the query of this URL (urlString), which only has three parameters template, href and access_token? That is, how can I hide or escape ? and =? Further, what would I need to do if value was Param Value (with a space)?
Notice that the template has the value HelloAnkur (with no space). But if I wanted it to have space, as in Hello Ankur, how would I do it? Should I write it as Hello%20Ankur or Hello Ankur would be fine?
I need the solution in such a way that URL url = new URL(urlString) can be created, or url can be created via URI. Please describe your answer up to this point as creating a safe URL is not straight forward in Java.
Thanks!
(this is going to become a classic)
Use URI Templates (RFC 6570). Using this implementation (disclaimer: mine), you can avoid all encoding problems altogether:
// Immutable, can be reused as many times as you wish
final URITemplate template = new URITemplate("https://graph.facebook.com/{userId}"
+ "/notifications?template={template}"
+ "&href=processThis.jsp?param={value}"
+ "&access_token=abc123");
final Map<String, VariableValue> vars = new HashMap<String, VariableValue>();
vars.put("userId", new ScalarValue("Ankur"));
vars.put("template", new ScalarValue("HelloAnkur"));
vars.put("value", new ScalarValue("ParamValue");
// Build the expanded string
final String expanded = template.expand(vars);
// Go with the string
Note that URI templates not only allow scalar values, but also arrays (the RFC calls these "lists" -- implemented as ListValue in the above) and maps (the RFC calls these "associative arrays" -- implemented as MapValue in the above).
I have a url, something like this localhost:8080/foo.action?param1=7¶m2=8¶m3=6
When this is the Url (as it is), request.getParmeter("param2") gives me 8 [Correct]
i) When the encoding converts this url to localhost:8080/foo.action?param1=7%26param2=8%26param3=6
In this case, request.getParameter("param1") gives me 7¶m2=8¶m3=6
ii) When the encoding converts this url to localhost:8080/foo.action?param1=7¶m2=8¶m3=6
In this case, request.getParameter("param1") gives me 7 and request.getParameter("param2") gives me null
What is the correct way of retrieving the parameters? [Assuming that using one of the two Url encoding schemes is unavoidable]
(I am using struts actions)
To prevent this do not encode parameters with delimeters, encode only parameters values. This will be the best way. If you cannot handle parameters encoding just do decoding on server side before parsing:
String queryString = request.getQueryString();
String decoded = URLDecoder.decode(queryString, "UTF-8");
String[] pares = decoded.split("&");
Map<String, String> parameters = new HashMap<String, String>();
for(String pare : pares) {
String[] nameAndValue = pare.split("=");
parameters.put(nameAndValue[0], nameAndValue[1]);
}
// Now you can get your parameter:
String valueOfParam2 = parameters.get("param2");
You can call req.getQueryString() to get the whole query parameters and then do server side decoding based on whatever encoding methods you choose.
Try using
String[] Parameters = = URLDecoder.decode(Request.getQueryString(), 'UTF-8').splitat('&') ;
Hope this helps.
I had this happen to me today. Turns out I was passing the encoded url over the wire. When the request is made it should be made as http://localhost/foo?bar=1&bat=2 not as http://localhost/foo?bar=1&bat=2.
In this case I had cut the url from an xml file and pasted it into a browser.
How can I encode URL query parameter values? I need to replace spaces with %20, accents, non-ASCII characters etc.
I tried to use URLEncoder but it also encodes / character and if I give a string encoded with URLEncoder to the URL constructor I get a MalformedURLException (no protocol).
URLEncoder has a very misleading name. It is according to the Javadocs used encode form parameters using MIME type application/x-www-form-urlencoded.
With this said it can be used to encode e.g., query parameters. For instance if a parameter looks like &/?# its encoded equivalent can be used as:
String url = "http://host.com/?key=" + URLEncoder.encode("&/?#");
Unless you have those special needs the URL javadocs suggests using new URI(..).toURL which performs URI encoding according to RFC2396.
The recommended way to manage the encoding and decoding of URLs is to use URI
The following sample
new URI("http", "host.com", "/path/", "key=| ?/#ä", "fragment").toURL();
produces the result http://host.com/path/?key=%7C%20?/%23ä#fragment. Note how characters such as ?&/ are not encoded.
For further information, see the posts HTTP URL Address Encoding in Java or how to encode URL to avoid special characters in java.
EDIT
Since your input is a string URL, using one of the parameterized constructor of URI will not help you. Neither can you use new URI(strUrl) directly since it doesn't quote URL parameters.
So at this stage we must use a trick to get what you want:
public URL parseUrl(String s) throws Exception {
URL u = new URL(s);
return new URI(
u.getProtocol(),
u.getAuthority(),
u.getPath(),
u.getQuery(),
u.getRef()).
toURL();
}
Before you can use this routine you have to sanitize your string to ensure it represents an absolute URL. I see two approaches to this:
Guessing. Prepend http:// to the string unless it's already present.
Construct the URI from a context using new URL(URL context, String spec)
So what you're saying is that you want to encode part of your URL but not the whole thing. Sounds to me like you'll have to break it up into parts, pass the ones that you want encoded through the encoder, and re-assemble it to get your whole URL.