How to populate a drop down using string array list - java

Struts 1.x :
How to populate a dropdown using string array list?
In the form bean (formbean) there are getter and setter methods for the list "blockIds" which is an string arraylist. For an example
ArrayList<String> blockIds = new ArrayList<String>();
blockIds.add("A");
blockIds.add("B");
What would be the jsp code which should look like the following after rendering.
<select name=“selectedItem”>
<option value=“A”>A</option>
<option value=“B”>B</option>
</select>

See like this,
public class TestAction extends Action {
public ActionForward populateDropdown(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
ArrayList<String> blockIds = new ArrayList<String>();
blockIds.add("A");
blockIds.add("B");
MyForm myForm=(MyForm)form;
myForm.setListMsg(blockIds);
return mapping.findForward("success");
}
}
And in HTML,
<html:select property="selectedItem" styleId="standard">
<html:optionsCollection name="myForm"
property="yourList" label="label" value="value" />
</html:select>
Even you can use <logic:iterate> tags for iterate.
Hope this helps

Related

How do i display object in thymeleaf

I need to display list of user i have this from controller.
#GetMapping("/maintenance-user")
public ModelAndView Index() throws Exception
{
ModelAndView model = new ModelAndView("maintenance/user/index");
model.addObject("model",service.get());
return model;
}
the service.get returns an Iterable object
And this is my view
<p th:text="${model.Id}"></p>
but it returns Property or field 'Id' cannot be found on object.
What am i missing here?
You need use th:each similar to below to iterate the list
<tr th:each="obj : ${model}">
<td th:text="${obj.Id}">Onions</td>
</tr>

Infuriating empty list in Spring form / controller

I'm trying to create a list of objects from form inputs. The objects are the same but their values may differ, it's essentially a menu.
I'm still getting to grips with Spring/Thymeleaf which is adding some level of complexity to what feels like a simple task.
I've a class for the menu, a simple POJO, there is then a list of these defined as a data member in the bean itself:
private ArrayList<GuestMenuOptions> guestMenus;
I've read many posts, tried many things and am on the verge of softly resting my head against the table.
I've had several errors, most of which either tell me that the list cannot be found or that the list is empty - it's currently in stable condition where the list, no matter what I try, will not be populated, even when I load in default values...unfortunately my debugger has died which is not helping.
Any help is appreciated. thank you
EntryController:
#RequestMapping(method=RequestMethod.GET, value="/")
public String indexPage(Model model) {
model.addAttribute("childMenuOptions", generateChildMenus());
//not sure if this is neccesary...
ArrayList<GuestMenuOptions>guestMenus = new ArrayList<>();
GuestMenuOptions ad1 = new GuestMenuOptions();
GuestMenuOptions ad2 = new GuestMenuOptions();
guestMenus.add(ad1);
guestMenus.add(ad2);
GuestContactBean ctb = new GuestContactBean();
ctb.setGuestMenus(guestMenus);
model.addAttribute("guestContactBean", ctb);
model.addAttribute("formBackingBean", new FormBackingBean());
return "index";
}
Form:
<form modelAttribute="guestBean" class="contact_form" name="rsvp" role="form" th:object="${formBackingBean}" th:action="#{/sendRsvp}" method="post">
<div class="row">
<div class="form-group">
<select name="ad1Starter" id="starterMealAdult1">
<option value="!!!">-Starter-</option>
<option th:field="${guestContactBean.guestMenus[0].starter}" th:each="entry : ${adultMenuOptions.get('starter').entrySet()}" th:value="${entry.key}" th:text="${entry.value}">
</option>
</select>
</div>
<input type="submit"guest name="submit" class="btn default-btn btn-block" value="Send RSVP">
RequestController:
#RequestMapping(value = "/sendRsvp", method = RequestMethod.POST)
public String sendRsvp(#ModelAttribute("guestContactBean") GuestContactBean guestContactBean,
#ModelAttribute("guestMenus") ArrayList<GuestMenuOptions>menus,
BindingResult result) throws MessagingException {
smtpMailSender.send(guestContactBean);
return "thanksMessage";
}
Beans:
FormBacking is POJO with no reference to the menus at all.
GuestMenuOptions is the same with just starter, desert members
guestContactbean has not much more going on, basic fields with the addition of the list of GuestMenuOptions
private String numberOfAdults;
private String eventAttending;
private ArrayList<GuestMenuOptions> guestMenus;
public ArrayList<GuestMenuOptions> getGuestMenus() {
return guestMenus;
}
EDIT:
The field that populates the drop downs in working fine, it's declared as private Map<String, Map<String, String>> adultMenuOptions;
private Map<String, Map<String, String>> childMenuOptions;
they are then built in the controller so that each may have several options under 'starter', 'main' and desert' for example:
starter.put("salmon", "Smoked Salmon");
starter.put("pate", "Chicken Liver Pate");
this is then populating both the value and text of the dropdown.
If I could save the state of this Map and pass it back to the controller instead, that would also be fine but I wasn't able to why then spawned the creation of the there wrapper list.
Please revisit http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dropdownlist-selectors. It should be as simple as
class Animal {
int id;
String name;
}
then in your template:
<select th:field="*{animalId}">
<option th:each="animal : ${animals}"
th:value="${animal.id}"
th:text="${animal.name}">Wireframe</option>
</select>
I think your code is all over the place and you're mixing up menu selection with menu item types.

