Initialize bean value from another bean (once) - java

I would like to set a value of bean from another bean once a page is displayed. The target dataTable is included because it is also used in another context.
Like I said before, there are two beans involved:
bean1 'gets' a parameter, will load an object and display some properties.
bean2 is the bean that is responsible for the filtering / search in the dataTable.
relevant parts:
<f:metadata>
<f:viewParam name="objectId" value="#{bean1.objectId}" />
</f:metadata>
<!-- resolving works -->
#{bean1.object.name}
included search:
<p:dataTable>...<p:inputText value="#{bean2.value}">...</p:dataTable>
How to assign (a substring of) bean1.object.name to the value of the input text once at page request but keep the existing value attribute of the field? I don't want to mess up the included page but would prefer to solve it "outside" in my including jsf/xhtml file.

The best way to do this is using javascript.
Define a input hidden tag to hold the value of #{bean1.object.name}.
Now in javascript get the value of this field using document.getElementById("").value
Take the substring and assign to input text field using javascript.

Related

Struts: Reference a Form-Bean as a Variable in Common JSP

I have a common JSP included in other pages; it must generically display a certain list from a bean.
All the main JSPs use a certain subclass of that bean.
In struts-config.xml, let's say there is one specific definition for my Action Form bean as an example,
<form-bean name="rr5YearBudgetForm" type="myapp.form.My5YearBudgetActionForm" />
The common JSP needs to check properties of that bean, in a general way (with the bean I pass in); these are properties which all the form beans will support. Right now, it's hard-coded to use the specific Form Bean below, but it must work with any bean that's passed in.
<c:if
test="${rr5YearBudgetForm.saved == true || fn:length(rr5YearBudgetForm.budgetPeriods) > 1}">
The question is, how do I pass in a specific variable containing my form-bean? I tried this simple c:set var, but that defines a string, with no properties.
Calling JSP
<c:set var="budgetForm" value="rr5YearBudgetForm" scope="request" />
<%# include file="common.jsp" %>
Common JSP
<c:if test="${budgetForm.saved == true || fn:length(budgetForm.budgetPeriods) > 1}">
but that does not work. I need a way to pass in the actual bean rather than a string.
Please try the bean tag:
<s:bean name="com.mkyong.common.action.HelloBean" var="hello">
<s:param name="msg">Hello Bean Tag</s:param>
</s:bean>
This tag library contains tags useful in accessing beans and their properties, as well as defining new beans (based on these accesses) that are accessible to the remainder of the page via scripting variables and page scope attributes.

JSF 2.0 Set default value on page

