tags:

views:

31

answers:

2

i am new in JSP,i have some problem with the following code :

    <%@ page contentType="text/html;charset=Big5" %>
<html>
    <head>
    <title></title>
    </head>
    <body>
        <form method="post" action="InsertStudent.jsp">
    <input type="text" size="20" name="txtName" />
    <input type="text" size="20" name="txtDob" />
    <input type="text" size="20" name="txtProStudied" />
    <input type="submit" name="B1" value="Submit" />     
        </form>

<% 
  if (request.getParameter("txtName") !="" && request.getParameter("txtDob") != "" && request.getParameter("txtProStudied") != "" ) {
              out.println("...bypass the if....statement");               
  }
%>

    </body>
</html>

If run this code, the out.println will fire even the 3 input box have value or not..

+3  A: 

Because request.getParameter returns a string, you cannot use the != operator. You must use the equal function. The return value of request.getParameter might also be null. You need to check for that as well.

if (request.getParameter("txtName") != null && !"".equals(request.getParameter("txtName")) 
 && request.getParameter("txtDob") != null && !"".equals(request.getParameter("txtDob")) 
 && request.getParameter("txtProStudied") != null && !"".equals(request.getParameter("txtProStudied"))) {
    out.println("...bypass the if....statement");               
}

It would be ideal to define a function to test if the return value is either an empty string or null to reduce the code.

public boolean isEmpty(String s)
{
    return (null == s || "".equals(s.trim()))
}
teneighty
Oh yeah~you are right~~ well,, Java and C# is different world.I am using C# sense to write java...
SilverNight
A: 

Maybe try:

if (request.getParameter("txtName").equals("")) { }

or .compareTo(), or .compareToIgnoreCase()

rascher