How do I set a String variable using inputText in JSF? - java

I have a flow.xml file that's calling a method on a bean. I just want to have a string that I get from a textbox passed in as a parameter to the method. I've added a h:inputText to my xhtml page, but I can't get it to set a String variable in the corresponding flow. What is the simplest possible way I can get a value from a textbox into a flowscope String variable?

public class SomeBean{
String val;
//getters & setters
public String foo(){
System.out.println(val);
return "SUCCESS";
}
}
xhtml
<h:form>
<h:inputtext value="#{someBean.val}"/>
<h:commandButton action="#{someBean.foo}"/>
</h:form>
as html it will render a html form with a textbox and a submit button on licking button it will call foo() and text from txtbox will get binded to val

MyBean myBean = (MyBean) facesContext.getApplication().createValueBinding("#{flowScope.myBean}").getValue(facesContext);
String val = myBean.GetBeanProperty();
Here you should
more examples.

Related

pass form values in managed bean

i want to pass my form value into my managed bean in order to process it but i always got a null value when i try to retrieve the value in my action method
My bean
#ManagedBean(name="datas")
#SessionScoped
public class Datas implements Serializable {
private static final long serialVersionUID = 1L;
private String ID_primary;
public Datas(){
}
public Datas (String ID_primary){
this.ID_primary=ID_primary;
}
public String getID_primary() {
return ID_primary;
}
public void setID_primary(String ID_primary) {
this.ID_primary= ID_primary;
}
public void process() {
Map<String, String> request=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String value = request.get("ID_primary"); // always return null
System.out.println("ID" + value);
}
}
My form
<h:form>
<div align="left">
<h:inputText id="ID_primary" name="ID_primary" value="#{datas.ID_primary}" />
</div>
..........
<div align="right">
<h:commandButton action="#{datas.process()}" value="Create" type="submit" />
</div>
</h:form>
Thank you very much for your help
You have two different form elements, when you click commandButton in the bottom form, values from the top form are not send with the request.
You can have tags like div inside a form, so you can make on big form with divs inside if it is the reason why you have have split them.
Also add #ManagedProperty annotation to ID_primary field:
public class Datas implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty(value = "#{Datas.ID_primary}")
private String ID_primary;
[..]
EDIT:
Ok, my bad, I have not looked at the code carefully. In ManagedBean with ManagedProperty this property will be set automatically by JSF, so you can read it like this:
public void process() {
System.out.println("ID" + getID_primary());
}

jsf : passing a selected hyperlink as a query argument

I have a mySql table of PROJECTS, which I am displaying as a list in the index.xhtml. The projectid column contains hyperlinks. When they're clicked I would like the specific projectid row selected to be passed as the query argument into another jsf file (ListProjects.xhtml) which displays all the project values referring to the projectid selected in the index.xhtml. The index.xhtml page seems to pass the values correctly (when hovering over the selection the url displays the right id value). When actually clicking the selction I get a blank page in the resulting ListPprojects.xhtml:
I'm not sure if it's my choice of tags on index.xhtml where should be replaced by another tag like CommandLink which maps to a bean action.
Alternatively, is tag in the result page (ListProject.xhtml) the right tag to use to retrieve the projectid value as the query argument?
Also if the projectid is an int, should this first be converted to String by using parseInt or other method?
Is the problem in one of the session beans where projectid is resulting in a null value which causes the result page to render blank records? Any advice is greatly appreciated. Thanks in advance!
The named query in the entity bean (projects.java) is:
#NamedQuery(name = "Projects.findByProjectid", query = "SELECT p FROM Projects p WHERE p.projectid = :projectid")
In the index.xhtml I use the following tag to display the hyperlink:
<h:link value="#{item.projectid}" outcome="ListProject">
<f:param name="projectid" value="#{item.projectid}"/>
</h:link>
The ListProjects.xhtml is the page where I would like to display the project details based on the projectid selected in the index.xhtml (and here's where I start getting confused):
<h:column>
<f:facet name="header">
<h:outputText value="Countryid"/>
</f:facet>
<h:commandLink action="#{selProjectMgtBean.selProjectList}" value="#{item.projectid}"/>
</h:column>
My session bean:
#Stateless
public class ProjectSelectedBean implements ProjectSelectedBeanLocal {
#PersistenceContext(unitName = "QueryTrialNoMavenPU")
private EntityManager em;
#Override
public List<Projects> getSelectedProjects(String projectid) {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
projectid=request.getParameter(projectid);
return em.createNamedQuery("Projects.findByProjectid", Projects.class).setParameter ("projectid", projectid).getResultList();
}
}
Finally the calls the methods for rendering the selection:
package com.manaar.beans;
imports....
#Named(value = "selProjectMgtBean")
#RequestScoped
public class SelProjectMgtBean {
#ManagedProperty(value="#{item.projectid}")
private String projectid;
private List<Projects> selProjectList;
#EJB
private ProjectSelectedBeanLocal projectSelectedBeanLocal;
#PostConstruct
public void init() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance ().getExternalContext().getRequest();
projectid=request.getParameter("projectid");
selProjectList = projectSelectedBeanLocal.getSelectedProjects();
}
public List<Projects> getSelProjectList() {
return selProjectList;
}
public void setSelProjectList(List<Projects> selProjectList) {
this.selProjectList = selProjectList;
}
}
you didn't set :projectId in query:
you can change code as follow:
public List<Projects> getSelectedProjects(String projectId) {
return em.createNamedQuery("Projects.findByProjectid", Projects.class).setParameter("projectId" , projectId).getResultList();
}
Regarding one of your questions:
Use h:link for pure navigational purposes (with the outcome parameter) and h:commandLink to invoke an action directly (with the action parameter). The called method in this case should return a String telling JSF where to navigate next.