using an attribute of an arraylist in my jsp with struts-bean.tld

I have an issue using an attribute of an arraylist in my jsp.
The arraylist in my ActionForm :
private ArrayList<Account> accounts = new ArrayList<Account>();
The class declaration of the Account object in the Arraylist :
public class Account implements Serializable, Cloneable {
private String bic;
public String getBic() {
return bic;
}
public void setBic(final String newBic) {
bic = newBic;
}
}
The call in my jsp :
<bean:write name="BankAccountsActionForm"
property="accounts.get(0).bic" />
The console error :
javax.servlet.jsp.JspException: No getter method for property accounts.get(0).bic of bean BankAccountsActionForm
Do you have a solution or another way to do this?
I have a terrible alternative using a property accountbic1 directly in the form. But it induces lots of work behind to re affect all the temporary attributes to the real ArrayList.
If you have a collection of items in Struts 1.x, then use the <logic:iterate> tag.
Add the struts-logic.tld taglig on top of your JSP as follows:
<%# taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
Then, using <logic:present> and <logic:iterate> you can iterate your ArrayList as follows:
<logic:present name="accounts">
<logic:iterate id="account" name="accounts">
<bean:write name="account.bic" />
</logic:iterate>
</logic:present>
If you want to iterate a collection and access a particular index, use the indexId on <logic:iterate> like so:
<logic:present name="accounts">
<logic:iterate id="account" name="accounts" indexId="index">
<logic:equal name="index" value="0">
<bean:write name="account.bic" />
</logic:equal>
</logic:iterate>
</logic:present>
The same can be done using JSTL:
<logic:present name="accounts">
<logic:iterate id="account" name="accounts" indexId="index">
<c:if test="${index == 0}">
<bean:write name="account.bic" />
</c:if>
</logic:iterate>
</logic:present>
Make sure that Account class has a getter/setter method for attribute bic.
This is simply the error of getter and setter method. recode your getter and setter according to POJO standard as shown below:
Remove final from setter method and change your setter and getter method name as per POJO standard as shown below :
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
try some thing like:
<bean:write name="BankAccountsActionForm" property="accounts.get(1).bic" />
As it is a ArrayList not Array.
Make sure you have getter setter for accounts in in action class ** BankAccountsActionForm **
public List getAccounts ();
public void setAccounts(List acc);
Change your setter and getter method name as per POJO standard as shown below :
public String getBic() {
return bic;
}
public void setBic(final String newBic)
{ bic = newBic; }
It will work fine
remove final from setter method and try again and write it as follows
public void setBic(String bic )
{ this.bic = bic ; }

Spring 3 MVC capability for JSTL jsp option group label

