I have been working on a Spring project that makes use of the Spring form taglib (http://www.springframework.org/tags/form).
I am using some multiple select boxes to indicate some options (Country, factory,...)When I pass an entire list to the select - all is well: the first option of the select list is selected by default. However, when a user is from a specific country, the list is filtered and only his country is shown. In this case the first element is not selected by default.
JSP page:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:select path="countryValues" multiple="true" size="9" style="width:192px;" cssErrorClass="field-error">
<form:options items="${command.countries}" itemValue="countryCode" itemLabel="correctDisplayString"/>
</form:select>
Command.java
public List<CountryMaster> getCountries() {
return countries;
}
public void setCountries(List<CountryMaster> countries) {
this.countries = countries;
}
Controller.java
#RequestMapping(value = "/overview", method = RequestMethod.GET)
public String overview(HttpServletRequest request, Model model) {
Attrs attrs = getAttrs(request);
UserLocale.initUser(getUser(request));
User user = UserLocale.getUser();
List<FactoryMaster> factoryList = getFactoryList(attrs);
List<CountryMaster> countryList = getCountryList(attrs);
Command command = initCommand(attrs);
model.addAttribute(command);
if(user.hasRole(User.NORMAL)&& user.getCountryCode() != null){
if(countries == null){
countries= getDaoBuilder().getDaoCountry().countryMap();
}
String isoCode = countries.get(user
.getCountryCode());
List<CountryMaster> buffer = new ArrayList<CountryMaster>();
for(CountryMaster i : countryList){
if(isoCode.equalsIgnoreCase(i.getIsoCode())){
buffer.add(i);
}
}
System.out.println("List size: "+buffer.size());
command.setCountries(buffer);
}
else{
command.getCountries().addAll(getCountryList(attrs));
}
command.getModels().addAll(getModelList(attrs));
command.setBrands(getBrandList(attrs));
return "/reporting/overview";
}
private List<CountryMaster> getCountryList(Attrs attrs) {
List<CountryMaster> result = new ArrayList<CountryMaster>();
CountryMaster ct = new CountryMaster(CountryMaster.ISO_COUNTRY_JOKER, 00);
ct.setDescription("ALL");
result.add(ct);
result.addAll(attrs.countryList);
return result;
}
On the HTML page, I can see in other lists that the first element has the attribute selected="selected". Anybody have any idea why this is not the case when I manipulate my list? Or does anyone know what is resposible for this selected attribute allocation? (Is this javascript, java attribute,...?)
Thanks in advance!
Turns out the value of the listbox can be set: this piece of code made it quite an easy fix:
public String overview(HttpServletRequest request, Model model) {
Attrs attrs = getAttrs(request);
UserLocale.initUser(getUser(request));
User user = UserLocale.getUser();
List<FactoryMaster> factoryList = getFactoryList(attrs);
List<CountryMaster> countryList = getCountryList(attrs);
Command command = initCommand(attrs);
model.addAttribute(command);
if(user.hasRole(User.NORMAL)&& user.getCountryCode() != null){
if(countries == null){
countries= getDaoBuilder().getDaoCountry().countryMap();
}
String isoCode = countries.get(user
.getCountryCode());
List<CountryMaster> buffer = new ArrayList<CountryMaster>();
for(CountryMaster i : countryList){
if(isoCode.equalsIgnoreCase(i.getIsoCode())){
buffer.add(i);
}
}
System.out.println("List size: "+buffer.size());
command.setCountries(buffer);
// FIXED SELECTION OF ELEMENT
command.setFactoryValues(new String[]{isoCode});
// FIXED SELECTION OF ELEMENT
}
else{
command.getCountries().addAll(getCountryList(attrs));
}
command.getModels().addAll(getModelList(attrs));
command.setBrands(getBrandList(attrs));
return "/reporting/overview";
}
This way, you set the value of the listbox using code, and when the page is opened - the value is already there, making it selected by default.
Related
This is a query I wrote:
public List<PrRevamps> fetchRevampHistory(String refNo) {
List<PrRevamps> list = dsl.select(
DSL.concat(
Tables.PR_REVAMPS.PR_REVAMP_CODE,DSL.val("-"),
Tables.PR_REVAMP_CODES.PR_DESCRIPTION
).as("DESCRIPTION"),
Tables.PR_REVAMPS.PR_REVAMP_DATE,
Tables.PR_REVAMPS.PR_KEY)
.from(Tables.PR_REVAMP_CODES,Tables.PR_REVAMPS)
.where(Tables.PR_REVAMPS.PR_REVAMP_CODE.equal(Tables.PR_REVAMP_CODES.PR_CODE))
.and(Tables.PR_REVAMPS.PR_PROP_REF_NO.equal(refNo))
.fetchInto(PrRevamps.class);
return list;
}
and I need to display revampCode and description in one row in vaadin grid.
i.e "A-Marshall"
This is the grid code below:
private void populateRevampGrid() {
Object ref = serv.getAttribute("ref");
String propRef = "";
if(ref != null) {
propRef = (String)ref;
List<PrRevamps> list = getService().fetchRevampHistory(propRef);
if(!list.isEmpty()) {
revampGrid.setContainerDataSource(new BeanItemContainer<>(list));
//revampGrid.addColumn("prRevampCode").setHeaderCaption("REVAMP DESCRIPTION");
revampGrid.removeColumn("prKey");
revampGrid.removeColumn("prLeaseType");
revampGrid.removeColumn("prPropRefNo");
revampGrid.getColumn("prRevampDate").setHeaderCaption("REVAMP DATE");
revampGrid.getColumn("prRevampCode").setHeaderCaption("REVAMP TYPE");
} else {
clearfields();
Notification.show("list is empty",Type.ERROR_MESSAGE.WARNING_MESSAGE);
}
}
}
As I understand, you have the description field, that has the desired value.
If not, you can add properties, generated from an object on the fly. But for this, you will need to use Container.
The full description can be found on Vaadin documentation https://vaadin.com/docs/v7/framework/datamodel/datamodel-container.html (see GeneratedPropertyContainer)
I try to display Arraylist object in Thmeleaf page but I got null for the value.
I can display the arraylist in controller on console. Is it correct the way I pass arraylist in function.
In controller
#RequestMapping("/searchSummon")
public String Search(Model model) {
model.addAttribute("summonsDetailType", new SummonsDetailType());
model.addAttribute("rowType", new RowType());
return "searchSummon";
}
#RequestMapping(value = "/searchProcess", method = RequestMethod.POST)
public String searchProcess(SummonsDetailType summonsDetailType, RowType rowType) {
ArrayList<RowType> rowTypes2 = new ArrayList<RowType>();
SummonsDetailType summonsDetailType2 = pdxiRes.getRequest().getSummonsDetail();
for (RowType rowType3 : summonsDetailType2.getRow()) {
rowTypes2.add(rowType3);
}
System.out.println(rowTypes2.get(0).getDistrictCode());
return "/searchResult";
}
html page
<tr th:each="rowType : ${rowType}">
<td th:text="'NRIC NO: ' + ${rowType.DistrictCode}"></td>
</tr>
I solved the problem by adding the arraylist in model
model.addAttribute("rowTypes2", rowTypes2);
We are working for internationalizing an old application with some dirty code. For example, we have an object DTO InstrumentDto:
private String label;
private Quotation quotation;
private ExprQuote quoteExp;
public String getTypeCouponCouru() {
if (this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_CPN_INCLUS)
|| this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_INTERET)) {
return "Coupon attaché";
} else if(this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_PIED_CPN)){
return "Coupon détaché";
} else {
return "";
}
}
public String getFormattedLabel() {
StringBuilder formattedLabel = new StringBuilder(this.label);
Quotation quote = this.quotation;
if (this.quotation != null) {
formattedLabel.append(" ");
formattedLabel.append(FormatUtil.formatDecimal(this.quotation.getCryQuote());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(" %");
} else {
formattedLabel.append(" ");
formattedLabel.append(this.quotation.getCurrency().getCode());
}
formattedLabel.append(" le ");
formattedLabel.append(DateUtil.formatDate(this.quotation.getValoDate()));
}
return formattedLabel.toString();
}
Then, those methods are used on JSPs. For example for getFormattedLabel(), we have :
<s:select name = "orderUnitaryForm.fieldInstrument"
id = "fieldInstrument"
list = "orderUnitaryForm.instrumentList"
listKey = "id"
listValue = "formattedLabel" />
IMO, the first method doesn't have its place on the DTO. We are expecting the view to manage the label to print. And in this view (the JSP), no problem to translate those words.
Additionally, this method is just used in 2 JSP. Not a problem to "repeat" the conditional tests.
But it's more difficult for getFormattedLabel() : this method is used in a lot of JSP, and the building of the formatted label is "complicated". And it's not possible having the i18n service in the DTO.
So how to do that ?
Your code in getFormattedLabel() seems to be business logic.
A DTO is a simple object without any complex test/behavior (see wiki definition).
IMO, you should move this chunk of code to your Action and split your *.properties file like this:
Your *.properties:
message1= {0} % le {1}
message2= {0} {1} le {2}
Your Action:
public MyAction extends ActionSupport {
public String execute(){
//useful code here
InstrumentDto dto = new InstrumentDto();
StringBuilder formattedLabel = new StringBuilder(label);
if (this.quotation != null) {
String cryQuote = FormatUtil.formatDecimal(this.quotation.getCryQuote());
String date = DateUtil.formatDate(this.quotation.getValoDate());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(getText("message1", new String[] { cryQuote, date }));
} else {
String cryCode = this.quotation.getCurrency().getCode();
formattedLabel.append(getText("message2", new String[] { cryQuote, cryCode, date }));
}
}
dto.setFormattedLabel(formattedLabel);
}
}
Hope this will help ;)
I have a jsp page on which there are various checkboxes.
Some of checkboxes are disabled by default and are already selected. There is an option to create a new template and assign values to checkboxes. These values are saved into a DB.
My problem is that saved values of selected checkboxes are always two less than values that were selected by the user. On debugging the java code, I found that the passed values were as selected by the user. But the values of the disabled checkboxes are saved to the DB, and the last two values selected by the user are not saved to the DB.
I am hereby attaching the code which picks the selected values and code which saves the values of checkboxes.
Code to pick selected checkbox values.
public ActionForward listSave(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HardwareKey key = SecurityUtils.getKeySecurity();
key.isFeaturePresent(HardwareKey.WS_DATA_EXCHANGE);
DataExchangeTemplateForm thisForm = (DataExchangeTemplateForm) form;
DataExchangeService service = (DataExchangeService) ServiceLocator
.getServiceWithName(DataExchangeService.class.getName());
ActionMessages errors = new ActionMessages();
Integer dexTemplateId = thisForm.getTemplateId();
String[] paramValues = request.getParameterValues("isRequiredFlag");
String[] fieldIds = request.getParameterValues("fieldId");
String[] dataTypeIds = request
.getParameterValues("dexDataType.dataTypeId");
String templateType = request.getParameter("templateType");
boolean isDexTemplate = false;
String direction = thisForm.getDirection();
String dexTemplateName = thisForm.getDexTemplateName();
if (Validator.isNullOrEmpty(dexTemplateName)) {
ActionMessage msg = new ActionMessage("error.data.exchange",
" Template name Can't be empty");
errors.add("error.data.exchange", msg);
saveErrors(request, errors);
return view(mapping, form, request, response);
}
String dexTemplateVersion = thisForm.getDexVersion();
if (Validator.isNotNullGreaterThanZero(dexTemplateId)) {
DexTemplate dexTemplateOld = (DexTemplate) service.getObject(
DexTemplate.class, dexTemplateId);
String profileNameOld = dexTemplateOld.getDescription();
if (!dexTemplateName.equalsIgnoreCase(profileNameOld)
&& service.isDuplicateTemplateName(dexTemplateName)) {
ActionMessage msg = new ActionMessage("error.data.exchange",
"Duplicate Template name");
errors.add("error.data.exchange", msg);
saveErrors(request, errors);
return view(mapping, form, request, response);
}
service.updateDexTemplateAndParams(dexTemplateName, direction,
dexTemplateId, dataTypeIds, paramValues, fieldIds,
dexTemplateVersion);
} else {
if (!service.isDuplicateTemplateName(dexTemplateName)) {
if(templateType != null && templateType.equals("extranetDex")) {
isDexTemplate = true;
}
dexTemplateId = service.saveDataExchangeTemplate(
dexTemplateName, direction, dexTemplateVersion, isDexTemplate);
// saving params...
service.saveDexTemplateParams(dexTemplateId, dataTypeIds,
paramValues, fieldIds);
} else {
ActionMessage msg = new ActionMessage("error.data.exchange",
"Duplicate Template name");
errors.add("error.data.exchange", msg);
saveErrors(request, errors);
return view(mapping, form, request, response);
}
}
Code To Save Selected Checkbox values:
public void saveDexTemplateParams(Integer dexTemplateId,
String[] dataTypeIds, String[] paramValues, String[] fieldIds)
throws BaajaException {
DexTemplate dexTemplate = (DexTemplate) getObject(DexTemplate.class,
dexTemplateId);
hibernateInitialize(dexTemplate);
int fieldOrder = 1;
if(paramValues!=null){
for (int i = 0; i < paramValues.length; i++) {
if (!Validator.isNullOrEmpty(paramValues[i])
&& paramValues[i].equalsIgnoreCase("true")) {
DexTemplateField templatefield = new DexTemplateField();
DexField dexField = (DexField) getObject(DexField.class,
Integer.parseInt(fieldIds[i]));
templatefield.setDexField(dexField);
templatefield.setDexTemplate(dexTemplate);
templatefield.setFieldOrder(fieldOrder++);
saveObject(templatefield);
}
Pls Suggest any possible solution.
Check if the name/id of the last 2 checkboxes are the same as for the other checkboxes.
It is recommended that if you are using Struts framework, use FormBean to attach to the JSP Form. In that FormBean, declare ArrayList with the name same as the property attribute of <html:checkbox> . This will help you minimize your support/maintenance time.
I am using JSF 1.2 framework. Right now i am trying to implement a file upload process in which the number of files to be uploaded is controlled by the end user. Please find the below snapshot and code snippet for reference.
XHTML Implementation:-
<a4j:commandLink action="#{importWSDLBean.xsdLoopIncrementAction}" reRender="WSDLPanelGrid">
<h:graphicImage value="/images/plus_icon.gif" />
</a4j:commandLink>
<a4j:commandLink action="#{importWSDLBean.xsdLoopDecrementAction}" reRender="WSDLPanelGrid">
<h:graphicImage value="/images/minus_icon.gif" />
</a4j:commandLink>
<h:panelGrid id="WSDLPanelGrid">
<c:forEach items="#{importWSDLBean.acscDataList}" var="inputFUpload">
<t:inputFileUpload id="#{inputFUpload.id}" value="#{inputFUpload.value}" />
</c:forEach>
</h:panelGrid>
Java Bean Implementation:-
public String xsdLoopIncrementAction() {
if (acscDataList == null) {
acscDataList = new ACSCDataList(new ArrayList());
HtmlInputFileUpload htmlUpload = new HtmlInputFileUpload();
htmlUpload.setId("upload" + (acscDataList.size() + 1));
acscDataList.add(htmlUpload);
} else {
HtmlInputFileUpload htmlUpload = new HtmlInputFileUpload();
htmlUpload.setId("upload" + (acscDataList.size() + 1));
acscDataList.add(htmlUpload);
}
return "success";
}
public String xsdLoopDecrementAction() {
if (acscDataList != null) {
if (acscDataList.size() > 0) {
acscDataList.remove(acscDataList.size() - 1);
}
}
return "success";
}
This implementation resets the file upload values whenever i increment or decrement the no. of file upload fields. Also when i submit the form i cant able to get the UploadedFile object (File Upload prerequisite such as Form type and Web.xml configuration is also included).
Can anyone help me out?
If you create dinamically yours input uploads? with binding property
<h:panelGrid binding="#{importWSDLBean.myPanelGrid}"></h:panelGrid>
in your backing bean add property
private javax.faces.component.html.HtmlPanelGrid myPanelGrid;
/**
* #return the myPanelGrid
*/
public javax.faces.component.html.HtmlPanelGrid getMyPanelGrid() {
return myPanelGrid;
}
/**
* #param myPanelGrid the myPanelGrid to set
*/
public void setMyPanelGrid(javax.faces.component.html.HtmlPanelGrid myPanelGrid) {
this.myPanelGrid = myPanelGrid;
}
/*change for your value upload type*/
Map<String,Object> values = new LinkedHashMap<String, Object>();
public void addInputAction() {
String key = "key"+values.size();
values.put(key,"newValue");
HtmlInputText input = new HtmlInputText();
/*add input property (converter,css,etc?)*/
input.setId("id_"+key);
input.setValueExpression("value", createValueExpression(
"#{WSDLPanelGrid.values['"+key+"']}", new Class[0], String.class));
/*add to panel grid your input*/
myPanelGrid.getChildren().add(input);
}
public static ValueExpression createValueExpression(String value,
Class[] params, Class returnType) {
FacesContext fctx = FacesContext.getCurrentInstance();
ELContext elctx = fctx.getELContext();
Application jsfApp = fctx.getApplication();
ExpressionFactory exprFactory = jsfApp.getExpressionFactory();
ValueExpression valueExpr = exprFactory.createValueExpression(elctx,
value, returnType);
return valueExpr;
}
Does something prevent you from using JSF 2? Primefaces ( www.primefaces.org ) has a multiple fileupload component. It is available for JSF 1.2, but development will go on for JSF 2 only.