I am trying to post a String[] from client to Spring 3. In Controller side i have defined the method like this.
#RequestMapping(value = "somemethod", method = RequestMethod.POST)
public ModelAndView exportSomething(#RequestParam("sentences") String[] sentences) {
//.. logic
}
The data that im sending looks like this
sentences: ["a","b,c","d"]
The problem is in server side the size of the sentences array is 4. It is splitting b and c as two different words.
Is this a issue with Spring or do i need change something the way i pass on the data?
Its a know issues I guess with Spring framework. See https://jira.springsource.org/browse/SPR-7963
Try sending data in this format.
sentences:"a;b,c;d"
Note in this case your delimiter is ; not , So you have sent a string which contains a list of
#RequestMapping(value = "somemethod", method = RequestMethod.POST)
public ModelAndView exportSomething(#RequestParam("sentences") String sentences) {
String[] sentenceArray = sentences.split(";");
for(String tempString:sentenceArray){
// perform what operation you want to perform
}
}
you will get an array of size three not four in this case.
The reason why your approach is not working is probably because you have used comma which is the default delimiter for an Array.
Related
I have Spring controller with endpoint like:
#RequestMapping("/provider")
public ResponseEntity<Something> load(#ModelAttribute PageRequest pageRequest)
{
... //do something
}
where PageRequest is simple POJO:
class PageRequest
{
String[] field;
String[] value;
... // constructor getters settest
}
When I GET request like:
.../provider?field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:
field[0] = commanders;
value[0] = John
value[1] = Bill
value[2] = Alex
But when I GET request like:
.../provider?field=country&value=Australia&field=commanders&value=John%2CBill%2CAlex then pageRequestdata is mapped:
field[0] = country;
field[1] = commanders;
value[0] = Australia
value[1] = "John,Bill,Alex"
My question is why mapping is different for these requests, and can it be done for first request same as for the second. (comma %2C separated data map to single value).
used: Spring 3.x
I did some investigation and figured out that for first request value=John%2CBill%2CAlex Spring using org.springframework.format.supportDefaultFormattingConversionService class which under the hood has org.springframework.core.convert.support.StringToArrayConverter whose convert() method split your string by to array using comma as a separator.
You have 2 ways to resolve this issue:
Use ; instead of , as separator for you value (value=John;Bill;Alex)
Use different conversion service bean containing your own converter from String to String[]. For more details look at this answer
When using Spring MVC, is there a way to create two entry points by whether or not any query string has been supplied in the request.
Something like below where * is a wildcard?
#RequestMapping(value = "/page", method = RequestMethod.GET, params = {"*"})
public String getResourceWithQuery(...)
#RequestMapping(value = "/page", method = RequestMethod.GET, params = {"!*"})
public String getResourceWithoutQuery(...)
Is this possible with Spring?
Edit: To be clear, I'm not looking for a particular query parameter, I'm looking to separate the methods by the existence of any query string being present at all.
The fall back is to have one method and then check in code for query parameters and split accordingly. Having a filter method like this is messy and I'd prefer not to have to do this. Unfortunately the splitting functionality by query pattern is common in my code as it is required by the business.
One end point is enough.
You can set default value for request parameter(or query string), this will make request parameter optional.
As per java doc,
defaultValue:
public abstract String defaultValue The default value to use as a fallback > when the request parameter is not provided or has
an empty value. Supplying a default value implicitly sets required()
to false.
For example,
public String doSomething(#RequestParam(value = "name", defaultValue = "anonymous") final String name) {
Your are trying to map the request URI which having the query string or not.you are using the params in #RequestMapping which actually use for narrow the Request matching.Read below link
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#params--
.By using below code you can accept anything after ~/page/ URI.I hope this will help
#RequestMapping(value = "/page/**", method = RequestMethod.GET)
public String getResourceWithQuery(...)
I'm a NanoHttpd newbie. I'm shifting my Java EE servlet code into NanoHttpd for embedded usage. Please don't recommend other embedded servers like Jetty, I'd like to use NanoHttpd in particular.
My jQuery Javascript code looks like this:
$.ajax({
type:'POST',
url:'',
traditional: true,
data: {
'prm1':'val2',
'prm2':'val2',
'array1':['array1','array2','array3']
},
success:function(result){},
error:function(xhr,err,stat){}
});
On a servlet getting parameters would look like this:
String serverval1 = request.getParameter("prm1"); //get single value
String serverval2 = request.getParameter("prm2"); //get single value
String[] params = request.getParameterValues("array1"); //get array
On NanoHttpd I can get individual values via:
String serverval1 = ihttpsession.getParms().get("prm1"); //get single value
String serverval2 = ihttpsession.getParms().get("prm2"); //get single value
String[] params = ???
How do I get array parameters in NanoHttpd?
I figured it out after seeing a few more NanoHttpd sample codes, apparently there are many ways to get the request parameters
String serverval1 = ihttpsession.getParms().get("prm1"); //get single value
String serverval2 = ihttpsession.getParms().get("prm2"); //get single value
//get parameters as array (alternative method)
Map<String,List<String>>prms=decodeParameters(ihttpsession.getQueryParameterString());
String[] array = prms.get("array1").toArray(new String[prms.get("array1").size()]);
the later method can also be used on non array parameters but will obviously contain only one value in their respective List<String> object
Question is pretty self explanatory. I want to send 2 different arrays of objects through a POST form without ajax to my controller.
I changed my question to using ajax and using a get request due to the size of the params. Currently getting a 400 (Bad Request). I have no idea why. Please take a look...
I have objects:
var phone = {phoneId:"", phoneNumber:"", phoneType:""};
var schedule = {scheduleId:"", time:"", day:""};
Which I place into a javascript arrays:
var phones = [phone1, phone2, phone3];
var schedules = [schedule1, schedule2];
and I use ajax to send:
var data = {
index: id,
schedules: schedules,
phones: phones
}
var url = "/myController/myUrl"
$.getJSON(url, data, function(result){
if(result.ok){
$('#messageAlertSuccess').show();
} else {
$('#messageAlertError').show();
}
});
I created wrapping classes to map them like so:
public class PhoneWrapper(){
private String phoneId;
private String phoneNumber;
private String phoneType;
}
And of course the scheduleWrapper follows the same convention.
Here's the method in my controller:
#ResponseBody
#RequestMapping(value="/myUrl", method=RequestMethod.GET)
public Result doSomething(#RequestParam("index") int index,
#RequestParam("phones") Set<PhoneWrapper> phoneWrappers,
#RequestParam("schedules") Set<ScheduleWrapper> scheduleWrappers,
Model model,
HttpSession session){
//do stuff here.
}
I am currently getting a 400. So what's wrong?
Update: here's the url that the .getJSON jquery method is building:
http://localhost:8080/myApp/myController/myUrl?index=9&schedules%5B0%5D%5BscheduleId%5D=1&schedules%5B0%5D%5BfromDay%5D=Monday&schedules%5B0%5D%5BtoDay%5D=Friday&schedules%5B0%5D%5BfromTime%5D=08%3A30%3A00&schedules%5B0%5D%5BtoTime%5D=16%3A00%3A00&schedules%5B1%5D%5BscheduleId%5D=5&schedules%5B1%5D%5BfromDay%5D=Saturday&schedules%5B1%5D%5BtoDay%5D=Monday&schedules%5B1%5D%5BfromTime%5D=09%3A00%3A00&schedules%5B1%5D%5BtoTime%5D=13%3A00%3A00&phones%5B0%5D%5BphoneId%5D=6&phones%5B0%5D%5BphoneNumber%5D=787-788-1111&phones%5B0%5D%5BphoneType%5D=PHONE&phones%5B1%5D%5BphoneId%5D=106&phones%5B1%5D%5BphoneNumber%5D=787-795-4095&phones%5B1%5D%5BphoneType%5D=FAX
I see a few things that don't look right
unless you have getters and setters in your wrappers (DTO is a better name), i don't use them for my DTOs for xhr calls, you need to change
public class PhoneWrapper(){
private String phoneId;
private String phoneNumber;
private String phoneType;
}
to have public fields vs private
public class PhoneWrapper(){
public String phoneId;
public String phoneNumber;
public String phoneType;
}
Your js arrays are not arrays but objects;
var phones = {phone1, phone2, phone3};
var schedules = {schedule1, schedule2};
Here they are as arrays
var phones = [phone1, phone2, phone3];
var schedules = [schedule1, schedule2];
Make sure you naming is the same of both the js and java sides. I find it very helpful to turn on the debugging when troubleshooting these problems. log4j -
<logger name="org.springframework.web.servlet.mvc" >
<level value="debug" />
</logger>
EDIT
So after the question was updated with more info I notice that it was the same problem as Binding a list in #RequestParam
I would say that you are almost there! The first thing the you need is a wrapper to hold the two Set<> parameters since spring is not able to map a collection directly to parameters (yet?).
Also, there are two ways to handle this kind of requests:
use a json request and #Requestbody with a single javascript object in the request body an map this into a java class (automatically by spring). This means you need to change a little how the data is send down and this approach has one side effect: you cannot merge data simply by defining the parameter as a model attribute.
a second possibility is to stay with the post form submit. Also here you need to create the wrapper and use this one as a requestparam. Either one per Set<> parameter like #Sotirios mentioned in his answer or one parameter which holds both sets. Then you need to modify your submit data to send the phone and schedule information like input fields. I haven't used sets in this case but
lists and the parameter names would look like phoneWrapper[0].phoneId.
The advantage of the second approach is that you can merge the request data with existing values so you do not need to send down a complete phone information all the time.
var phones = {phone1, phone2, phone3};
var schedules = {schedule1, schedule2};
These two are not arrays (square brackets), but objects (curly brackets).
Compare with
var phones = ["phone1", "phone2", "phone3"];
var schedules = ["schedule1", "schedule2"];
and if you are to pass actual object references (phone1, phone2, phone3, schedule1 and schedule2 are object variables) then you need to use
var phones = [phone1, phone2, phone3];
var schedules = [schedule1, schedule2];
For spring the map request parameters to Class instance fields, they have to match the name of the parameter.
So with
<input type="hidden" name="someParameter" value="123"/>
and
public class SomeClass {
private String someParameter;
// getters and setters
}
a Spring controller will be able to be injected with a SomeClass instance whose field someParameter has the value 123 that comes from the html hidden input request parameter. This is also known as a command object.
A javascript array has no meaning to either html or http.
As for the solution, I would keep your class PhoneWrapper, use javascript to populate 3 <input> elements, and change the method definition to
#RequestMapping(value=MY_URL, method=RequestMethod.POST)
public String doSomething(#RequestParam("index") int index,
PhoneWrappers phoneWrappers,
ScheduleWrappers scheduleWrappers,
Model model,
HttpSession session){
Notice there are no more array [] brackets. (You would do the same for ScheduleWrappers).
My requirement is as follows:
I want to give actor name, start date, end date and get all the films he acted in that period.
For that reason, my service request is like this.
http://localhost:8080/MovieDB/GetJson?name=Actor&startDate=20120101&endDate=20120505
Now, i want to improve it.
I want to give a start date, end date and more than one actor name and want to see all those actors movies in that period.
I am not sure how should my url look to support such thing.
I am writing a java based web service using spring.
Below code is to support one actor
#RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(#RequestParam("name") String ticker, #RequestParam("startDate") String startDate, #RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
One solution i am thinking is using a % symbol to seperate actor names. For example:
http://localhost:8080/MovieDB/GetJson?name=Actor1%Actor2%Actor3&startDate=20120101&endDate=20120505
Now, in the controller i will parse the name string with % and get back all actors names.
Is this a good way to do this or is there a standard approach?
Thanks
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
#RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(#RequestParam("name") String[] ticker, #RequestParam("startDate") String startDate, #RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}