I want to invoke a getter method (returns String value) of a Java class from JSP by using "jsp:usebean", but it returns a null value. What I don't understand is why it can't return the updated value.
Can someone shed some light on this?
Should I use a Cookie to get the value from JSP?
I'm not sure what you're using (Struts, plain Servlets, etc.) but essentially you need to add an attribute to the ServletRequest like:
class Person {
private String firstName;
// other fields, getters, setters
}
public void method(HttpServletRequest httpServletRequest) {
Person p = new Person();
p.setFirstName("Obama");
httpServletRequest.setAttribute("person", p);
}
and in your JSP:
<jsp:getProperty object="person" property="firstName" />
or if you use JSTL:
<c:out value="${person.firstName}"/>
It is simple.
In java file:
package loga;
class bean{
String name;
public void setName(String Uname)
{
this.name=Uname;
}
public void getName()
{
return name;
}
In jsp file, call this method as:
<jsp:useBean id="object" class="loga.bean">
<jsp:setproperty name="object" property="Name" Value="XXXX"/>
<jsp:getProperty name="object" property="Name"/>
</jsp:usebean>
Here, the property indicates the method name of the getName() in the java class.
To pass value from other controls use param property and give name of the control.
Related
In my java code
package com.luv2code.jsp.tagdemo;
public class Student {
public String firstName;
public String lastName;
public boolean goldCustomer;
public Student(String firstName, String lastName, boolean goldCustomer) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.goldCustomer = goldCustomer;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isGoldCustomer() {
return goldCustomer;
}
public void setGoldCustomer(boolean goldCustomer) {
this.goldCustomer = goldCustomer;
}
}
In JSP Code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import="java.util.*,com.luv2code.jsp.tagdemo.Student" %>
<%
ArrayList<Student> data=new ArrayList<>();
data.add(new Student("Subhajit","Maity",true));
data.add(new Student("Biswajit","Kundu",true));
data.add(new Student("Sourav","Das",false));
pageContext.setAttribute("myStudent", data);
%>
<html>
<head>
</head>
<body>
<c:forEach var="tempStudent" items="${myStudent}">
${tempStudent.firstName}
</c:forEach>
</body>
</html>
If I use getter and setter method for setting and getting the firstname,lastname and goldcustomer then the code works fine.But with out getter and setter it gives error.If I declare the class variable as public then it can be accessible to any where then ahy should I use getter and setter menthod?
JSP/Servlet engine was designed to work following some basic principles. Among those principles is Encapsulation, which you should never give direct access to your class properties.
When your jsp is compiled the EL expression ${tempStudent.firstName} will look like com.luv2code.jsp.tagdemo.Student.getFirstName() assuming you are following encapsulation principle.
That's is part of spec, you cannot change this behavior.
The getter and setter are good tools for encapsulation. These methods may contain some logic besides their main purpose. You might want to get to check privileges whether the getter and setter should be executable, also, you might want to do some different things. For instance, if you set a husband's family name, you might need to also set the family name of the individual. You are not able to do this if you simply set the values of public data members.
You need to follow encapsulation rules for using JSP Pages. In your jsp you can call anything that start with get.
public String getAnyString() {
return "Any String";
}
You can call it to your JSP page. It doesn't look for you variables it will go for you encapsulated methods.
For readable properties there will be a getter method to read the
property value. For writable properties there will be a setter method
to allow the property value to be updated. Thus even when a script
writer types in something such as “b.Label = foo” there is still a
method call into the target object to set the property, and the target
object has full programmatic control. So properties need not just be
simple data fields, they can actually be computed values. Updates may
have various programmatic side effects
From java doc Beans
Your JSP page uses two several languages (besides HTML and JSP tags).
1 - Java
The code close to the top is regular Java:
ArrayList<Student> data=new ArrayList<>();
data.add(new Student("Subhajit","Maity",true));
If you wanted to, you could access the fields directly, i.e. without getter and setter methods:
Student student = ...;
student.lastName = "Maity";
2 - Expression Language
Tags such as <c:forEach items="${myStudent}"> and expressions such as ${tempStudent.firstName} do not use Java but the Expression Language of Java EE. It is designed as a simple scripting language.
As per specification, the expression ${tempStudent.firstName} accesses the property firstName of the JavaBean tempStudent. A JavaBean is basically any Java object that conforms to certain rules. In particular, getter and setter methods becomes properties.
As per JavaBeans Specification, chapter 7.1:
Properties are always accessed via method calls on their owning
object.
That's why it doesn't work with fields only but requires getters and possibly setters.
I have an container object that contains a google/Guava Optional and I want to access the content of this Optinal in jsp.
import com.google.common.base.Optional;
public class Container {
private Optional<User> user;
public Optional<User> getUser(){return this.user;}
}
public class User{
private String name;
public String getName() {return this.name;}
}
A Optional has a method get() to obtain the inner object. http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html#get%28%29
I have already tried (${container} ins an instance of Container):
<c:out value="${container.user.name}" />
<c:out value="${container.user.get.name}" />
<c:out value="${container.user..name}" />
none of them work (Tomcat 7.42). Does anybody has an idea how to solve this, without adding a new property to the container (getUser2(){return this.user.get();})?
Thanks to Sotirios Delimanolis
since Servlet 3.0 / JSP 2.2 one can use
<c:out value="${container.user.get().name}" />
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.
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.
I've got an object in my form that contains various string properties.
When I want to print it in my JSP form I could do it with
<c:out value="${form.company.address}" />
which works perfectly.
Now I want to create an HTML input field. But when I write
<html:text property="company.address" />
I get an error saying
Caused by: javax.servlet.jsp.JspException: No getter method for property company.address of bean org.apache.struts.taglib.html.BEAN
Do you know how I can create an HTML input field with my company's address?
My bean's got the necessary corresponding getters and setters.
The correct way of translating this:
<c:out value="${UFForm.company.address}" />
to Struts is,
<html:text name="UFForm" property="company.address">
It means that there's a request with name UFForm with a bean that contains a method getCompany() (which I'm assuming returns a Company object) and that in turns has a getAddress() getter (if you understand what I mean). In a nutshell, the bean from request/session UFForm, the TagLib is accessing getCompany().getAddress();
PS Hope that getAddress() doesn't return a null else <html:text /> will throw an exception.
Edit To explain what I did above:
public class Company implements Serializable {
private String address;
//Setter
public void setAddress(String address) {
this.address = address;
}
//Getter
public String getAddress() { return this.address; }
}
public class UFForm implements Serializable {
private Company company;
public void setCompany(Company company) {
this.company = company;
}
public void getCompany() {
if (this.company == null) {
setCompany(new Company());
}
return this.company;
}
}
What I did above in <html:text /> is equivalent to
UFForm ufForm = ....;
String property = ufForm.getCompany().getAddress();
Your bean should have corresponding setter and getter methods.
Html form
<html:text property="name" size="10" maxlength="10">
Corresponding bean.
public class AddressForm
{
private String name=null;
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
When you are getting the value for the text box with:
<html:text property="company.address" />
You are in fact saying to Struts to do:
formObject.getCompany().getAddress();
So you must have a getter for the company (which must not return null or the next operation will fail) and a setter for the address on the company object. The setters/getters must be public. This must already be the case since you can do the following with no error:
<c:out value="${UFForm.company.address}" />
Now, the thing that bugs me is this part: ${UFForm.. When you use JSTL you are accessing the form explicitly. With the <html:text> you access a property on the form implicitly. This implicit form is provided by the enclosing <html:form> tag. Do you have the <html:text> inside a <html:form>?
The form bean is located/created/exposed based on the form bean specification for the associated ActionMapping so check your mapping also.