Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

request.setAttribute() nullpointer in struts 2

 
Deepu Surendran
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have created

HttpServletRequest request=null; in Action Class

and trying to send a object using request.setAttribute in a method()

eg:public String listCourses(){

String hai="Test";
try{
request.setAttribute("disp",hai);
}
catch(Exception e){
System.out.println("Exception occured :"+e);
}
return SUCCESS;
}

am getting null pointer exception



 
Vanessa Danin
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously the request variable's value is null since it has not been set to anything. Actions in Struts2 are not servlets.

In order to access the servlet request, your action needs to implement the RequestAware interface. Please refer to the following API documentation: http://struts.apache.org/2.1.2/struts2-core/apidocs/org/apache/struts2/interceptor/RequestAware.html

In order to implement this interface:
1) Your action class must declare that it implements the interface
2) Include the setter method (and optionally the getter) in your class:
public void setRequest(Map request) {
this.request = request;
}

public Map getRequest() {
return request;
}
3) Declare an instance request variable of type Map

Since the request is a Map, you use Map's put method to set request attributes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic