Adding content from a database into a dropdownlist in struts2 - mysql

I am doing my project in struts2 framework. but i cant find a way to specify a dropdown list from a database.. is there a way.. pls help

If you are talking about a drop down list in your JSP page than there is already a select Tag for that
<s:select name="mydrop_down" list="%{sports}" />
where list is a Iterable source to populate from. If the list is a Map (key, value), the Map key will become the option 'value' parameter and the Map value will become the option body.
All you need to create a List/Map/Array in you action class and provide its getter and setter how the list will be picked form the ActionClass in jsp will be handled by the framewrok itself
Action Class
public class MyAction extends ActionSuport{
private List<String> sports; //can be array or map etc
getters and setters for sports
public String execute() throws Exception{
sports = init the List and fill it
// can fill the list from database
return SUCCESS;
}
}

Related

Does the business logic for deserializing a JsonPayload have to match?

I am currently attempting to deserialize a Json Payload that has been fired from a webhook URL on an MVC application, but I do not know if the business logic provided has to match exactly to prevent any null values.
Basically the Json Payload contains way to much useless information that I do not what to display. This is a brief preview of what the Payload looks like:
"webhookEvent":"jira:issue_updated",
"user":{
"self":"http://gtlserver1:8080/rest/api/2/user?username=codonoghue",
"name":"codonoghue",
"issue":{
"id":"41948",
"self":"http://gtlserver1:8080/rest/api/2/issue/41948",
"key":"OP-155",
"fields":{
"summary":"Test cc recipient",
"progress":{
"progress":0,
"total":0}, ....
I only want to display information about the issue and the other information is just white noise to me and don't want to use it. Now do I have to create classes only for the issue details etc like this:
Public Class jiraIssue
Public Property id As String
Public Property key As String
Public Property fields As jiraFields
End Class
Or do I have to make sure to provide sufficient business logic about the User class just to make sure that it will be received correctly? I also know that using Json2csharp.com the classes that can be made are user, issue, fields, progress as well as the overall RootObject, so I also want to know is do these classes need to contain the exact same matching variables as the JsonPayload, e.g. I don't want progress to have the variable total.
When using Json2csharp that in every class they contain an ID variable with the property as string and I would like to know if this is needed in the classes to be able to display the information or can I not use it as it is also irrelevant.
The main thing that I want to deserialize is the RootObject, which contains a webhookEvent (string) an issue (which links to issue class, which links to fields class which links to all relevant information), comment which links to a comment class. I want to deserialize this so would this be correct?
Public Class Rootobject
Public Property webhookEvent As String
Public Property issue As Issue
Public Property comment As Comment2
Public Property timestamp As Long
End Class
Public Class Issue
Public Property key As String
Public Property fields As Fields
End Class
Public Class Fields
Public Property issueType as IssueType
Public Property summary As String
Public Property summary As String
End Class
Dim Issue As RootObject = New System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(Of RootObject)(json)
For Each item As var In Issue.issue
Console.WriteLine("WebhookEvent: {0}, issue: {1}", item.WebhookEvent, item.issue)
Next
Update
It seems that the problems that I was having was due to the JsonPayload itself, the business logic did not affect. There were issues with the incompatible characters, some fields were null and could not be and a few others as well.
I have correctly got my Json payload correctly read in and the Json Payload information does not have to correctly match up with the classes that you create. You only have to create classes and variables for the information that you need from the Json Payload. For example if you did not want the information on comments do not create a comment class.
Public Class Rootobject
Public Property webhookEvent As String
Public Property issue As Issue
' Public Property comment As Comment2
' comment out the comment class because it is not needed
Public Property timestamp As Long
End Class

validating a JSON list as the root object with spring mvc

I need to validate a JSON list similar to the following:
[{"op":"A","path":"C","value":"B"},...]
in a Spring MVC application - I am currently deserializing (using default Jackson) to an object along the lines of:
public class Operations extends ArrayList<Operation>{}
public class Operation {
#NotEmpty
public String op;
#NotEmpty
public String path;
public Object value;
public void setOp(String op)... and other getters/setters
}
but I cannot figure out how to get jsr303 validation provided by reference hibernate implementation to fire for the attributes of Operation.
I can get it to function if I wrap the list in a class but then I have an incorrect format for the JSON, ie something like:
{"ops":[{"op":"A",...},...]}
is it possible to validate the first object (Operations)? and if not is it possible to serialize the first format (ie the JSON list) to an object of the second format (ie a list wrapped in a placeholder object with a placeholder field)
Update
Having failed to find a way to trigger the jsr303 validation on a bare ArrayList I have written a custom jackson json deserializer to stick it into a containing object with an annotated field along the lines of
#JsonDeserialize(using=OperationsDeserializer.class)
public class Operations {
#NotEmpty
private ArrayList<Operation> ops;
public void setOps(ArrayList<Operation>ops)...
public ArrayList<Operation> getOps()...
}
This works but now any autogenerated documentation for my api is generating json examples with the dummy "ops" field in it - ie {"ops" : [ ... ] }
so the search for a method of triggering jsr303 validation on an ArrayList that is not a field of another object continues - perhaps there is a way to inject a proxy wrapping class at runtime that might work around this?
Use ObjectMapper.class. it has a method which will convert Json Object into Class Object
method is , new ObjectMapper().readValue(String str, Class<T> valueType)
So you can iterate your Object array, convert to string and pass it to this method to get your result.
so it would look like,
new ObjectMapper().readValue(object.toString, Operation.class);

Combobox created dynamically from database (JSF)

I wanted to create in JSF a combobox (selectOneMenu). I want to fill this combobox with all logins from one column from Database (SELECT logins FROM database).
Will be much gratefull from any help.
In your backing bean (YourBean in the example) you should have an array of Strings (or of objects with a getter method that returns the String you want). For instance lets assume you have the following code in your backing bean:
private ArrayList<String> logins; // read from DB
private String selectedLogin; // this will hold the selected value
// this method will be called by the JSF framework to get the list
public ArrayList<String> getLogins()
{
return logins;
}
public String getSelectedLogin()
{
return selectedLogin;
}
public String setSelectedLogin(String sl)
{
selectedLogin = sl;
}
In you Facelets page, assuming you are on JSF 2.x:
<h:selectOneMenu value="#{YourBean.selectedLogin}">
<f:selectItems value="#{YourBean.logins}" itemLabel="#{l}" itemValue="#{l}" var="l"/>
</h:selectOneMenu>
This will create a select menu with all the options in the array. Once the form is submitted the value will be set in the String value of your backing bean.

Map JSON array of objects to #RequestBody List<T> using jackson

I'm having issues using Jackson to map a Javascript posted JSON array of hashes (Tag).
Here is the data received by the controller #RequestBody (It is send with correct json requestheader):
[{name=tag1}, {name=tag2}, {name=tag3}]
Here is the controller:
#RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags")
#ResponseStatus(HttpStatus.CREATED)
public void createAll(#PathVariable("purchaseId") final Long purchaseId, #RequestBody final List<Tag> entities)
{
Purchase purchase = purchaseService.getById(purchaseId);
Set<Tag> tags = purchase.getTags();
purchaseService.updatePurchase(purchase);
}
When I debug and view the 'entities' value it shows as an ArrayList of generic objects, not as a list of objects of type 'Tag' as I would expect.
How can I get jackson to map a passed array of objects to a list of obejcts of type 'Tag'?
Thanks
It sounds like Spring is not passing full type information for some reason, but rather a type-erased version, as if declaration was something like List<?> tag. I don't know what can be done to fully resolve this (may need something from Spring integration team), but one work-around is to define your own type like:
static class TagList extends ArrayList<Tag> { }
and use that instead. This will retain generic parameterization through super-type declarations so that even if Spring only passes equivalent of TagList.class, Jackson can figure out the Tag parameter.
Another way to do this is to rather obtain an array than a List, as follows:
#RequestBody Tag[] entities
Jackson requires a default constructor with no parameters on custom Objects, so you'll need to simply add a default constructor to your Tag class.
In your case simply add to your Tag class:
public Tag(){}

Struts 2 - pattern/strategy for multiple objects on the same page

I'm looking for a good design pattern/strategy for how to using the Struts 2 framework for editing multiple objects of the same type on an HTML page. Struts is really good for editing a single object, like Address. If you provider accessor methods for address1, city, state, etc, struts calls those and the standard struts UI tags will populate the form fields accordingly.
How to do this when editing multiple of the same type of object on the same page. I have a web based contest, parting of the contest is a set of rating scale objects for each contest. Each rating scale has a value and a label. If I name the input fields value_0, value_1... and label_0, label_1... then I either have to code a bunch of accessor methods (UGLY) or use the raw parameters to get the values I need. It is difficult, but not impossible, to use the struts validation methods to send error messages back to the correct form field.
If I name all the fields "Value" and "label", struts is kind enough to call a method that sets a List of input values, but I have no way of sending validation errors back to the correct output field.
I need something that doesn't require a huge number of accessor methods, allows easy access to the inputs to validate, return validation messages to the correct form field.
The strategy here is to use a Map<Integer, Address>.
Example Bean Class
Let's assume the following example Address class.
public class Address {
private String line1;
private String line2;
private String city;
private String state;
private String zipCode;
// getters and setters here
}
Example Action
public class ExampleAction extends ActionSupport {
/**
* A map of ID -> Address.
*/
private Map<Integer, Address> addresses = Maps.newLinkedHashMap();
// ... action method(s) and validate here
public Map<Integer, Address> getAddresses() {
return addresses;
}
}
In your JSP layer, you can iterate over the map (each iteration is a Map.Entry) and output the fields (line1, line2, city, etc.) for each. The field names should be:
addresses[0].line1
addresses[0].line2
addresses[0].city
addresses[0].state
addresses[0].zipCode
...
addresses[5].line1
addresses[5].line2
addresses[5].city
addresses[5].state
addresses[5].zipCode
To perform validation, just iterate over the map and check each field appropriately. When editing addresses, you can use the primary key of the address from your database. For adding new addresses, you can just increment starting from zero. The index can be any number, so long as its unique within the map.
I typically map out everything I need to use in a form and group them into related classes, Person, Address, Misc for example. I will then create a wrapper class and use delegate accessor methods to provide a single interface to access the individual objects. Most often I work with JPA entites so these classes are already set up for me, I just need the wrapper and maybe some utility methods for CRUD functions. For example:
public class ContactWrapper implements Serializable{
private Person person;
private Address address;
private Misc misc;
// Getters / Setters for primary objects - person, address, misc
...
// Delegate accessors
public String getName(){
return person.getName();
}
public String setName(String name){
return person.setName(name);
}
...
}
Now you have one object to work with in your action class and jsp's which can be references however you choose.
In your action class:
public class ContactAction extends ActionSupport{
private ContactWrapper contact;
....
}
In your JSP:
<s:textfield name="contact.name" />
Struts handles all the object instantiation auto-magically, even in objects contained inside other objects.