I am a newbie to Spring and I want to create "option group select" But I am unable to do this.
I want an output as following but in HTML type saying
<select name="..." value"...">
<optgroup label="Category 1">
<option ... />
<option ... />
</optgroup>
<optgroup label="Category 2">
<option ... />
<option ... />
</optgroup>
</select>
General
movies
hobbies
Games
football
basketball
Images
officePics
familyPics
PresntationPics
RingTones
pop
classical
jazz
jsp code
Edited : Correct one
<form:select multiple="single" path="servicemodule" id="servicemodule">
<form:option value="None" label="--Select--" />
<c:forEach var="service" items="${servicemodule}">
<optgroup label="${service.key}">
<form:options items="${service.value}"/>
</optgroup>
</c:forEach>
</form:select>
Controller code :
There are 4 main categories and under each of these there can be many subCategories. These can be retrieved from getServiceModuleList method. But I am not getting idea where to implement the loop to store different subcategories under their respective main category.
#Autowired
private ServiceModule servicemodule;
Edited: Correct #ModelAttribute
#ModelAttribute("servicemodule")
public Map<String,List<String>> populateService() {
String[][] mainCategory = new String[7][2];
mainCategory[0][0]= "General"; mainCategory[0][1]= "general1234";
mainCategory[1][0]= "Games"; mainCategory[1][1]= "games1234";
mainCategory[2][0]= "Images"; mainCategory[2][1]= "images1234";
mainCategory[3][0]= "Ringtones"; mainCategory[3][1]= "ringtone1234";
Map<String,List<String>> serviceModule=
new LinkedHashMap<String,List<String>>();
List<String> subCategory=new ArrayList<String>();
List<ServicesPojo> services=
servicemodule.getServiceModuleList("1",mainCategory[0][1],"0");
for(ServicesPojo serviceName: services)
{
subCategory.add(serviceName.getServiceName().trim());
}
serviceModule.put(scats[0][0],subService);
return serviceModule;
}
Edited: Got the Answer for Loop
for(int i=0;i<mainCategory.length;i=i+2){
List<String> subCategory=new ArrayList<String>();
List<ServicesPojo> services=
servicemodule.getServiceModuleList("1",mainCategory[0][i],"0");
for(ServicesPojo serviceName: services)
{
subCategory.add(serviceName.getServiceName().trim());
}
serviceModule.put(mainCategory[i][0],subCategory);
}
Model
This has the main error whether I should keep only String or List Confused!!
Edited: Now Corrected one
private List<String> servicemodule;
public List<String> getServicemodule() {
return servicemodule;
}
public void setServicemodule(List<String> servicemodule) {
this.servicemodule = servicemodule;
}
Error Description
org.springframework.beans.NotReadablePropertyException:
Invalid property 'serviceModule' of bean class
[springx.practise.model.SiteModel]: Bean property 'serviceModule'
is not readable or has an invalid getter method:
Does the return type of the getter match the parameter type of the setter?
Solved!!
Watch you case: servicemodule != serviceModule.
The <c:foreEach> loop isn't correct either: it uses itemGroup both for var and varStatus, and itemGroup is never used inside the loop. Instead, serviceModule is used, but is not defined anywhere.
And I have a hard time understanding your code, one of the reasons being that you use the same name for very different things and don't pluralize attributes of type List.
private ServiceModule servicemodule;
...
Map<String,List<String>> serviceModule
...
private List<String> servicemodule;
...
<form:select multiple="single" path="serviceModule" id="serviceModule">
...
<c:forEach var="itemGroup" items="${servicesModule}" varStatus="itemGroup">
No wonder you lost yourself.

Struts getting values from checkbox

I am having a struts app with a jsp page that populates check boxes from collection as below
UserDetails.java
public class UserDetails extends ActionForm
{
private Collection userSkills;
.
//Getters and Setters for userSkills
.
.
.
public void reset(ActionMapping mapping, HttpServletRequest request)
{
userSkills = new ArrayList();
userSkills.add(new LabelValueBean("java", "Java"));
userSkills.add(new LabelValueBean("mysql", "MySQL"));
userSkills.add(new LabelValueBean("php", "PHP"));
userSkills.add(new LabelValueBean("css", "CSS"));
userSkills.add(new LabelValueBean("html", "Html"));
}
}
I am Populating the JSP page with the values from collection as Below
RegisterUser.jsp
<logic:iterate property="userSkills" id="userDet" name="User">
<html:checkbox property="label" name="userDet" indexed="true">
<bean:write property="label" name="userDet"></bean:write>
</html:checkbox>
</logic:iterate>
The Output is as below
Now while submitting the form I want the values from the Checked Check box alone.I don't want to write 5 separate lines for getting values from each check box. How to do this
Thanks for the help.
Struts has a tag that fit your needs : multibox, you can see these links :
http://struts.apache.org/release/1.2.x/userGuide/struts-html.html#multibox
http://www.jguru.com/faq/view.jsp?EID=925277
And convert your collection to an array
In Userdetails.java
public class UserDetails extends ActionForm {
private String[] userSkills;
//setter and getter for userSkills
}
In RegisterUser.jsp
<html:multibox property="userSkills" value="java"/> java
<html:multibox property="userSkills" value="mysql"/> mysql
<html:multibox property="userSkills" value="php"/> php
Try to use this

Categories