Remove first object from json response #ResponseBody - java

In my test application I have a controller with the following method:
#RequestMapping(value = "/{city}", method = RequestMethod.GET)
public #ResponseBody
MyAnwser getAnwser(#PathVariable String city) {
return new MyAnwser(city);
}
which returns the following
{"result":{"valueA":"valueB"}}
I'm looking for a way to remove the first object sign from the response - "{" to get:
"result":{"valueA":"valueB"}
but I can't figure out a way to do it while using #ResponseBody

If you do that, you wouldn't end up with a valid JSON! In other words, you can't mustn't do that.

As you want to Remove First And Last Character of your Received String Then use
String str="your Received String goes here";
str=str.substring(1, str.length()-1)

Related

#RequestParam name includes square brackets []

I am writing a feign client to consume an endpoint of a PHP API.
I need to call an endpoint which is like :
www.myapp.com/number.php?number[]=1
My Feign Client looks like this:
#FeignClient(name = "testProxy", url = "${service.url}")
public interface NumberProxy {
#RequestMapping(value = INumber.URL, method = RequestMethod.GET)
public String getEvents(#RequestParam("numbers[]") Integer number);
}
The problems is number[].
If I see the feign log to check the GET URL, this is what I see.
GET [https://www.myapp.com/number.php?number[]={number[]}][1] HTTP/1.1
The number[] is not replaced by the actual value and that is what the API call is failing.
Is there a way to deal with this?
P.S.
I know that the PHP API should not have a query parameter like this, but it is what it is and I can not change that.
And I have also tried with List<Integer> for the number variable, but output is same.
Are we talking about a org.springframework.web.bind.annotation.RequestParam if so it shouldn't be the problem of square brackets. For me it works fine:
#RequestMapping(value = "/api/somepath", method = RequestMethod.POST)
public void uploadData(
#RequestPart("file") MultipartFile fileUpload, HttpServletRequest request,
HttpServletResponse response, #RequestParam(name = "param[]") Integer number) {
LOGGER.trace("paramValue=[{}]", number)
}
logs a value passed through a client
What if the problem is in parameter naming? In the first occurence you write numberS[] but further it named as number[]
You should name your parameter just as numbers without the brackets and change the type to a List:
#RequestMapping(value = INumber.URL, method = RequestMethod.GET)
public String getEvents(#RequestParam("numbers") List<Integer> number);

Spring #RequestMapping handling of special characters

I have a REST API like this:
#RequestMapping(value = "/services/produce/{_id}", method = RequestMethod.PATCH,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String patchObject(#RequestBody PatchObjectRequest obj,
#PathVariable("_id") String id) {
// some code
}
My problem is that the id that might be given is in the form:
US%2FCA%2FSF%2FPlastic
Which is a URL encoding of "US/CA/SF/Plastic".
My problem is that when a % character is put into the URL the #RequestMapping does not map it to this method and it will return a 404. Is there a way to accept ids that have % character in them as part of the URL?
You are receiving this error because using it as path variable it is decoded and then server tries to match it to a path that doesn't exits. Similar questions where posted a few years ago: How to match a Spring #RequestMapping having a #pathVariable containing "/"?, urlencoded Forward slash is breaking URL.
A good option for you would be to change _id from #PathVariable to #RequestParam and problem solved, and remove it from path.
Hope you can add regex in the path variable like:
#RequestMapping(value = "/services/produce/{_id:.+}",
method = RequestMethod.PATCH,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)

Spring REST Controller understanding arrays of strings when having special characters like blank spaces or commas

I am trying to write a Spring REST Controller getting an array of strings as input parameter of a HTTP GET request.
The problem arises when in the GET request, in some of the strings of the array, I use special characters like commas ,, blank spaces or forward slash /, no matter if I URL encode the query part of the URL HTTP GET request.
That means that the string "1/4 cup ricotta, yogurt" (edit which needs to be considered as a unique ingredient contained as a string element of the input array) in either this format:
http://127.0.0.1:8080/[...]/parseThis?[...]&ingredients=1/4 cup ricotta, yogurt
This format (please note the blank spaces encoded as + plus, rather than the hex code):
http://127.0.0.1:8080/[...]/parseThis?[...]&ingredients=1%2F4+cup+ricotta%2C+yogurt
Or this format (please note the blank space encoded as hex code %20):
http://127.0.0.1:8080/[...]/parseThis?[...]&ingredients=1%2F4%20cup%20ricotta%2C%20yogurt
is not rendered properly.
The system does not recognize the input string as one single element of the array.
In the 2nd and 3rd case the system splits the input string on the comma and returns an array of 2 elements rather than 1 element. I am expecting 1 element here.
The relevant code for the controller is:
#RequestMapping(
value = "/parseThis",
params = {
"language",
"ingredients"
}, method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public HttpEntity<CustomOutputObject> parseThis(
#RequestParam String language,
#RequestParam String[] ingredients){
try {
CustomOutputObject responseFullData = parsingService.parseThis(ingredients, language);
return new ResponseEntity<>(responseFullData, HttpStatus.OK);
} catch (Exception e) {
// TODO
}
}
I need to perform HTTP GET request against this Spring controller, that's a requirement (so no HTTP POST can be used here).
Edit 1:
If I add HttpServletRequest request to the signature of the method in the controller, then I add a log statement like log.debug("The query string is: '" + request.getQueryString() + "'"); then I am seeing in the log a line like The query string is: '&language=en&ingredients=1%2F4+cup+ricotta%2C+yogurt' (So still URL encoded).
Edit 2:
On the other hand if I add WebRequest request to the signature of the method, the the log as log.debug("The query string is: '" + request.getParameter("ingredients") + "'"); then I am getting a string in the log as The query string is: '1/4 cup ricotta, yogurt' (So URL decoded).
I am using Apache Tomcat as a server.
Is there any filter or something I need to add/review to the Spring/webapp configuration files?
Edit 3:
The main problem is in the interpretation of a comma:
#ResponseBody
#RequestMapping(value="test", method=RequestMethod.GET)
public String renderTest(#RequestParam("test") String[] test) {
return test.length + ": " + Arrays.toString(test);
// /app/test?test=foo,bar => 2: [foo, bar]
// /app/test?test=foo,bar&test=baz => 2: [foo,bar, baz]
}
Can this behavior be prevented?
The path of a request parameter to your method argument goes through parameter value extraction and then parameter value conversion. Now what happens is:
Extraction:
The parameter is extracted as a single String value. This is probably to allow simple attributes to be passed as simple string values for later value conversion.
Conversion:
Spring uses ConversionService for the value conversion. In its default setup StringToArrayConverter is used, which unfortunately handles the string as comma delimited list.
What to do:
You are pretty much screwed with the way Spring handles single valued request parameters. So I would do the binding manually:
// Method annotations
public HttpEntity<CustomOutputObject> handlerMethod(WebRequest request) {
String[] ingredients = request.getParameterValues("ingredients");
// Do other stuff
}
You can also check what Spring guys have to say about this.. and the related SO question.
Well, you could register a custom conversion service (from this SO answer), but that seems like a lot of work. :) If it were me, I would ignore the declaration the #RequestParam in the method signature and parse the value using the incoming request object.
May I suggest you try the following format:
ingredients=egg&ingredients=milk&ingredients=butter
Appending &ingredients to the end will handle the case where the array only has a single value.
ingredients=egg&ingredients=milk&ingredients=butter&ingredients
ingredients=milk,skimmed&ingredients
The extra entry would need to be removed from the array, using a List<String> would make this easier.
Alternatively if you are trying to implement a REST controller to pipe straight into a database with spring-data-jpa, you should take a look at spring-data-rest. Here is an example.
You basically annotate your repository with #RepositoryRestResource and spring does the rest :)
A solution from here
public String get(WebRequest req) {
String[] ingredients = req.getParameterValues("ingredients");
for(String ingredient:ingredients ) {
System.out.println(ingredient);
}
...
}
This works for the case when you have a single ingredient containing commas

