Welcome to Dream.In.Code
Become a Java Expert!

Join 150,403 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 948 people online right now. Registration is fast and FREE... Join Now!




Fetching form value in Java class

 
Reply to this topicStart new topic

Fetching form value in Java class

kensington
3 Apr, 2008 - 04:17 PM
Post #1

New D.I.C Head
*

Joined: 8 Oct, 2007
Posts: 31


My Contributions
In my Tomcat 4.1.27 container (with no struts), I am trying to pass a form value to a JavaBean but I keep getting NullPointerException on the web page when I call the JavaBean.

This does compile but I cant get the form value in my JSP. I assume I am doing something wrong with my request object. Please advise how I can make this work.
CODE

public class First
{
    private HttpServletRequest request;
    private String lastname;

    public First()
    {
         lastname= (String) request.getParameter("lastname");
    }
  
    /* Getter and Setter Methods */
     public String getLastname() {
    return lastname;
     }

      public void setLastname(String lastname) {
    this.lastname = lastname;
      }


    public FetchFormValue()
    {
        if(lastname.equals("Smith")
        {
             //do stuff for Smith
        }
        else
        {
            //do other stuff
        }
    }
..
}


Please advise.
User is offlineProfile CardPM
+Quote Post

bhandari
RE: Fetching Form Value In Java Class
4 Apr, 2008 - 12:13 AM
Post #2

D.I.C Addict
Group Icon

Joined: 31 Jan, 2008
Posts: 747


Dream Kudos: 900
My Contributions
QUOTE
if(lastname.equals("Smith")
{
//do stuff for Smith
}
else
{
//do other stuff
}


Check your objects against null value before invoking non-static methods on them.
For String equals method, there is another way around to avoid NPE as:
CODE

if("Smith".equals(lastname))
        {
             //do stuff for Smith
        }
        else
        {
            //do other stuff
        }


User is offlineProfile CardPM
+Quote Post

1lacca
RE: Fetching Form Value In Java Class
4 Apr, 2008 - 01:27 AM
Post #3

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 12 times
My Contributions
In the constructor the request object is not initialized.
You can get hold of the HttpRequest object at two places: in a servlet in doPost or doGet, or in the JSP either from as the predefined variable request from a scriptlet, or from the useBean directive.


User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 07:17PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month