My html page sends only one parameter. I need to handle it and send a response. This code handles more than one parameter and in my case is not so good:
Enumeration<?> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
}
But how I can modify this code if I have only one parameter and do not know its name.
Thanks!
Try something like this.
Map<String,String[]> paramMap = request.getParameterMap();
String myValue = paramMap.get(paramMap.keySet().iterator().next())[0];
Related
I have a code which gets a body POST from Postman:
#RequestMapping(value="/dep", method=RequestMethod.POST)
public JsonResponse dep(#RequestBody String body) throws SQLException {
Connection connection = ConnectionSingleton.getInstance().getConnection(env);
Statement statement = connection.createStatement();
statement.close();
connection.close();
System.out.println("BODY #### "+body);
return new JsonResponse("depreciated");
}
Postman sent:
{
"idn":"MLCM00292",
"monto":"9149.92"
}
And the string is like:
%7B%0A%09%22idn%22%3A%22MLCM00292%22%2C%0A%09%22monto%22%3A%229149.92%22%0A%7D=
The words in bold are the parameters and their assigned values. I want to receive the parameters like variable. What its the correct way to get the params from a body in a POST request? What is missing in my code?
You can use a Map like this:
public JsonResponse dep(#RequestBody Map<String, String> body)
and then inside the method get the values like this:
String id = body.get("idn");
String monto = body.get("monto");
You can change the generics type for the Map class as it fits your needs. For example, if you are going to receive values of different types you can use it like Map<String, Object> body, then you could parse every value according to the data type (which you must know in advance). Something like:
String id = body.get("idn").toString();
double monto = Double.parseDouble(body.get("monto").toString());
For more complex data type I recommend you to create some custom POJOs or JavaBeans.
Further readings
Difference between DTO, VO, POJO, JavaBeans?
Let's say I have a page which lists things and has various filters for that list in a sidebar. As an example, consider this page on ebuyer.com, which looks like this:
Those filters on the left are controlled by query string parameters, and the link to remove one of those filters contains the URL of the current page but without that one query string parameter in it.
Is there a way in JSP of easily constructing that "remove" link? I.e., is there a quick way to reproduce the current URL, but with a single query string parameter removed, or do I have to manually rebuild the URL by reading the query string parameters, adding them to the base URL, and skipping the one that I want to leave out?
My current plan is to make something like the following method available as a custom EL function:
public String removeQueryStringParameter(
HttpServletRequest request,
String paramName,
String paramValue) throws UnsupportedEncodingException {
StringBuilder url = new StringBuilder(request.getRequestURI());
boolean first = true;
for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
String key = param.getKey();
String encodedKey = URLEncoder.encode(key, "UTF-8");
for (String value : param.getValue()) {
if (key.equals(paramName) && value.equals(paramValue)) {
continue;
}
if (first) {
url.append('?');
first = false;
} else {
url.append('&');
}
url.append(encodedKey);
url.append('=');
url.append(URLEncoder.encode(value, "UTF-8"));
}
}
return url.toString();
}
But is there a better way?
The better way is to use UrlEncodedQueryString.
UrlEncodedQueryString can be used to set, append or remove parameters
from a query string:
URI uri = new URI("/forum/article.jsp?id=2¶=4");
UrlEncodedQueryString queryString = UrlEncodedQueryString.parse(uri);
queryString.set("id", 3);
queryString.remove("para");
System.out.println(queryString);
I'm trying to get param values passed to a Java Servlet but the string returned is not correct. I'm storing the values in a Map and checking if the key exists.
Map params;
params = request.getParameterMap();
String id = params.get("id").toString();
String data = params.get("data").toString();
System.out.println("streaming" + data + " with id of " + id);
Yet if I call this servlet via http://localhost:8080/Serv/stream/data?data=hereisdata&id=you my output looks like this:
streaming[Ljava.lang.String;#5e2091d3 with id of [Ljava.lang.String;#36314ab8
What am I missing?
EDIT: as the suggested answers are not working, I'm including the entire class as I'm likely messing something up within the class:
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import Engine.Streamer;
public class AnalyzerController {
private Map params;
private String pathInfo;
private HttpServletRequest request;
public AnalyzerController(HttpServletRequest request)
{
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
public void processRequest()
{
System.out.println("procing with " + pathInfo);
switch(pathInfo){
case "/stream/data":
if(params.containsKey("id") && params.containsKey("data")) processStream();
break;
}
}
private void processStream()
{
System.out.println("we are told to stream");
String data = request.getParameter("data");
String id = request.getParameter("id");
Streamer stream = new Streamer();
stream.streamInput(data, "Analyzer", id);
}
}
This line specifically is throwing the NPE: String data = request.getParameter("data");
If you look at the docs of the Request#getParameterMap(), it returns a Map of the type Map<String, String[]>. Therefore, you need to take out the first element from the value String[] array returned from the map.
String id = params.get("id")[0];
Ofcourse, you can avoid all this and directly get the parameters from the request objects using the Request#getParameter() method.
String id = request.getParameter("id");
Edit: Looking at your class code, it seems that the instance variable request is not initialized. Initialize that in the constructor like this:
public AnalyzerController(HttpServletRequest request)
{
this.request = request; // Initialize your instance variable request which is used in the other methods.
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
You can get the required parameters instead of the whole map
String id = request.getParameter("id");
String data = request.getParameter("data");
Try something like this.
String data = ((String)params.get("data"));
Or directly from the Request.
String data = request.getParameter("data");
You can use request object plus it's method for to get data usinggetParameter() of you can use getParameterValues() if multiple data are from page.
String id = request.getParameter("id")
String data = request.getParameter("data")
why are you using Map ?
Any special need of it or any reason ?
or you can use like this :
String id = params.get("id")[0];
I have capture the current URL on the page.
using :
String url = driver.getCurrentUrl();
Now I want a specific text inside this string. Let say
String url = http://www.youtube.com/watch?v=R5-gtsdenpE
and I want
Capture and store the current page URL in String URL. (Done)
Capture the text in the URL after "v" and store it in String emb. (??)
I am using JAVA to write my scripts on Ubuntu.
Use:
String fullURL = http://www.youtube.com/watch?v=R5-gtsdenpE;
String emb = fullURL.split("\\?v=")[1];
This is what you want I guess-
String string = "http://www.youtube.com/watch?v=R5-gtsdenpE";
URL url = new URL(string);
System.out.println(url.getQuery());
Handle the exception appropriately.
In case you don't want to use URL class, just search for the first index of ? and then use substring() to get the string after that.
System.out.println(string.substring(string.indexOf("?")+1));
Url url = new Url(driver.getCurrentUrl());
Map<String, String[]> params = parameterMapFromString(url.getQuery());
String v = params.get("v")[0];
If you are requirement is static and you are sure that you have to get the value after "v" than you can try this also
String emb = url.substring(url.indexOf("v"), url.length()).trim();
It's absolutely strange, but I can't find any Java/Android URL parser that will be compatible to return full list of parameters.
I've found java.net.URL and android.net.Uri but they are can't return parameters collection.
I want to pass url string, e.g.
String url = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";
SomeBestUrlParser parser = new SomeBestUrlParser(url);
String[] parameters = parser.getParameterNames();
// should prints array with following elements
// AWSAccessKeyId, Policy, Signature, key, Content-Type, acl, success_action_status
Does anyone know ready solution?
There is way to get collection of all parameter names.
String url = "http://domain.com/page?parameter1=value1¶meter2=value2";
List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url));
for (NameValuePair p : parameters) {
System.out.println(p.getName());
System.out.println(p.getValue());
}
This static method builds map of parameters from given URL
private Map<String, String> extractParamsFromURL(final String url) throws URISyntaxException {
return new HashMap<String, String>() {{
for(NameValuePair p : URLEncodedUtils.parse(new URI(url), "UTF-8"))
put(p.getName(), p.getValue());
}};
}
usage
extractParamsFromURL(url).get("key")
Have a look at URLEncodedUtils
UrlQuerySanitizer added in API level 1
UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(url_string);
List<UrlQuerySanitizer.ParameterValuePair> list = sanitizer.getParameterList();
for (UrlQuerySanitizer.ParameterValuePair pair : list) {
System.out.println(pair.mParameter);
System.out.println(pair.mValue);
}
The urllib library will parse the query string parameters and allow you to access the params as either a list or a map. Use the list if there might be duplicate keys, otherwise the map is pretty handy.
Given this snippet:
String raw = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";
Url url = Url.parse(raw);
System.out.println(url.query().asMap());
for (KeyValue param : url.query().params()) {
System.out.println(param.key() + "=" + param.value());
}
The output is:
{Policy=456, success_action_status=201, Signature=789, AWSAccessKeyId=123, acl=public-read, key=asdasd, Content-Type=text/plain}
AWSAccessKeyId=123
Policy=456
Signature=789
key=asdasd
Content-Type=text/plain
acl=public-read
success_action_status=201