Spring Controller: Passing Url As Parameter 404 Error

My controller attaches a question mark at the end of a string. It works great for every types of string.
https://www.mywebsite.com/attachQuestionmark/33 returns 33?
https://www.mywebsite.com/attachQuestionmark/hello returns hello?
However it returns not found error for urls such as https:://www.test.com.
https://www.mywebsite.com/attachQuestionmark/https:://www.test.com returns 404 error.
Is there any way to pass a full url to spring mvc controller?
#RequestMapping(
value = MyUrlBuilder.API_CREATIVE_CREATE + "/attachQuestionmark/{string}",
method = RequestMethod.GET,
produces = MediaType.ALL_VALUE)
#ResponseBody
#PMET
public static String attachQustionmark(#PathVariable("url") String value)
{
return value + "?";
}
Try URL-encoding the path variable, eg:
https://www.mywebsite.com/attachQuestionmark/https%3A%3A%2F%2Fwww.test.com
Because otherwise the / inside the variable will be interpreted as another path

how to hide the key in url,but not the values using Get method in Spring

I am getting the Model Attribute Object's, Key and value pair in the url,I have to hide those key-value pair or else it should be values alone.
Ex:consider the following url,
http://localhost:8080/Sample/showPage.htm?
name=ram&std=II&sec=A
&Search=Get
this name,std and sec forms the model attribute object 'StudentDetails' pojo class,I want the url like below:
http://localhost:8080/Sample/showPage.htm?
ram/II/A/Get
In the Controller, assuming that you have a method call showPage
Use the following,
#RequestMapping(value = "/{name}/{std}/{sec}/{Search}", method = RequestMethod.GET)
public String showPage(#PathVariable("name") String name,#PathVariable("std") String std,
#PathVariable("sec") String sec,#PathVariable("Search") String Search) throws Exception {
// use the values name, std, sec and search as you need.
}

Categories