How can i get value from <h:selectManyCheckbox>

I have one collection , which I'm displaying in my .xhtml page by <h:dataTable>. I want to reach a few goals: at first I want to set list.check value by <h:selectManyCheckbox>, at second I want whatever the values remains selected until the end of current session. Now It displays correctly, but when I select some value it doesn't transmit it in list.check property. I'm using JSF v.2.2.
Code in JSF bean:
private List<AnswerDTO> answerListDto;
//getters and setters
Code in .xhtml
<h:form>
<h:dataTable value="#{main.answerListDto}" var="list">
<h:column>
<h:selectManyCheckbox value="#{list.check}">
<f:selectItem itemValue="1" itemLabel="#{list.ansValue}" />
</h:selectManyCheckbox>
</h:column>
</h:dataTable>
</h:form>
AnswerDTO class:
public class AnswerDTO implements Serializable, DTO {
private static final long serialVersionUID = 1L;
private Integer id;
private Question questId;
private String ansValue;
private String ansStatus;
private String check;
//getters and setters
}
Strange use of selectManyCheckbox I must say. Concrete problem is that value of selectManyCheckbox must be an array.
My opinion is that selectBooleanCheckbox should be used instead of selectManyCheckbox. Your check property can have only two values, an empty array (if checkbox is not selected), and array of length 1 with value which is equal to ansValue (if checkbox is selected).

struts2. Object fron jsp to action

First of all I'm newbie in Struts.
I've a class:
public class Articulo {
private int codigo;
private String descripcion;
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
}
which is populated with values in a dispatcher. In the dispatcher I've
private Articulo articulo;
.......
public Articulo getArticulo() {
return articulo;
}
public void setArticulo(Articulo articulo) {
this.articulo = articulo;
}
There is also a JSP with
<s:property value="articulo"/>
which read ok the articulo. Also works articulo
<s:property value="articulo.codigo"/>
But now I want from that jsp forward the entire object articulo to another action.
I can do
<s:hidden name="articulo.codigo" value="%{articulo.codigo}"/>
<s:hidden name="articulo.descripcion" value="%{articulo.descripcion}"/>
and that works fine, but is there anyway to do something like
<s:hidden name="articulo" value="%{articulo}"/>
So, is there anyway to get the object from JSP without setting all the properties of it?
there are 2 points:
Problem: you can't transfer object using <s:hidden />, all the parameter, what are transfered with HTTP should be string. Since you cannot convert this object to String, you can't transfer it using HTTP either.
Solution: You can put your object into session, so that you can access it anytime you want. here is an EXAMPLE
Yes, you can transfer object in two ways either by parameter or store it in session and access it whenever you need it.
<jsp:forward page="URL" >
<jsp:param name="ParamName1" value="YourObject" />
</jsp:forward>
Visit here for more detail.
http://www.gulland.com/courses/jsp/actions/forward
Keeping the object information in sessions is usually the preferred method.
But an alternative option is to create your own Type Converter.
Create a type converter by extending StrutsTypeConverter. The
Converter's role is to convert a String to an Object and an Object to
a String.
By doing so, you could so something like <s:hidden name="articulo" value="%{articulo}"/>
Keep in mind this method is insecure as the object values will be printed out as String in the hidden tag and can be seen through the browser.
But the advantage is that this method works across different sessions if you have a need for such a thing.

Why validation message is not displayed for a selectOneMenu component(JSF 2)?

I use this class for doing validation from input fields:
#ManagedBean
#RequestScoped
public class UserInputValidation {
public void validateCity(FacesContext context, UIComponent validate,
Object value) {
String inputFromField = (String) value;
if (inputFromField.equals("") || inputFromField.equals(" ")) {
FacesMessage msg = new FacesMessage("Odaberite grad");
throw new ValidatorException(msg);
}
}
//...
}
And this is the managed bean that holds the inputed values:
#ManagedBean
#RequestScoped
public class InputController {
//Attributes
private String city;
//Get set methods
Why when i create a selectOneComponent and i select the first component(blank input), the validation message is not shown?
<h:selectOneMenu id="city" value="#{inputController .city}">
<f:selectItems value="#{searchController.formatedCities()}" validator="#{userInputValidation.validateCity}"/>
</h:selectOneMenu>
<span style="color: red;"><b><h:message for="city"
showDetail="true" /></b></span>
The first of the fields in the selectOneMenu is a blank(The formatedCitiesMethod() returns a "" as first element), so why the validation message is not being shown if the form is submit button is clicked with the blank selected?
The validator attribute has to go in the <h:selectOneMenu>, not in the <f:selectItems>
Said that, why don't you just use required="true"? Why is the validator a #ManagedBean instead of a #FacesValidator?

Categories

Resources