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>
Related
I have the following class users.java:
package org.XY;
public class user {
private String mail;
private String name;
private String org;
private String pw;
private String admin;
public user (String mail,String name,String org, String pw, String admin){
this.mail=mail;
this.name=name;
this.org=org;
this.pw = pw;
this.admin = admin;
}
public String getMail() {
return this.mail;
}
public String getName() {
return this.name;
}
public String getOrg() {
return this.org;
}
public String getPw() {
return this.pw;
}
public String getAdmin() {
return this.admin;
}
public String getUser() {
String u = this.mail + " | " + this.name + " | " + this.org + " | " + this.pw + " | Is admin:" + this.admin;
return u;
}
}
And the following jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import="org.XY" %>
<%# page import="java.util.List" %>
<%#page isELIgnored="false"%>
<html>
<head>
<title>myservlet</title>
</head>
<body>
<%--<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.getMail()}" /></td>
<td><c:out value="${user.getName()}" /></td>
<td><c:out value="${user.getOrg()}" /></td>
<td><c:out value="${user.getPw()}" /></td>
<td><c:out value="${user.getAdmin()}" /></td>
</tr>
</c:forEach>--%>
<%
List<user> users = (List<user>) request.getAttribute("users");
for (user user : users) {
%>
${user.mail}
<%
}
%>
<%
for (user user : users) {
out.println("<li>" + user.getPw());
}
%>
...
I want to create a table which contains all the data from the users.
As you can see, I tried using the ${user.mail} method with el.
Both give me an javax.el.PropertyNotFoundException: No public static field named [mail] was found on class [org.isse.sopro.user] error and an java.lang.NoSuchFieldException: mail error.
I already tried renaming the getter methods but it did not solv the issue.
Could someone tell me what I am diong wrong?
Regards
Andi
UPDATE:
Obviously it wasn't about the program itself, it was about maven. After a complete reload from Intellij, maven reloaded the project and everything worked fine.
You can not use ${user.mail} because of did not implements Serializable
You need change user class implements Serializable
public class user implements Serializable{
}
And you can use ${user.mail} instead of ${user.getMail()}
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.mail}" /></td>
</tr>
</c:forEach>
Try this
<%--<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.mail}" /></td>
<td><c:out value="${user.name}" /></td>
<td><c:out value="${user.org}" /></td>
<td><c:out value="${user.pw}" /></td>
<td><c:out value="${user.admin}" /></td>
</tr>
</c:forEach>--%>
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>
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>
I have to display several links in a JSP and the structure of the HTML is the equal for every link, so I've used an struts2 taglib iterator to build it. The problem is that I don't know how to build the link itself:
My JSP
<%# taglib prefix="s" uri="/struts-tags"%>
<head></head>
<div class="menuBotoes">
<s:iterator value="links" var="link">
<s:a namespace="link.nameSpace" action="link.action">
<table cellpadding="0" cellspacing="0" class="tableBotaoMenu">
<tr class="trCimaBotaoMenuSelect">
<td align="center" class="imagemBotaoMenuSelect"><img src="<s:url value="/includes/imagens/global/botoes/grafico.png" />" /></td>
<td align="left" class="descricaoBotaoMenuSelect"><s:property value="textoLink" /></td>
</tr>
<tr class="trBaixoBotaoMenuSelect">
<td align="center" class="imagemBotaoMenuSelect" colspan="2"><s:property value="projeto" /></td>
</tr>
</table>
</s:a>
</s:iterator>
</div>
The object that is being iterated over in the JSP is this:
public enum LinksRelatorios {
1("Caixa Visita", "/relatorios/", "iniciarRelatorioCaixaVisita", "TISS"),
2("Caixa Visita Empresa", "/relatorios/", "iniciarRelatorioCaixaVisitaEmpresa", "TISS"),
3("Produtividade Internação Domiciliar", "/relatorios/", "iniciarRelatorioInternacaoDomiciliar", "TISS"),
4("Pendências", "/relatorios/", "iniciarRelatorioPendencias", "TISS"),
5("Solicitação Inicial", "/relatorios/", "iniciarRelatorioSolicitacaoInicial", "TISS"),
6("Solicitação Prorrogação", "/relatorios/", "iniciarRelatorioSolicitacaoProrrogacao", "TISS"),
7("Tempo Resposta", "/relatorios/", "iniciarRelatorioTempoResposta", "TISS");
private String textoLink;
private String nameSpace;
private String action;
private String projeto;
private LinksRelatorios(final String textoLinkParam, final String nameSpaceParam, final String actionParam,
final String projetoParam) {
this.textoLink = textoLinkParam;
this.nameSpace = nameSpaceParam;
this.action = actionParam;
this.projeto = projetoParam;
}
public String getTextoLink() {
return this.textoLink;
}
public String getNameSpace() {
return this.nameSpace;
}
public String getAction() {
return this.action;
}
public String getProjeto() {
return this.projeto;
}
}
My Action
#Controller
#Scope("request")
public class InicioAction extends BaseAction {
private static final long serialVersionUID = -1161409943678292285L;
private static final LinksRelatorios[] links = LinksRelatorios.values();
public String inicio() {
this.addActionMessage(this.getText("msg.sucesso.saudacao.mensagem", new String[] { (String) BaseAction
.getSession().getAttribute(Constantes.PERFIL) }));
return Action.SUCCESS;
}
public String iniciarRelatoriosPorProjeto() {
return Action.SUCCESS;
}
public String iniciarRelatoriosFiltro() {
return Action.SUCCESS;
}
public static LinksRelatorios[] getLinks() {
return InicioAction.links;
}
}
I've tried using
<s:a namespace="link.nameSpace" action="link.action">, < s:a namespace="%{link.nameSpace}" action="%{link.action}">, <s:a namespace="#link.nameSpace" action="#link.action">, but not seems to work.
Before someone asks, the enum is working fine, in my JSP I have <s:property value="projeto" /> and <s:property value="textoLink" /> and these are properties that come from the enum.
I've read the online official docs in http://struts.apache.org/release/2.3.x/docs/using-struts-2-tags.html, http://struts.apache.org/release/2.3.x/docs/a.html and http://struts.apache.org/release/2.3.x/docs/url.html but the examples sections is actually pretty poor comparing to frameworks such as PrimeFaces or RichFaces that have built theirs own showcases.
Use the below code
<s:a namespace="%{#link.nameSpace}" action="%{#link.action}">
Use of %{} makes struts2 evaluate the contents of the expression inside {} and then assign the result to the attribute.
Refer http://struts.apache.org/release/2.0.x/docs/tag-syntax.html for more details.
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.