Is a custom JSF converter needed for this simple class? - java

I have been trying with limited success to code a JSF application. In one section of the application, I need users to select from a select menu which displays a list of selectable status values. The Status class (presented below), which is used to populate the List that is displayed in the select menu, is a simple class made up of two Strings: one is the code used to look up the description in the database, the other is the human-readable description. I am trying to find out if I need a converter here at all, and if so, how best to implement the converter. This is a JSF 1.1 project using Java 1.5
I am using the following code in the JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<h:graphicImage id="image" url="/images/appname.jpg"
alt="app name" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<jsp:include page="/jsp/menu.jsp" />
</head>
<body>
<h:outputText
value="Add Value"
style="font-size:20px;" />
<h:messages errorStyle="color: red" infoStyle="color: green"
layout="table" />
<h:form id="statusReasonEditForm">
<table>
<tr>
<td><h:outputText id="txtvalue" value="Status" /></td>
<td><h:selectOneMenu id="selectStatus"
value="#{pc_statusReasonBacker.status}"
binding="#{pc_statusReasonBacker.selectItem}">
<f:selectItems value="#{pc_statusReasonBacker.selectStatuses}" />
<f:converter converterId="statusConverter" />
</h:selectOneMenu>
<td><h:outputText id="txtvaluereason" value="Status Reason" /></td>
<td><h:inputText id="txtinputreason"
value="#{pc_statusReasonBacker.statusReason.statusReason}"
maxlength="100" size="40" /></td>
<td><h:outputText id="txtvaluereasondesc"
value="Status Reason Desc" /></td>
<td><h:inputText id="txtinputreasondesc"
value="#{pc_statusReasonBacker.statusReason.statusReasonDesc}"
maxlength="100" size="40" /></td>
</tr>
</table>
<tr>
<td><h:commandButton id="savebutton" value="Save"
action="#{pc_statusReasonBacker.save}" /></td>
<td><h:commandButton id="cancelbutton" value="Cancel"
action="#{pc_statusReasonBacker.cancel}" /></td>
</tr>
</h:form>
<hr />
</body>
</html>
</f:view>
The backing bean is shown here (some non-related sections, such as paging, removed for clarity):
public class StatusReasonBacker {
private List<StatusReason> statusReasonList;
private List<Status> statusList;
private List<SelectItem> selectStatuses;
private StatusReason statusReason;
private StatusDao sDao;
private Status status;
private UIData statusReasonTable;
private HtmlSelectOneMenu selectItem;
private String selectedStatus = "";
public StatusReasonBacker() {
sDao = new StatusDao();
statusReason = new StatusReason();
selectStatuses = new ArrayList<SelectItem>();
status = new Status();
selectItem = new HtmlSelectOneMenu();
}
public String insert() {
status.setStatusCde("");
statusReason.setStatus(status);
statusReason.setStatusReason("");
statusReason.setStatusReasonCde("");
statusReason.setStatusReasonDesc("");
return "success";
}
public String edit() {
this.statusReason = (StatusReason) statusReasonTable.getRowData();
selectItem.setValue(statusReason.getStatus().getStatusCde());
return "success";
}
public String update() {
if ("".equalsIgnoreCase(statusReason.getStatusReason().trim())) {
Message
.addErrorMessage("You must enter a value for the status reason.");
return "failure";
} else if (("".equalsIgnoreCase(statusReason.getStatusReasonDesc()
.trim()))) {
Message
.addErrorMessage("You must enter a value for the status reason description.");
return "failure";
}
sDao.updateStatusReason(statusReason);
return "statusreasons";
}
public String delete() {
StatusReason statReason = (StatusReason) statusReasonTable.getRowData();
sDao.deleteStatusReason(statReason);
return "statusreasons";
}
public String cancel() {
return "statusreasons";
}
public String save() {
statusReason.setStatus(status);
sDao.insertStatusReason(statusReason);
return "statusreasons";
}
...
public StatusDao getSDao() {
return sDao;
}
public void setSDao(StatusDao dao) {
sDao = dao;
}
public List<StatusReason> getStatusReasonList() {
statusReasonList = sDao.getStatusReasons();
return statusReasonList;
}
public void setStatusReasonList(List<StatusReason> statusReasonList) {
this.statusReasonList = statusReasonList;
}
public UIData getStatusReasonTable() {
return statusReasonTable;
}
public void setStatusReasonTable(UIData statusReasonTable) {
this.statusReasonTable = statusReasonTable;
}
public StatusReason getStatusReason() {
return statusReason;
}
public void setStatusReason(StatusReason statusReason) {
this.statusReason = statusReason;
}
public List<Status> getStatusList() {
statusList = sDao.getStatuses();
return statusList;
}
public void setStatusList(List<Status> statusList) {
this.statusList = statusList;
}
public List<SelectItem> getSelectStatuses() {
selectStatuses.clear();
if (statusList == null) {
statusList = this.getStatusList();
}
for (Status sr : statusList) {
SelectItem si = new SelectItem();
si.setValue(sr.getStatusCde());
si.setLabel(sr.toString());
si.setDescription(sr.toString());
selectStatuses.add(si);
}
return selectStatuses;
}
public void setSelectStatuses(List<SelectItem> selectStatuses) {
this.selectStatuses = selectStatuses;
}
public String getSelectedStatus() {
selectedStatus = statusReason.getStatusDesc();
return selectedStatus;
}
public void setSelectedStatus(String selectedStatus) {
this.selectedStatus = selectedStatus;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public HtmlSelectOneMenu getSelectItem() {
return selectItem;
}
public void setSelectItem(HtmlSelectOneMenu selectItem) {
this.selectItem = selectItem;
}
}
Thanks!

I am trying to find out if I need a converter here at all, and if so, how best to implement the converter.
You need a converter whenever you want to pass non-standard Java Objects from a HTTP request to another HTTP request. With non-standard I mean not a String, Number or Boolean. This all simply because HTTP request parameters can only be Strings. That Number and Boolean works is because EL can recognize them and has built-in coercions for it.
For non-standard Java Objects you need to implement a javax.faces.convert.Converter which converts the Object to a String (or a Number so you want, for example a Long id which can be the PK of the associated row in database table) inside the getAsString() method before displaying in HTML. You do the other way round in the getAsObject() method during processing of the request parameters (e.g. get the associated object from DAO by its id).
You can find here an example of how to use a Converter for a h:selectOneMenu. You see that this article also contains an alternative, but you'll need to do a bit more work in the backing bean to convert (map) the objects yourself.

Related

Values not appeared in drop down

there is an issue in my web application, the below code i wrote for entire application and it is working fine..but not in this case.
I am using the correct variables name in JSTL, my query is also running fine and produces the required result that i want, but still those values didn't appeared in the drop down .. i am even not able to figure it out
can anybody help me to sort out this
<td>
<span id="store_${i}"></span>
<f:select class="form-control" path="boqList[${i}].organizationCode" id="storeId${i}" onchange="chekeAvailibiltyAtStore(this.value,'${b.itemCode}','${b.itemUnit}','${i}')" required="true">
<f:option value="">Select Area Store</f:option>
<c:forEach items="${areaStors}" var="as" >
<f:option value="${as.organizationCode}">${as.organizationName}</f:option>
</c:forEach>
</f:select>
</td>
Inside controller
mav.addObject("areaStors", areaStoreDAO.findAll());
Inside Service (Query working Fine)
public List<ErpAreaStore> findAll() {
String query = "SELECT ORGANIZATION_CODE "
+ " , ORGANIZATION_NAME "
+ " FROM XXAP_AREA_STORE "
+ " ORDER BY ORGANIZATION_CODE ASC ";
MapSqlParameterSource param = new MapSqlParameterSource();
List<ErpAreaStore> inventoryOnhands = getNamedParameterJdbcTemplate().query(query, param, new RowMapper<ErpAreaStore>() {
#Override
public ErpAreaStore mapRow(ResultSet rs, int rowNo) throws SQLException {
ErpAreaStore areaStore = new ErpAreaStore();
areaStore.setOrganizationCode(rs.getInt("ORGANIZATION_CODE"));
areaStore.setOrganizationName(rs.getString("ORGANIZATION_NAME"));
return areaStore;
}
});
return inventoryOnhands;
}
POJO
public class ErpAreaStore implements java.io.Serializable {
private int organizationCode;
private String organizationName;
public int getOrganizationCode() {
return organizationCode;
}
public void setOrganizationCode(int organizationCode) {
this.organizationCode = organizationCode;
}
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
}
see the below screenshot
Add <jsp:useBean> tag at the beginning of your JSP. It's a straightforward test that the areaStors list is present. Example:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<jsp:useBean id="areaStors" scope="request" type="java.util.List"/>
<!-- ... -->
<td>
<span id="store_${i}"></span>
<f:select class="form-control" path="boqList[${i}].organizationCode" id="storeId${i}" onchange="chekeAvailibiltyAtStore(this.value,'${b.itemCode}','${b.itemUnit}','${i}')" required="true">
<f:option value="">Select Area Store</f:option>
<c:forEach items="${areaStors}" var="as" >
<f:option value="${as.organizationCode}">${as.organizationName}</f:option>
</c:forEach>
</f:select>
</td>

how to bind data to list in spring form

I have a spring form with having backing object for it. The form is like this-
<sf:form cssClass="form-horizontal" commandName="campaignModel" method="post">
<sf:input path="campaign.name" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
</sf:form>
Model class(Form backing Object) -
CampaignModel.java
public class CampaignModel {
private Campaign campaign = new CampaignImpl();
private List<LandingPageModel> landingPageModels = new Arraylist<LandingPageModel>;
public Campaign getCampaign() {
return campaign;
}
public void setCampaign(Campaign campaign) {
this.campaign = campaign;
}
public List<LandingPageModel> getLandingPageModels() {
return landingPageModels;
}
public void setLandingPageModels(List<LandingPageModel> landingPageModels) {
this.landingPageModels = landingPageModels;
}
LandingPageModel.java is -
public class LandingPageModel {
private LandingPage landingPage = new LandingPageImpl();
private List<LandingPageParameterImpl> landingPageParameters = new ArrayList<LandingPageParameterImpl>();
public LandingPage getLandingPage() {
return landingPage;
}
public void setLandingPage(LandingPage landingPage) {
this.landingPage = landingPage;
}
public List<LandingPageParameterImpl> getLandingPageParameters() {
return landingPageParameters;
}
public void setLandingPageParameters(List<LandingPageParameterImpl> landingPageParameters) {
this.landingPageParameters = landingPageParameters;
}
}
LandingPage.java is -
public class LandingPageImpl extends EntityImpl implements LandingPage {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} }
So i want that i can insert many objects of landingPage (having their own url property) in landingPageModels list. That means i can have mulitple input tag having url property like this -
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
But when executing this code, spring gives me error that landingPage property of landingPageModels has not getter setter method. How to solve it and how to take multiple value like this ?
In order to bind a list model property to multiple input fields, you need this in the rendered form:
<input type="text" name="landingPageModels[0].landingPage.url" class="form-control" />
<input type="text" name="landingPageModels[1].landingPage.url" class="form-control" />
<input type="text" name="landingPageModels[2].landingPage.url" class="form-control" />
Which is accomplished by:
<c:forEach items="${campaignModel.landingPageModels}" varStatus="s">
<sf:input path="landingPageModels[${s.index}].landingPage.url" class="form-control" />
</c:forEach>
The error you are getting is correct as landingPageModels is a list.
You would need to use index access like this landingPageModels[0].landingPage.url.
If you have dynamic number of input/url, then you can use <c:forEach> to create dynamic input variable names
<c:forEach items="${campaignModel.landingPageModels}" var="landingPage">
<sf:input path="landingPage.url" class="form- control" />
</c:forEach>
Will the above not works for you to view data? To get them in controller you may have to use dynamic table row concept in HTML or for each single LandingPage entry add to form bean object by clicking add button and render back.
In my case Person command object having List<Token> property, in order to bind the list of tokens we have designed page as attached screen shot below, clicking on Add button hits the controller and add the each token List<Token> and render back to same view and displays added token in list view, it facilitates to add multiple token for Person.
I dont know how to do it with spring form lib input but if you want to bind using simple html input than you can bind list like this
Simple.jsp
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
</head>
<body>
<form:form method="post" action="save.html" modelAttribute="contactForm">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td><input name="contacts[0].firstname" /></td>
<td><input name="contacts[0].lastname" /></td>
</tr>
<tr>
<td><input name="contacts[1].firstname" /></td>
<td><input name="contacts[1].lastname" /></td>
</tr>
</table>
<br/>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
#controller :
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("contactForm") ContactForm contactForm) {
List<Contact> contacts = contactForm.getContacts();
if(null != contacts && contacts.size() > 0) {
ContactController.contacts = contacts;
for (Contact contact : contacts) {
System.out.printf("%s \t %s \n", contact.getFirstname(), contact.getLastname());
}
}
return new ModelAndView("show_contact", "contactForm", contactForm);
}
ContactForm.java
import java.util.List;
public class ContactForm {
private List<Contact> contacts;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
Contact.java
public class Contact {
private String firstname;
private String lastname;
private String email;
private String phone;
public Contact() {
}
//getters and setters
}

retrieve updated array list from jsp to action class in struts2

I am retrieving database values and putting them in an array list(al). This array list is getting displayed in a JSP page in the form of a table. I want to modify the values in JSP page and update the new value in the database using Struts2. How do i do that?
Main action class
public class HelloWorldAction extends ActionSupport implements SessionAware{
ProjectDb pd;
public ProjectDb getPd() {
return pd;
}
public void setPd(ProjectDb pd) {
this.pd = pd;
}
ArrayList<ProjectDb> al=new ArrayList<ProjectDb>();
public ArrayList<ProjectDb> getAl() {
return al;
}
public String status() throws Exception{
boolean flag=false;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager
.getConnection("jdbc:ucanaccess://D:\\Db1.mdb");
username=(String) map.get("user");
PreparedStatement ps=conn.prepareStatement(
"SELECT * FROM StaleInGers WHERE (((StaleInGers.mailId)=(Select email from DBA where username='"+username+"' and email='"+email+"')))");
//ps.setString(1,username);
//ps.setString(2,password);
ResultSet rs=ps.executeQuery();
al=new ArrayList<ProjectDb>();
while(rs.next()){
pd =new ProjectDb();
pd.setProject(rs.getString("project"));
pd.setStatus(rs.getString("status"));
pd.setComments(rs.getString("comments"));
al.add(pd);
flag=true;
}
} catch (Exception e) {
System.out.println("Exception : " +e);
}
if(flag==true){
return "success";
}
else{
return "error";
}
}
}
This is POJO class
public class ProjectDb {
private String project,status,comments,email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
This is the JSP page where i display the array list
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4
/loose.dtd">
<html>
<head>
<style type="text/css">
table,td,th {
border: 1px solid green;
width:100%;
}
th {
background-color: green;
color: white;
}
</style>
</head>
<body>
<form action="update">
<table >
<tr>
<th>Project</th>
<th>Status</th>
<th>Comments</th>
</tr>
<s:iterator value="al" id="array" status="alStatus">
<tr>
<td><s:property value="%{project}"/></td>
<td><s:textfield name="array[%{#alStatus.index}].status" value="%{status}" theme="simple"
/></td>
<td><s:textfield name="array[%{#alStatus.index}].comments" value="%{comments}" theme="simple"
/></td>
</tr>
</s:iterator>
</table><br><br>
<input style="opacity: 0.7; border-radius: 5px; border: 0; width: 250px;
height:35px;
font-family: Goudy Old Style; font-size: 22px; background: #00CC80;"
type="submit" value="Submit">
</form>
</body>
</html>
The first that comes in mind is making the table fields of input type, and place the values that come from ArrayList on each input value paramether. After this make an update method (like satus() one), and using your pojo's setters update the input values triggering the update method on form action.
It should look something like this:
Update method in HelloWorldAction:
public void update(ProjectDB prjDb) throws Exception{
boolean flag=false;
PreparedStatement ps = null;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager
.getConnection("jdbc:ucanaccess://D:\\Db1.mdb");
conn.setAutoCommit(false);
username=(String) map.get("user");
/*Selecting which field would be updated */
if(!"".equals(prjDb.getEmail().trim())){
ps=conn.prepareStatement(
"UPDATE StaleInGers SET email=? WHERE (((StaleInGers.mailId)=(Select email from DBA where username='"+username+"' and email='"+email+"')))");
ps.setString(1,prjDb.getEmail());
}
//else if(...){...} --> Treat all the cases, if email is not empty, and another field is not empty, if only one field is not empty, etc..
int i = ps.executeUpdate();
conn.commit();
if(i>0){ flag=true; }
}
} catch (Exception e) {
System.out.println("Exception : " +e);
}
if(flag==true){
return "success";
}
else{
return "error";
}
}
//Don't forget to close the connection and prepared statement
The fields must be populated from the array on action that gets you into this page (there you can make the updates) as you did in your JSP. This is the Demo example of the update method but it should work, i let you wrote the rest of the code by yourself.
Use var instead of id (that is deprecated) in the Iterator; in your case, it is not even needed BTW.
Ensure in your target action (update) you have a List<ProjectDb> (use the Interface List, not the implementation ArrayList) named array, with getter/setter;
use an <input type="hidden" /> to send the value that you are showing with <s:property />:
<td>
<s:hidden name="array[%{#alStatus.index}].project" value="%{project}" />
<s:property value="%{project}" />
</td>
Previously I need to pass javascript array to action class of struts 2, i tried with json, var arr1=["1", "2", "3"], in
$.getJSON('ajaxSaveDetails', {
javaArray : JSON.stringify(arr1)
}.fail(function(){
$(".error-txt").text("Error occured");
});
In Action class, i written private String javaArray ; and in method
jsonArray = (JSONArray)new JSONParser().parse(javaArray);
I got proper array.

Struts2 not able to retrieve contained Object used as an attribute in action class

Hi I have created an action class "MyClass" in Struts2 and i want to fetch its instance variable "validationResult" in my jsp file but i am getting null though another instance variable "version" is getting populated.When I am displaying their contents using <s:iterator> tag it is displaying the contents of instance variable "validationResult" also.
Action Class
package my.com;
public class MyClass extends ActionSupport{
private String version;
private List<VersionTO> validationResult;
#Override
public String execute() throws Exception {
validationResult=Arrays.asList(new VersionTO ("abc","def","ghi","jkl"), new VersionTO("mno","pqr","stu","vwx"));
version="212";
return SUCCESS;
}
public String getVersion() {
return Version;
}
public void setVersion(String version) {
this.version = version;
}
public List<VersionTO> getValidationResult() {
return validationResult;
}
public void setValidationResult(List<VersionTO> validationResult) {
this.validationResult = validationResult;
}
}
Bean
pack my.be;
public class VersionTO {
private String server;
private String version;
private String versionOn;
private String compared;
public VersionTO() {
super();
}
public VersionTO(String server, String version,
String versionOn, String compared) {
this.server = server;
this.version = version;
this.versionOn = versionOn;
this.compared = compared;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersionOn() {
return versionOn;
}
public void setVersionOn(String versionOn) {
this.versionOn = versionOn;
}
public String getCompared() {
return compared;
}
public void setCompared(String compared) {
this.comparedVersion = compared;
}
}
JSP
<jsp:useBean id="ver" class="MyClass" scope="page">
<jsp:setProperty name="ver" property="*" />
</jsp:useBean>
<jsp:getProperty name="ver" property="vdVersion"/> <!--here i am getting proper output ie 212-->
<jsp:getProperty name="ver" property="validationResult"/> <!--here i am getting null in the output -->
<%
if (ver.getValidationResult() != null && ver.getValidationResult().isEmpty()) {
%>
<!-- logic for Presentation not working as each time I am getting null in validationResult -->
<%
}
%>
<!-- working fine -->
<s:iterator value="validationResult">
<tr>
<td><s:property value="server" /></td>
<td><s:property value="version" /></td>
<td><s:property value="versionOn" /></td>
<td><s:property value="compared" /></td>
</tr>
</s:iterator>
You need to set a default no args constructor on your object, otherwise Struts2 won't be able to instantiate it.
public VersionTO() {
/* ... stuff ... eg set all to =""; */
}
public VersionTO(String server, String version,
String versionOn, String compared) {
/* ... stuff ... */
}
Read the whole story
EDIT
You don't need all those tags and operations... the action attributes are already on the ValueStack. Just use Struts tags instead of JSP tags and evil scriptlets. Turn your JSP from :
<jsp:useBean id="ver" class="MyClass" scope="page">
<jsp:setProperty name="ver" property="*" />
</jsp:useBean>
<jsp:getProperty name="ver" property="vdVersion"/> <!--here i am getting proper output ie 212-->
<jsp:getProperty name="ver" property="validationResult"/> <!--here i am getting null in the output -->
<%
if (ver.getValidationResult() != null && ver.getValidationResult().isEmpty()) {
%>
<!-- logic for Presentation not working as each time I am getting null in validationResult -->
<%
}
%>
into :
<s:property name="version"/> <!--WARNING ! In your Action class it is version... "vdVersion" may be a typo-->
<s:if test=%{validationResult!=null">
<!-- now the logic for Presentation will work, for example : -->
<s:iterator value="validationResult" status="stat">
<tr>
<td><s:property value="server" /></td>
<td><s:textfield name="validationResult[%{#stat.index}].version" /></td>
<td><s:property value="versionOn" /></td>
<td><s:property value="compared" /></td>
</tr>
</s:iterator>
</s:if>

Function must be used with aprefix -jsp

I have similar problem asked here The function " " must be used with a prefix when a default namespace is not specified . But my context is different.
I have Spring web app which contains a jsp that gets arraylist of Objects created (using helping class) from controller and these object values are rendered in a table. My Controller, Jsp page, and Helping class are as follows
Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home( Model model) {
logger.info("Welcome home! the client locale is ");
ArrayList<TrendSign> ts=new ArrayList<TrendSign>();
for(int i=0;i<5;i++)
{
TrendSignDAO actor = new TrendSignDAO();
actor.setPhrase("phrase"+i);
actor.setHitCount(i);
actor.setWordCount(i);
actor.setCharCount(i);
ts.add(actor);
}
model.addAttribute("ts", ts );
return "home";
}
}
JSP Page is as follows:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>Phrase</th>
<th>hit count</th>
<th>wordcount</th>
<th>char count</th>
</tr>
</thead>
<tbody>
<c:forEach var="row" items="${ts}">
<tr class="odd gradeX">
<td><c:out value="${row.getPhrase()}"/></td>
<td><c:out value="${row.getHitCount()}"/></td>
<td><c:out value="${row.getWordCount()}"/></td>
<td><c:out value="${row.getCharCount()}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
Helping class
public class TrendSign {
private String phrase;
private int hitCount;
private int wordCount;
private int charCount;
public void setPhrase(String phrase)
{
this.phrase = phrase;
}
public String getPhrase()
{
return (this.phrase);
}
public void setHitCount(int hitCount)
{
this.hitCount = hitCount;
}
public int getHitCount()
{
return (this.hitCount);
}
public void setWordCount(int wordCount )
{
this.wordCount = wordCount;
}
public int getWordCount()
{
return (this.wordCount);
}
public void setCharCount(int charCount )
{
this.charCount = charCount;
}
public int getCharCount()
{
return (this.charCount);
}
public TrendSignDAO() {
// TODO Auto-generated constructor stub
this.phrase = "Phrase";
this.hitCount = 5;
this.wordCount = 1;
this.charCount = 1;
}
}
This working fine in my local host (java 6 Tomcat 6) But when I deployed to jelastic(java 6 Tomcat 6), getting the error WEB-INF/views/home.jsp(26,8) The function getPhrase must be used with a prefix when a default namespace is not specified. The url to access the web app at jelastic is http://lovedmusic.jelastic.servint.net/. Can anyone help me how to debug this?
Your DAO doesn't quite look like a DAO, but nevertheless, using JSP-EL, you should be able to access your getters without the method syntax. Just use the property name:
<td><c:out value="${row.phrase}"/></td>
<td><c:out value="${row.hitCount}"/></td>
<td><c:out value="${row.wordCount}"/></td>
<td><c:out value="${row.charCount}"/></td>

Categories

Resources