I would like to know if there is a way to set a default value to a inputText, or inputHidden or any other tag that can be recovered in the backing bean when the page shows.
I would like something like this (this code doesn't work):
<h:inputText id="companyName" value="#{loginController.companyName}" defaultValue="123456">
And in the backing bean:
private String companyName;
#PostConstruct
public void init() {
System.out.println("CompanyName=" + companyName);
}
So that it shows "CompanyName=123456" in the console.
I need to define the default value in the page itself, I don't want to put the default value in the backing bean.
The real problem is that I need to find a way to pass a value to the backing bean defined in the page. I have many pages and I want to define a 'mode' in each page to be shown differently, and this 'mode' needs to be read by the backing bean when the page displays (before any submit)
I've somewhat solved the problem by showing what I want to show in certain mode, using an h:panelGroup and an EL expression to set the value to the bean:
<h:panelGroup rendered="#{loginController.companyName('123456')}" >
...
</h:panelGroup>
Thanks everybody for your comments

Pass Value From JSP To JSF Page Backing Bean

Is it possible to pass parameter from a JSP page to a JSF page's backing bean?
JSP page is popup window open when I invoke a button in JSF page and my selected value in JSP page, I should be able to pass to JSF's backing bean.
P.S. When I add comment and I put #anyname when someone replies, #namyname part is getting truncated.
Update 1
To get the selected value from JSP to bean I did a crude approach.
I added the the following in JSP
String str = request.getParameter("selectname");
and assigned string str to a hidden field
<input type="hidden" name="hid" value="<%=str%>" />
and in my bean I am getting the value like the following
logger.info("jsp value "+FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("hid"));
This almost works except I always gets the value which I previously selects.
E.g. First time when I selects 1 and value returned in bean is null, second time when I selects 2, value returned is 1.
How could I get the currently selected value in my bean?
First, if your JSF view technology is JSP, then you can use the <h:> tags in the jsp and it becomes straightforward 0 just add a <h:commandButton action="#{yourBean.yourMethod}" />
Otherwise, you still can perhaps, but I'd suggest that you make your popup also a JSF page. JSF and JSP don't coexist well. If you really must retain the situation, then you can try to emulate a JSF POST request to the target jsf URL.
f:viewParam lets you associate bean
properties with request parameters
–
-This introduces several new capabilities
New tags that navigate via GET instead of POST and tags that
navigate via GET instead of POST, and send parameters along with the
address
Sending data from non-JSF forms to JSF pages
Make results pages results pages bookmarkable
This is a new feature in JSF 2.0
example:
<f:viewParam name="fg" value="#{colorPreferences.foreground}" />
If the “fg” parameter is non-null, it is passed to
setForeground before the page is rendered
<f:metadata>
<f:viewParam name="param1" value="#{bean.prop1}"/>
<f:viewParam name="param2" value="#{bean.prop2}"/>
</f:metadata>
<h:head>…</h:head>
<h:body>
Blah Blah blah #{bean prop1} , blah, #{bean.prop1}
</h:body>
If the page is called with page.jsp?param1=foo&param2=bar, then “foo” and “bar” are passed to “setProp1” and “setProp2” before the page is rendered. If any of the parameters are null (i.e., no such request parameter exists), then the associated setter is not called at all, and the bean has its normal value for that property
You can find the answer from the JSF tutorial http://www.coreservlets.com/JSF-Tutorial/jsf2/

How do JSP tag files and libraries work?

I've been learning about JSPs and came across tag files and libraries. I know that they are custom actions and useful for pointing out errors instead of using JavaBeans for example, but I still don't understand how they work. Lets say for example you do:
<jsp:directive.attribute name = "amount" required = "true" />
And later, assuming that calc is defined using jsp:useBean, amount can be used by:
<c:set target="${calc}" property = "amount" value ="${amount}" />
But what happens behind the scenes?
${calc} represents value of variable calc which may be there in pageCOntext,request,session,Servletcontext
By the statement
<c:set target="${calc}" property = "amount" value ="${amount}" />
it will store value in calc var's amount represented by value
Behind the scene it would be
calc.setAmount(amount);
Tag files are custom tag handlers which are written in JSP. These jsp are converted to java tag handlers by the JSP compiler.

How to use bean in JSP?

How to use bean in JSP with only <jsp:useBean>, not MVC?
Assume you have a grade.txt file which contains following data:
Tom 90
Jerry 70
Katy 80
John 60
It asks you to create a bean named grade.java, a JSP page named graderesult.jsp, and a html page named gradecheck.html.
gradecheck.html provides a input textbox and a button submit, once you submit the name of the student, the graderesult.jsp will communicates with bean to show the name and the score corresponding to the person.
You can make use of <jsp:setProperty name="beanname" property="*" /> to "automatically" set all request parameters as bean properties matching the property name. As this is a typical homework question, I won't give complete code examples, but only hints:
Create a bean Grade with a property name.
Add a constructor which loads the data from the text file into a Map<String, Integer> property representing name-score pairs. Learn more about Java IO here and about Java Maps here.
Add a "special" getter getScore() which returns the score from the Map using the name as key.
Create a form with <input type="text" name="name"> in the gradecheck.html. Let the form submit to graderesult.jsp. The request method doesn't matter, I would prefer POST though.
In the graderesult.jsp use <jsp:useBean> to declare and instantiate the bean in request scope and use <jsp:setProperty> to "automatically" set all input values in the bean.
Use EL to show the name by ${grade.name} and the associated score by ${grade.score}.
Good luck.

Categories