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];
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?
I have a member function that will retrieve all membershipId of a member(one member might have multiples of membershipId).After retrieve all membershipId using List,it will call the url like this.
This is my service:
RestRequest request = RestRequest.newBuilder()
.url("/membership/" + membershipId + "/outlet")
.get();
This is my controller:
#RequestMapping(value = "/favouriteStores", method = RequestMethod.GET)
public Object FavouriteStores(ModelMap modelMap,HttpSession session)throws Exception {
String memberId = "5677a7075e3f1b998fc7483b";
List<Membership> membershipList= memberService.getMembershipByMemberId(memberId);
List<String> membershipIds = membershipList.stream().map(m->m.getId()).collect(Collectors.toList());
String membershipId = membershipIds.toString();
Set<Outlet> outletSet = membershipService.getOutletByMembershipId(membershipId);
My problem is it will transform the whole membershipId in one url like this
"membership/[12345, 54321]/outlet"
It should be two url like "membership/[12345]/outlet" and "membership/[54321]/outlet"
I know we can use foreach to do that in controller,but i don't know how.Thanks for any helps.
Try map method of Stream instead :
You can achieve this using map method of Stream.
Set<Outlet> outletSet = membershipIds.stream()
.map(membershipService::getOutletByMembershipId)
.collect(Collectors.toSet());
Even you can combine your previous stream operations and omit creation of intermediate list objects :
String memberId = "5677a7075e3f1b998fc7483b";
Set<Outlet> outletSet = memberService.getMembershipByMemberId(memberId)
.stream()
.map(Membership::getId)
.map(membershipService::getOutletByMembershipId)
.collect(Collectors.toSet())
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);
In my application I have to extract parameters of a request and put into a collection in the order of their appearance in the querystring.
For example, if the sender makes following request,
http://myapp.com/myrequest?param3=value3¶m2=value2¶m1=value1 ,
I need to generate a collection, in which the elements are placed in this order: param3, param2, param1.
To achieve this, I first extract the names of the parameters using the method getParameterNames shown below.
private List<String> getParameterNames(HttpServletRequest aRequest)
throws IOException {
final List<String> parameterNames = new LinkedList<>();
final BufferedReader reader = aRequest.getReader();
final String queryString = IOUtils.toString(reader);
final String[] parameterValuePairs = queryString.split("&");
for (String parameterValuePair : parameterValuePairs) {
final String[] nameValueArray = parameterValuePair.split("=");
parameterNames.add(nameValueArray[0]);
}
return parameterNames;
}
The problem: After invokation of this method, aRequest.getParameterValue(...) returns null for ever parameter name.
If I do it otherwise - first save the parameter map, and then invoke getParameterNames, then its result is null.
final Map<String,String[]> parameterMap = aRequest.getParameterMap();
final List<String> parameterNames = getParameterNames(aRequest);
I tried following things:
Make sure that reader.close() is not invoked in getParameterNames (elsewhere I read that this may cause problems).
Invoke reader.reset().
None of this helped.
How can I get a list of parameter-value pairs from a HttpServletRequest, which is sorted by parameter's appearance in the querystring?
With the first approach you don't need to use Reader to get the parameters. Instead do:
final List<String> parameterNames = new LinkedList<>();
final String queryString = query.getQueryString(); // get query string from query itself
// rest of your code stays unchanged
The reason it didn't work is because data from a request input stream can be read only once.
Or, if I am wrong and that is not the case, you can save parameters and their values into a LinkedHashMap:
final LinkedHashMap<String, String> parameterValues = new LinkedHashMap<>();
final BufferedReader reader = aRequest.getReader();
final String queryString = IOUtils.toString(reader);
final String[] parameterValuePairs = queryString.split("&");
for (String parameterValuePair : parameterValuePairs) {
final String[] nameValueArray = parameterValuePair.split("=");
parameterValues.put(nameValueArray[0], nameValueArray[1]);
}
Now parameterValues is a map with entries sorted by the order of appearance.
I would like to parse a string which is basically a URL. I need to check simply that a parameters is passed to it or not.
so http://a.b.c/?param=1 would return true http://a.b.c/?no=1 would return false and http://a.b.c/?a=1&b=2.....¶m=2 would return true since param is set
I am guessing that it would involve some sort of regular expression.
Java has a builtin library for handling urls: Spec for URL here.
You can create a URL object from your string and extract the query part:
URL url = new URL(myString);
String query = url.getQuery();
Then make a map of the keys and values:
Map params<string, string> = new HashMap<string, string>();
String[] strParams = query.split("&");
for (String param : strParams)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
params.put(name, value);
}
Then check the param you want with params.containsKey(key);
There is probably a library out there that does all this for you though, so have a look around first.
String url = "http://a.b.c/?a=1&b=2.....¶m=2";
String key = "param";
if(url.contains("?" + key + "=") || url.contains("&" + key + "="))
return true;
else
return false;