do the following mate
<s:textfield name="address.unit" label="Unit"/>
Frage
I have two classes as following
Address
int ID
int unit
String street
User
int ID
String Name
Address address
my user class
public class user{
.....
private Address address;
...getters setters...
}
As shown above User class has an object of Address class in it. My code is expected to receive the values of a form and show them on console.
But when I try to access the unit attribute of address class it shows the following error.
"SEVERE: Exception occurred during processing request: null java.lang.NullPointerException"
my controller
@Action
class myclass implements ModelDriven{
private User user = new User();
public Register(){
System.out.println("User's Unit" + user.getAddress().getUnit()); // error is on this line
}
@Override
public Object getModel() {
return user;
}
jsp file
<s:form action="Register">
<s:textfield name="name" label="Name"/>
<s:textfield name="unit" label="Unit"/>
<s:textfield name="block" label="Block"/>
</s:form>
Lösung
do the following mate
<s:textfield name="address.unit" label="Unit"/>
Andere Tipps
try this action class this will definitly work
public class myclass extends ActionSupport implements ModelDriven<User>, Preparable{
private User user = new User();
@Override
public void prepare() throws Exception {
user=new User();
}
@Override
public User getModel() {
return user;
}
public Register(){
System.out.println("User's Unit" + user.getAddress().getUnit());
}
}
and change the jsp
<s:textfield name="address.unit" label="Unit"/>
for setting only unit property
<s:textfield name="name" label="Name"/>
Here struts2 will search for name="name" property in the related DTO's in your respective action, but value-stack will failed to find the property named "name" in your action, because you have created a different bean class Address which is having member "name". So you have to tell your form-element that "name" instance resides in different POJO i.e. Adderess . So make changes like this:
<s:textfield name="address.name" label="name"/>
the problem as I see it is, you've not new
d address
object
address = new Address();
in the constructor of User
class.
Looks like when you created the user object using "private User user = new User()" the address object of the user is not initialized. As user.getAddress() is null, when you try to invoke user.getAddress().getUnit() it will result in null pointer exception