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>
Related
In my Maven-based MVC Springframework project, I have a class named Rentals, which I've mapped to a PostgreSQL table of the same name. In it, I've configured the Id to be a Serial int, which increments automatically for every new entry.
My question is: How do I make it so that Spring knows that if it saves a new Rental object, it saves it with its predestined id?
Here is my Rentals java:
#Entity
#Table(name = "rentals")
public class Rentals implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
#SequenceGenerator(name="rentals_id_seq", sequenceName="rentals_id_seq", allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator="rentals_id_seq")
private int id;
// Other column data
// Empty, only id, full and all except id constructors
// Getters and setters, hashcode, equals and tostring
}
My DAO implementation is very simple, which implements from a simple DAO interface and uses a private SessionFactory sessionFactory to realize the CRUD operations.
My Service implementation is also very simple, which implements a Service interface (which is an exact copy of the DAO interface) and uses a private MurDao murDao to realize the CRUDs.
This is my Controller:
#Controller
public class MurController {
private MurService murService;
#Autowired(required = true)
#Qualifier(value = "murService")
public void setMurService(MurService murService) {
this.murService = murService;
}
// other CRUDs for other entities
#RequestMapping(value = "/rentals", method = RequestMethod.GET)
public String listRentals(Model model) {
model.addAttribute("rental", new Rentals());
model.addAttribute("listUsers", this.murService.getUsers());
model.addAttribute("listMovies", this.murService.getMovies());
model.addAttribute("listRentals", this.murService.getRentals());
return "rental";
}
#RequestMapping(value = "/rentals/add", method = RequestMethod.POST)
public String addRental(#ModelAttribute("rental") Rentals rnt) {
try {
this.murService.getRental(rnt.getId());
this.murService.updateRental(rnt);
} catch (ObjectNotFoundException ex) {
this.murService.addRental(rnt);
}
return "redirect:/rentals";
}
#RequestMapping("/rentals/remove/{id}")
public String removeRental(#PathVariable("id") int id) {
this.murService.deleteRental(id);
return "redirect:/rentals";
}
#RequestMapping("/rentals/edit/{id}")
public String editRental(#PathVariable("id") int id, Model model) {
model.addAttribute("rental", this.murService.getRental(id));
model.addAttribute("listRentals", this.murService.getRentals());
return "rental";
}
}
Finally, the .jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<html><head><title>Rental Page</title><style type="text/css">.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}.tg .tg-4eph{background-color:#f9f9f9}</style></head>
<body>
<c:url var="addAction" value="/rentals/add" ></c:url>
<form:form action="${addAction}" modelAttribute="rental">
<table>
<tr><td>
<form:label path="iduser">
<spring:message text="ID User"/>
</form:label></td><td>
<form:select path="iduser">
<form:options items="${listUsers}" itemValue="id" itemLabel="fullName"/>
</form:select>
</td></tr><tr><td>
<form:label path="idmovie">
<spring:message text="ID Movie"/>
</form:label></td><td>
<form:select path="idmovie">
<form:options items="${listMovies}" itemValue="id" itemLabel="title"/>
</form:select>
</td></tr><tr><td>
<form:label path="dateof">
<spring:message text="Date Of"/>
</form:label></td><td>
<form:input path="dateof" cssClass="form-control"/></td><td>
<spring:message text="Please use dd-mm-yyyy" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message text="Add Rental"/>" />
</td>
</tr>
</table>
</form:form> <br> <h3>Rentals List</h3>
<c:if test="${!empty listRentals}"><table class="tg"><tr>
<th>ID User</th>
<th>ID Movie</th>
<th>Date Of</th>
<th width="60">Delete</th>
</tr><c:forEach items="${listRentals}" var="rental"><tr>
<td>${rental.iduser}</td>
<td>${rental.idmovie}</td>
<td>${rental.dateof}</td>
<td><a href="<c:url value='/rentals/remove/${rental.id}'/>" >Delete</a></td>
</tr>
</c:forEach>
</table></c:if></body></html>
What is currently happening is that, whenever I set some information in the "add new rental" button, the .jsp sends through a new Rental Object, but it has an id of 0. I don't want this, I want to create a new Rental with an id of Null or something like that so that spring knows that it has to wait to know what number of id to give it given it is auto-generated and self-incremental.
How do I approach this? Why does the jsp sends through an object with id 0? Any and all help is appreciated!
As Alan Hay commented, an int primitive cannot be null. And it was exactly what I needed. Just after I switched all ints that deal with my Rental's id, this happened.
Información: Rentals{id=null, iduser=testUser01, idmovie=testMovie01, dateof=Tue Jan 01 00:01:00 CST 2019}
Información: Hibernate: select nextval ('rentals_id_seq')
Información: Hibernate: insert into rentals (dateof, iduser, idmovie, id) values (?, ?, ?, ?)
And it was saved to my database. Thanks a lot, Alan Hay!
Problem solved, thanks guys ;) I EDITED THE CODE, LOOK AT THE BOTTOM
I am a Spring newbie and I am a little bit confused about using an object I already created through different controller in Spring MVC. I wrote a simple project that allow user to insert some car's details(brand, model and license plate number) and to see the list of submitted records (plus a reset all action and a selective delete of a single record). Now I also want to edit the values of a record but things get tough for me..
VeicoloController.java
#Controller
#RequestMapping("/veicolo")
#SessionAttributes("veicoli")
public class VeicoloController {
#Autowired VeicoloValidator veicoloValidator;
#GetMapping({"", "lista"})
public String lista() {
return "/veicolo/lista_veicoli";
}
#GetMapping("inserisci_veicolo")
public ModelAndView inserisci(){
return new ModelAndView("veicolo/inserisci_veicolo", "modelVeicolo", new Veicolo());
}
#PostMapping("save")
public ModelAndView salvaVeicolo(#ModelAttribute("modelVeicolo") Veicolo veicolo, BindingResult bindingResult,Model model)
{
System.out.println("Veicolo = " + veicolo);
veicoloValidator.validate(veicolo, bindingResult);
if (bindingResult.hasErrors()){
return new ModelAndView("veicolo/inserisci_veicolo");
}
else{
Set<Veicolo> veicoli;
if (!model.containsAttribute("veicoli")){
veicoli = new HashSet<>();
model.addAttribute("veicoli", veicoli);
}
else{
veicoli = (Set<Veicolo>) model.asMap().get("veicoli");
}
veicoli.add(veicolo);
return new ModelAndView("veicolo/lista_veicoli");
}
}
Now, here there are my problematic Controllers:
I use this controller to edit the row, using the license plate number as unique element to retrieve that particular vehicle object and passing it by querystring from the jsp(i'll show it later). In this way i can show the vehicle attribute in the edit forms (and hiding the license plate number form that cannot be modified)
#GetMapping("modifica")
public ModelAndView modificaVeicolo(#RequestParam("targa")String targa, Model model){
Set<Veicolo> veicoli = (Set<Veicolo>)model.asMap().get("veicoli");
Veicolo veicoloMod = null;
for(Veicolo v:veicoli){
if(v.getTarga().equalsIgnoreCase(targa)){
veicoloMod = v;
break;
}
model.addAttribute(veicoloMod);
}
return new ModelAndView("veicolo/modifica_veicolo", "modelVeicolo", veicoloMod);
}
This is how I tried to do the update Controller, I really don't know how to use the object I got in the previous controller that give me (i suppose) all the information I need of the car
#PostMapping("update")
public ModelAndView updateVeicolo(#ModelAttribute("modelVeicolo")Veicolo veicolo, BindingResult bindingResult,Model model)
{
// Veicolo veicoloToUpdate = (Veicolo)model.asMap().get("veicoli");
veicoloValidator.validate(veicolo, bindingResult);
if (bindingResult.hasErrors())
{
return new ModelAndView("veicolo/modifica_veicolo");
}
else
{
Set<Veicolo> veicoli =(Set<Veicolo>)model.asMap().get("veicoli");
veicoli.add(veicolo);
}
return new ModelAndView("veicolo/lista_veicoli");
}
modifica_veicolo.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Modifica il veicolo</title>
</head>
<body>
<h1>Modifica il veicolo</h1>
<br>
<br>
<form:form method="POST" action="${pageContext.request.contextPath}/veicolo/update" commandName="modelVeicolo" ModelAttribute="modelVeicolo">
<table>
<tr>
<p class="errorLine">
<form:errors path="marca" cssStyle="color: #ff0000"/>
</p>
<td><form:label path="marca">Marca</form:label></td>
<td><form:input path="marca" /></td>
</tr>
<tr>
<p class="errorLine">
<form:errors path="modello" cssStyle="color: #ff0000"/>
</p>
<td><form:label path="modello">Modello</form:label></td>
<td><form:input path="modello"/></td>
</tr>
<td><form:input type="hidden" path="targa" value="${veicolo.targa}" /></td>
<tr>
<td colspan="3">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
<br>
<br>
Torna alla Home
</body>
</html>
and lista_veicoli.jsp (from the list you can edit the record)
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Lista veicoli</title>
</head>
<body>
<h1>Lista Veicoli</h1>
<br>
<br>
<c:if test="${veicoli == null || veicoli.isEmpty()}">
Nessun veicolo registrato.
</c:if>
<div> </div>
<table>
<thead>
<tr>
<th>| Marca </th>
<th>| Modello |</th>
<th> Targa |</th>
</tr>
</thead>
<c:forEach var="veicolo" items="${veicoli}">
<tr>
<td>
${veicolo.marca}
</td>
<td>
${veicolo.modello}
</td>
<td>
${veicolo.targa}
</td>
<td>
<a href="${pageContext.request.contextPath}/veicolo/modifica?targa=${veicolo.targa}" > modifica </a>
</td>
<td>
<a href="${pageContext.request.contextPath}/veicolo/rimuovi?targa=${veicolo.targa}" > elimina </a>
</td>
</tr>
</c:forEach>
</table>
<br>
<br>
<p>Torna alla Home |</p>
<p>Cancella Lista |</p>
<p>Inserisci un altro veicolo |</p>
</body>
</html>
I am stuck now, if I click on the update button nothing happen and I doubt that things can be done way too better than this. I need your help :'(
Also, sorry for the long post!
EDIT:
ok, i changed this controller and it seems to work, but only for the first record inserted!
#PostMapping("update")
public ModelAndView updateVeicolo(#ModelAttribute("modelVeicolo")Veicolo veicolo,
BindingResult bindingResult,Model model)
{
veicoloValidatorNoTarga.validate(veicolo, bindingResult);
if (bindingResult.hasErrors())
{
return new ModelAndView("veicolo/modifica_veicolo");
}
else
{
Set<Veicolo> veicoli =(Set<Veicolo>)model.asMap().get("veicoli");
Veicolo daInserire = veicolo;
Veicolo daRimuovere = null;
for(Veicolo v : veicoli)
{
if(v.getTarga().equalsIgnoreCase(veicolo.getTarga())){
daRimuovere = v;
break;
}
}
veicoli.remove(daRimuovere);
veicoli.add(daInserire);
}
return new ModelAndView("veicolo/lista_veicoli");
}
If i want to edit the second or more element of the set an exception occurs. It says "HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Model object must not be null".
In fact in the modificaVeicolo Controller at the line
for(Veicolo v:veicoli){
if(v.getTarga().equalsIgnoreCase(targa)){
veicoloMod = v;
break;
}
targa value is the correct value of the second or third(etc) car, but v has the value of the first car's license plate! In theory it should have the value of the selected car
...any suggestions?
Key Point::If you choose to use HashSet storing Objects,the Class has to override equals and hashcode!
1.Veicolo.java
Override equlas and hashcode
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Veicolo veicolo = (Veicolo) o;
return targa.equals(veicolo.getTarga());
}
#Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + getTarga().hashCode();
return result;
}
2.VeicoloController.updateVeicolo()
Update object By deleting and adding
#PostMapping("update")
public ModelAndView updateVeicolo(#ModelAttribute("modelVeicolo") Veicolo veicolo, BindingResult bindingResult,
Model model) {
// Veicolo veicoloToUpdate = (Veicolo)model.asMap().get("veicoli");
veicoloValidator.validate(veicolo, bindingResult);
if (bindingResult.hasErrors()) {
return new ModelAndView("veicolo/modifica_veicolo");
} else {
Set<Veicolo> veicoli = (Set<Veicolo>) model.asMap().get("veicoli");
if (veicoli.contains(veicolo)) {
veicoli.remove(veicolo);
veicoli.add(veicolo);
}
}
return new ModelAndView("veicolo/lista_veicoli");
}
3.VeicoloController.modificaVeicolo()
Move the model.addAttribute into the loop
#GetMapping("modifica")
public ModelAndView modificaVeicolo(#RequestParam("targa") String targa, Model model) {
Set<Veicolo> veicoli = (Set<Veicolo>) model.asMap().get("veicoli");
Veicolo veicoloMod = null;
for (Veicolo v : veicoli) {
if (v.getTarga().equalsIgnoreCase(targa)) {
veicoloMod = v;
model.addAttribute(veicoloMod);
break;
}
}
return new ModelAndView("veicolo/modifica_veicolo", "modelVeicolo", veicoloMod);
}
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
}
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>
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.