Can I submit a field value as an array with extjs? - java

On my form I have a textarea which calls for a list of words. e.g. word1,word2,word3 etc. The user can put as many words as they wish. My application gets this entry back as a single string, "word1,word2,word3" and to convert it to an array I have to do myString.split(",").
I was wondering if it is possible to set up the form so that extjs knows it should convert this to an array when it submits the data? Something like:
var myField = {
xtype : 'textarea',
fieldLabel : 'Words',
name : 'words',
type: 'array'
}
edit: I'd also be happy with having some kind of onSubmit function that sets the value of the field to an array client side before it is sent

Assuming you use extjs 4 and higher I would suggest the following:
Override Ext.form.field.TextArea field and implement it's getModelData( ) function to be something like this:
getModelData: function() {
var me = this,
data = null;
if (!me.disabled && !me.isFileUpload()) {
data = {};
data[me.getName()] = me.getValue().split(",");
}
return data;
}
This will allow Ext to properly interpret your field's model value as a string array. Then the model of your form will contain proper array for your field.
You may call getFieldValues() for your basic form to return corresponding json to send it to server, or you may use Ext MVC functions to work with form's model.

Related

Reading POST Ajax array parameters in NanoHttpd

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

Design for large scale parameter validation for JPA?

I have a method that takes in a JSON and takes out the data and distributes it to various strings so that they can be set in an entity and persisted. My example below is quite simple but for my actual code I have about 20+ fields
For example see
public Projects createProject(JsonObject jsonInst) {
Projects projectInst = new Projects();
String pId = jsonInst.get("proId").getAsString();
String pName = jsonInst.get("proName").getAsString();
String pStatus = jsonInst.get("proStatus").getAsString();
String pCustId = jsonInst.get("proCustId").getAsString();
String pStartDate = jsonInst.get("proStartDate").getAsString();
...
//Set the entity data
projectInst.setProjectId(pId);
projectInst.setProjectName(pName);
...
Notice if a varible dosent have a corrosponding entry in the Json this code will break with null pointer exception. Obviously I need to validate each parameter befopre calling .getAsString()
What is the best way to do this from a readability point of view I could create 2 varibles for each parameter and check and set for example.
if(jsonInst.get("proName")){
String pName = jsonInst.get("proName").getAsString();
}
Or should I wait for it to be set
if(!pName.isEmpty()){
projectInst.setName(pName)
}
...
Which of these do you think is the best parameter to use for preventing errors.
Is there a way to handle if something is set on a large scale so that I can reduce the amount of code I have to write before I use that varible?
You can create a method that will take field name as parameter and will return json value for that field :
private String getJSONData(String field,JsonObject json){
String data=null;
if(json.has(field)){
data=json.get(field).getAsString();
}
return data;
}
you can call this method for each of your field:
String pId = getJSONData("proId",jsonInst);
By this way you can not only escape NullPointerException, but also avoid code repetition.

Solr: Introduce a custom field in solr query response

Is it possible to introduce a custom field in Solr QueryResponse that would contain a value that is computed based on another response value? For example if I have "score" field in the response, I want my custom field (let it be named "multipliedScore") to contain value = (score * 10);
The value of the custom field needs to be calculated (not static).
Maybe there's a way to take the score value calculated by Solr and multiply it or turn into a string with prefix/postfix (not asking here about turning it into percentages)?
You can achieve this using a DocTransformer . Just inherit from the class and implement the required logic in the transform method :
public void transform(SolrDocument doc, int docId) {
String oldValue = doc.getFieldValue(fieldName);
doc.put(newField,getNewValue(oldValue));
}

how to get dynamic values from posting a form in the Spring controller

I am creating a form dynamically, and I need to post it and get the values in SpringController
for(var i=0;i<datArray.length;i++){
element[i] = document.createElement("input");
element[i].setAttribute("type", "text");
element[i].setAttribute("name", "text");
element[i].setAttribute("placeholder",datArray[i]);
element[i].setAttribute("id", datArray[i]+"id");
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element[i]);
}
About Pic - this is my dynamic form drawn in Select onChange
On Every dropdown Changed I am generating different text boxes dynamically. I need to post the dynamic text boxes and get the values in the Controller Spring in JAVA.
How to get dynamically posted Values in controller?
Any Idea?
Are you always sending the same model Object? I mean, does your form element always has the same name attribute?
if yes, you can just create a pojo class with attributes maching your names and use a RequestAttribute annotation.
If no, there is no way, you will just have to use the old requestparameter.
UPDATE
If you dont know what parameters are submitted, loop into all parameters :
List<String> requestParameterNames = Collections.list((Enumeration<String>) request.getParameterNames());
for (String parameterName : requestParameterNames) {
String attributeName = parameterName;
String attributeValue = request.getParameter(parameterName);
//DO YOUR STUFF
}
//DO YOUR STUFF

sending javascript object arrays as parameters to controller

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).

Categories

Resources