How do I translate text in .java source files? - java

I have an enum like this
public enum CheckboxFeature {
Option1(" choose this"),
Option2(" or this"),
Option3(" maybe this"),
Option4(" lastly this");
#Getter
private final String text;
public static CheckboxFeature fromName(String v) {
for (CheckboxFeature c: CheckboxFeature.values()) {
if (c.name().equalsIgnoreCase(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
This shows the four options as checkboxes in the web view
<form:checkboxes items="${features}" path="enabledFeatures" itemLabel="text" delimiter="<br/>"/>
How can I translate these options? I use fmt:message for the rest of the translations in the web view.
I have tried
Option1(" <fmt:message key=\"text.test\"/>"),
and
Option1(" ${option1}"),
with
<fmt:message key="text.select" var="option1"/>
in the .jsp.
Neither of them work, so it seems it can't work this way. What is the correct way of translating the strings? Ideally using the fmt:message and i18n resources (lang.properties files) that are in place and working on the rest of the servlet?

Optimally, you get the resource key from the enum, and look that up.
public enum CheckboxFeature {
Option1("label.option1.key"),
Option2("label.option2.key"),
Option1("label.option3.key"),
Option2("label.option4.key");
private final String key;
[...]
I don't know how to nest a l10n lookup in the itemLabel attribute, so I would write something like:
<c:forEach items="Options.values()" var="current">
<form:checkbox path="selectedOptions" value="${current.name()}"/> <fmt:message key="${current.getKey()}"/>
</c:forEach>

1、CheckboxFeature add method like:
public static List<String> getAllCheckboxFeature(String v) {
return Arrays.asList(Option1.getText(),...Option4.getText());
}
2、than use the jstl like:
<c:forEach items="${options}" var="option">
<input type="checkbox" ="${option}">
</c:forEach>

Related

JSTL - Unable to access property of the object stored as session variable

I'm following the standard MVC architecture.
In my Controller I have the following code,
userDetailsBean = userDetailsDAO.getUserDetailsFromEmail(loginEmail);
session.setAttribute("userDetails", userDetailsBean);
The object userDetailsBean contains different methods like getFName(), getLName() etc. I'm accessing this object from the View file as follows,
<c:choose>
<c:when test="${sessionScope.userDetails != null}">
<li>
<a href="#userName">
${sessionScope.userDetails.getFName()}
</a>
</li>
</c:when>
<c:otherwise>
<li>
Log in/Register
</li>
</c:otherwise>
</c:choose>
I'm getting the following error from the above code,
HTTP Status 500 - /header.jsp(22,38) The function getFName must be used with a prefix when a default namespace is not specified
I searched a lot on the internet and tried many different suggestions like,
${sessionScope.userDetails.fName}
${sessionScope.userDetails.get(0).fName}
but none of it worked,
I'm using Tomacat 6 with JSTL 1.2 and Netbeans as IDE.
Any help is appreciated, thanks in advance!
You could read the JavaBean Specification. For links to it, look at the answer at Where is the JavaBean property naming convention defined?
Look at sections 8.3 and 8.8.
You should make your life easy and just use conventional names for your fields. But, if you choose not to do that, then consider the following bean.
package test;
public class BeanTest implements java.io.Serializable {
private String bHours = "ten";
private String RICK = "me";
private String Joe = "hello";
public BeanTest(){
}
public void setbHours(String bHours){
this.bHours = bHours;
}
public String getbHours(){
return bHours;
}
public void setRICK(String str){
RICK = str;
}
public String getRICK(){
return RICK;
}
public void setJoe(String str){
Joe = str;
}
public String getJoe(){
return Joe;
}
}
In a JSP you can use the following to access the data in the bean.
<jsp:useBean id="myBean" class="test.BeanTest" />
${myBean.RICK}
${myBean.joe}
${myBean.bHours}
<%=myBean.getbHours()%>

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 ; }

How to make spring checkboxes checked by default?

I'm using Spring 3.1.0.RELEASE. I have this field in my command object ...
public Set<EventFeed> getUserEventFeeds() {
return this.userEventFeeds;
}
On my Spring JSP page, I want to display a checkbox list of all possible event feeds, and then have checked checkboxes if the user has one in his set. I want to have some special HTML formatting around each checkbox, so I'm trying ...
<form:form method="Post" action="eventfeeds.jsp" commandName="user">
...
<c:forEach var="eventFeed" items="${eventFeeds}">
<tr>
<td><form:checkbox path="userEventFeeds" value="${eventFeed}"/></td>
<td>${eventFeed.title}</td>
</tr>
</c:forEach>
...
However, the items aren't getting checked by default if one is in the set. How do I do this? Here is the binder I'm using in my controller class ...
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(EventFeed.class, new EventFeedEditor());
}
private class EventFeedEditor extends PropertyEditorSupport {
#Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(eventFeedsDao.findById(Integer.valueOf(text)));
}
#Override
public String getAsText() {
return ((EventFeed) getValue()).getId().toString();
}
}
#Dave, there is something called form:checkBoxes. You can try with that.
<form:checkboxes path="userEventFeeds" items="${eventFeeds}" itemLabel="id" itemValue="value"/>
My assumption here is you should have "id" and "value" defined in the EventFeed class.
I just tried this by having a String[] availableList and String[] selectedList. It works like charm. You can give a try as well.
Interestingly this works:
<form:checkbox path="services" value="${type}" checked="checked"/>
You can do this by placing selected default property true in your class
class User {
boolean userEventFeeds = true;
}
I've tried both form:checkboxes and form:checkbox with the same data and the first works, the second doesn't. (Same release of Spring you have)
It looks like there was a bug which, despite their claim, seems to be still there.
For my usecase (reacting on stuff in a list that has nothing to do with the object being filled), this code worked:
(Please be aware that this is a last-resort kind of code, other solutions are most likely better suited.)
<%# taglib prefix="jstl" uri="http://java.sun.com/jsp/jstl/core" %>
<jstl:forEach var="listObject" items="${someList}">
<jstl:if test="${listObject.active}">
<form:checkbox path="active" checked="checked"/>
</jstl:if>
<jstl:if test="${!listObject.active}">
<form:checkbox path="active"/>
</jstl:if>
</jstl:forEach>

Populate List<String> in struts2 from form data

I feel this should be exceedingly obvious, but so far I've failed to find an answer.
I want to have a list of strings (or an array of strings, I really don't care) get populated by form data in Struts2.
I've seen several examples of how to do indexed properties with beans, but wrapping a single string inside an object seems fairly silly.
So I have something like
public class Controller extends ActionSupport {
private List<String> strings = new ArrayList<String>();
public Controller() {
strings.add("1");
strings.add("2");
strings.add("3");
strings.add("4");
strings.add("5");
}
public String execute() throws Exception {
return ActionSupport.SUCCESS;
}
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> s) {
strings = s;
}
}
...
<s:iterator value="strings" status="stringStatus">
<s:textfield name="strings[%{#stringStatus.index}]" style="width: 5em" />
</s:iterator>
The form fields get populated with their initial values (e.g. 1, 2, etc), but the results are not properly posted back. setStrings is never called, but the values get set to empty strings.
Anybody have any idea what's going on? Thanks in advance!
I believe as you have it, your jsp code would render something like:
<input type="text" name="strings[0]" style="width: 5em" value="1"/>
<input type="text" name="strings[1]" style="width: 5em" value="2"/>
<input type="text" name="strings[2]" style="width: 5em" value="3"/>
...
Notice that the name of the field references are "strings[x]" where as you need the name to be just "strings". I would suggest something like:
<s:iterator value="strings" status="stringStatus">
<s:textfield name="strings" value="%{[0].toString()}" style="width: 5em" />
</s:iterator>
Not sure if the value attribute above may is correct, but I think something like this will get you the desired result.

Multiple Submit Buttons problem in Struts2

Trying to work with multiple submit buttons within a single form in struts2 application but not able to work.
here is the jsp code i am using
<tr>
<td class="button"><input type="submit" value="Import"
name="destinationImport" class="button"></td>
<td class="button"><input type="submit" value="Export"
name="destinationExport" class="button"></td>
</tr>
here is the java part
private boolean destinationImport;
private boolean destinationExport;
//and the respective setters and getters
but i am sure is that Struts2 type convertor is having problem converting the String value to boolean
do any one have idea how to achieve this
Thanks in advance
Methods : getDestinationExport / setDestinationExport should deal with String, since your values: "Export" and "Import" aren't convertible directly to boolean type.
If you need convert it by internal rule, place corresponding code inside setDestinationExport. Something like that:
public void setDestinationExport(String arg){
destinationExport = "Export".equals(arg);
destinationImport = "Import".equals(arg);
}
This way should works
private boolean destinationImport = false;
private boolean destinationExport = false;
public void setDestinationImport(boolean destinationImport) {
this.destinationImport = true;
}
public void setDestinationExport(boolean destinationExport) {
this.destinationExport = true;
}
Reference:
http://serpensalbus.com/blog/tricking-struts2-multiple-submit-buttons/

Categories