pass form values in managed bean - java

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

Related

How to prepopulate a form in Stripes?

I have a Stripes form using an Action bean.
I can store the data without any problem out of the form, but I did not find out how to prepopulate the form's data.
I have simplified my example to show what's not working.
My code under #Before is without any effect: the data dont go into the form.
How should I manage this approach?
myform.jsp:
...
<stripes:form beanclass="UserActionBean">
...
<stripes:text name="user" />
<stripes:submit name="store" value="Save" />
...
</stripes:form>
...
ActionBean:
public class UserActionBean implements ActionBean {
private String user;
#Before
public void init() {
user = "myuser";
}
#DefaultHandler
public Resolution store() {
...
}
}
You will need public getters and setters for Stripes to be able to read the value.
Although usually I would use the #DefaultHandler for the get, and then create a new handler for the save e.g. #HandlesEvent(value = "save") public Resolution save () {...
This might be crude, but I used a getter like Scary Wombat said and initialized the variable in the ActionBean. Or you could set its value in your handler that does the initial page display.
#Validate(required = true, on = {
"proceed"
})
private String tumblrUrl= "xyz.tumblr.com";
...
public String getTumblrUrl() {
return this.tumblrUrl;
}
public void setTumblrUrl(final String tumblrUrl) {
this.tumblrUrl = tumblrUrl;
}

JSF/JPA value binding expression not setting entity bean's property

I am learning JSF/EJB and I have run into a problem.
I am trying to write a code that takes a string from user and store that string to database.
Here's my code:
Entity bean:
#Entity
public class TestTable implements Serializable {
private static final long serialVersionUID = 1L;
public TestTable() {
super();
}
#Id
#GeneratedValue
private int firstcolumn;
private String secondcolumn;
private String testphrase = "test phrase";
public String getTestphrase() {
return testphrase;
}
public void setTestphrase(String testphrase) {
this.testphrase = testphrase;
}
public int getFirstcolumn() {
return firstcolumn;
}
public void setFirstcolumn(int firstcolumn) {
this.firstcolumn = firstcolumn;
}
public String getSecondcolumn() {
return secondcolumn;
}
public void setSecondcolumn(String secondcolumn) {
this.secondcolumn = secondcolumn;
}
}
Table has three columns, first column is primary key, second column stores string entered by user and third column stores "test phrase".
Controller bean:
#Named
public class TestController implements Serializable {
private static final long serialVersionUID = 1L;
#EJB
DataAccess dacc;
#Inject
TestTable testTable;
public TestController()
{
}
public TestTable getTestTable() {
return testTable;
}
public void setTestTable(TestTable testTable) {
this.testTable = testTable;
}
public void test()
{
System.out.println("string secondcolumn= "+ testTable.getSecondcolumn());
dacc.addtodb(testTable);
}
}
I used System.out.println("string secondcolumn= "+ testTable.getSecondcolumn()); in method test() to check data before it is written to database. My problem is, it is always null. Output in console :
INFO :string secondcolumn= null .
secondcolumn is not set by value binding expression in JSF.
Now, JSF:
<h:outputText value="Second column:">
</h:outputText>
<h:inputText label="Second column" value="#{testController.testTable.secondcolumn}">
</h:inputText>
<h:outputText value="#{testController.testTable.getTestphrase()}">
</h:outputText>
<h:commandButton action="#{testController.test}" value="Save">
</h:commandButton>
I checked database and rows are being added. Entries in Column SECONDCOLUMN are NULL.
Entries in TESTPHRASE are "test phrase". I get no error messages and I have tried everything I can to solve the problem and now I am stuck. Any feedback are welcome.
Your problem is that you're injecting an entity class. The best will be initializing it manually using the new keyword, retrieving the entity from database, etc. One way to do this would be using a #PostConstruct method in your CDI bean:
#Named
//here you should define the scope of your bean
//probably #RequestScoped
//if you're working with JSF 2.2 there's already a #ViewScoped
public class TestController implements Serializable {
private static final long serialVersionUID = 1L;
#EJB
DataAccess dacc;
//this musn't be injected since it's not a business class but an entity class
//#Inject
TestTable testTable;
public TestController() {
}
#PostConstruct
public void init() {
//basic initialization
testTable = new TestTable();
}
//rest of your code...
}
With this change, JSF will be able to set the values from the <h:form> into the bounded fields. Note that JSF code will just invoke the necessary getters and setters accordingly to the defined in your EL, it won't create a new instance of the bounded fields. The getters are invoked when generating the view and the setters when submitting the form to the server.
More info:
Creating new entities while enabling injection
Why use #PostConstruct?
StackOverflow Expression Language wiki

javax.servlet.jsp.JspException: No getter method for property

I am unable to find out what I am doing wrong. I am bound to use Form Bean within Form Bean as there are numerous different parts of the form. Basically, there is a response part as well as request part on the same form.
While initializing the view, I am getting a no getter method exception.
I am using Struts 1.2
javax.servlet.jsp.JspException: No getter method for property getAvailableAddres
sRequest.resellerId of bean org.apache.struts.taglib.html.BEAN
at org.apache.struts.util.RequestUtils.lookup(RequestUtils.java:968)
struts-config.xml:
<form-beans>
<form-bean name="getAvailableAddress" type="com.wisor.talktalk.model.GetAvailableAddress" />
<form-bean name="provideRequest" type="com.wisor.talktalk.common.talktalkbean.RequestActionForm" />
</form-beans>
<action-mappings>
<action path="/ttTestJsp" type="com.wisor.talktalk.controller.TestJsp"
name="getAvailableAddress"
scope="session"
validate="false"
unknown="false">
<forward name="init" path="/WEB-INF/talk/preorderView/getAvailableAddress.jsp"/>
</action>
</action-mappings>
JSP Page:
<html:form action="/ttTestJsp.do?task=getResponse" styleClass="form">
<fieldset>
<label class="inline label" for="reseller_id"><fmt:message
key="label.field.resellerId" />:</label>
<html:text
property="getAvailableAddressRequest.resellerId"
styleClass="mandatory" readonly="readonly"></html:text>
</fieldset>
<html:submit value="GetAddress"/>
</html:form>
FormBean Main:
public class GetAvailableAddress extends ActionForm{
private GetAvailableAddressRequest getAvailableAddressRequest;
public void intilize(){
getAvailableAddressRequest = new GetAvailableAddressRequest();
}
public GetAvailableAddressRequest getGetAvailableAddressRequest(){
return this.getAvailableAddressRequest;
}
public void setGetAvailableAddressRequest(GetAvailableAddressRequest getAvailableAddressRequest){
this.getAvailableAddressRequest = getAvailableAddressRequest;
}
}
child Form Bean:
public class GetAvailableAddressRequest implements Serializable{
private String resellerId;
public String getResellerID(){
return this.resellerId;
}
public void setResellerID(String resellerId){
this.resellerId = resellerId;
}
}
Action Class:
public class TestJsp extends Action {
Logger logger = Logger.getLogger(this.getClass());
#Override
public ActionForward execute( ActionMapping map, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response) throws Exception{
ActionForward forward = null;
GetAvailableAddress form = (GetAvailableAddress) actionForm;
form.intilize();
forward = map.findForward("init");
return forward;
}}
It seems your getter and setter for ressellerId field are not properly named in GetAvailableAddressRequest class. You are using ID at the end of the method name instead of Id
Corrected signatures below:
public String getResellerId(){
return this.resellerId;
}
public void setResellerId(String resellerId){
this.resellerId = resellerId;
}
Remember that the property name of the input tag must match with a getter method name in the action form
sample :
in the jsp
<html:textarea property="productDescription" rows="15" cols="50" >
</html:textarea>
in the action form
public String getProductDescription() {
return productDescription;
}
To others being redirected here: first check all your variable/method names.
The problem for me was that the Form Bean requested the values from the POJO class(the class with getters and setters) in order to display the initial jsp; since they had no value to begin with, they returned a null, making the jsp think there's no getter.
Just set a default value, even "".
public class GetAvailableAddressRequest implements Serializable{
//private String resellerId;
private String resellerId = "defaultValue";
public String getResellerID(){
return this.resellerId;
}
public void setResellerID(String resellerId){
this.resellerId = resellerId;
}
This fixed it for me!
your getter and setter for this field are not properly named in.
it should be like "private String variableName" not like "private String VariableName".
CamelCase is not recommended here.

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?

Spring validation errors not displayed

I have the following situation. I have a validator to validate my command object and set the errors on a Errors object to be displayed in my form. The validator is invoked as expected and works okay, but the errors i set on the Errors objects are not displayed, when i am sent back to my form because of the validation errors.
Validator:
public void validate(Object obj, Errors err) {
MyCommand myCommand = (MyCommand) obj;
int index = 0;
for (Field field : myCommand.getFields()) {
if (field.isChecked()) {
if ((field.getValue() == null) || (field.getValue().equals(""))) {
err.rejectValue("fields[" + index + "].value", "errors.missing");
}
}
index++;
}
if (myCommand.getLimit() < 0) {
err.rejectValue("limit", "errors.invalid");
}
}
Command:
public class MyCommand {
private List<Field> fields;
private int limit;
//getters and setters
}
public class Field {
private boolean checked;
private String name;
private String value;
//getters and setters
}
Form:
<form:form id="myForm" method="POST" action="${url}" commandName="myCommand">
<c:forEach items="${myCommand.fields}" var="field" varStatus="status">
<form:checkbox path="fields[${status.index}].checked" value="${field.checked}" />
<c:out value="${field.name}" />
<form:input path="fields[${status.index}].value" />
<form:errors path="fields[${status.index}].value" cssClass="error" /></td>
<form:hidden path="fields[${status.index}].name" />
</c:forEach>
<fmt:message key="label.limit" />
<form:input path="limit" />
<form:errors path="limit" cssClass="error" />
</form:form>
Controller:
#RequestMapping(value = REQ_MAPPING, method = RequestMethod.POST)
public String onSubmit(Model model, MyCommand myCommand, BindingResult result) {
// validate
myCommandValidator.validate(myCommand, result);
if (result.hasErrors()) {
model.addAttribute("myCommand", myCommand);
return VIEW;
}
// form is okay, do stuff and redirect
}
Could it be that the paths i give in the validator and tag are not correct? The validator validates a command object containing a list of objects, so that's why i give a index on the list in the command object when registering an error message (for example: "fields["+index+"]".value).
Or is it that the Errors object containing the errors is not available to my view?
Any help is welcome and appreciated, it might give me a hint or point me in right direction.
I found what is your problem.
property fields in object myCommand always null.
You need to create constructor for class MyCommand in which you need to use LazyList from Apache Commons or AutoPopulatingList from Spring to create auto growing list of Field
In example (using AutoPopulatingList):
public class MyCommand {
private List<Field> fields;
private int limit;
//getters and setters
//...
//Constructor
public MyCommand() {
fields = new AutoPopulatingList<Field>(Field.class);
}
}
The line err.rejectValue("fields[" + index + "].value", "errors.missing"); will not do what you are trying to achieve. The first argument must be a property name of your Command bean, in your case fields.
To give the user a message you will have to use a parameterizable message in your properties file, eg. myform.field.error = you have an error in field {0}
So, use this method of the Errors object:
void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage)
Where you pass index into errorArgs

Categories

Resources