2. 采用方法(1),(2)request中的变量(通过request.setAttribute()保存到request中的值)不能在新的页面中采用,采用方法(3)能.
综上,我们应该采用(1),(2)重定向比较好。
四、JSP中正确应用类
应该把类当成JAVA BEAN来用,不要在<% %> 中直接使用. 如下的代码(1)经过JSP引擎转化后会变为代码(2):
从中可看出如果把一个类在JSP当成JAVA BEAN 使用,JSP会根据它的作用范围把它保存到相应的内部对象中.
如作用范围为request,则把它保存到request对象中.并且只在第一次调用(对象的值为null)它时进行实例化.
而如果在<% %>中直接创建该类的一个对象,则每次调用JSP时,都要重新创建该对象,会影响性能.
代码(1)
<%
test.print("this is use java bean");
testdemo td= new testdemo();
td.print("this is use new");
%>
代码(2)
demo.com.testdemo test = (demo.com.testdemo)request.getAttribute("test");
if (test == null)
{
try
{
test = (demo.com.testdemo) java.beans.Beans.instantiate(getClass().getClassLoader(),"demo.com.testdemo");
}
catch (Exception _beanException)
{
throw new weblogic.utils.NestedRuntimeException("cannot instantiate 'demo.com.testdemo'",_beanException);
}
request.setAttribute("test", test);
out.print("\r\n");
}
out.print("\r\n\r\n\r\n");
test.print("this is use java bean");
testdemo td= new testdemo();
td.print("this is use new");
五、JSP的调试
JSP的调试比较麻烦,特别是当bean是在一个session中存在时,更加困难。得从好几个页面开始往里面走才行。通常是用out.println()或System.out.print()来打一大堆的信息来查问题。如果是用jbuilder做开发,它能直接调试JSP.不过更重要的是知道错误产生的原因及解决方法。下面对一些JSP编程常见错误进行分析。
(1).java.lang.NullPointerException异常
一般是对一个为NULL值的变量进行操作引起的.如下面的操作就会抛出java.lang.NullPointerException
String a = null;
a.substring(0,1);
为避免这种异常,最好在对变量操作之前检查看它是否为NULL值.如:
<%
String ss=Session.getAttribute("NAME")
if isnull(ss)
{
}
else
{
}
%>
(2).JSP是用JAVA写的,所以它是大小写敏感的,用过其他编程语言的人最容易犯这个错误。另外在浏览器的地址栏中输入的访问JSP的地址也
是区分大小写的.如http://localhost:7001/demo/t.jsp与http://localhost:7001/Demo/t.jsp是不一样的.
(3).在jsp中判断字符串要使用compareTo方法,不要用==,因为在java中String变量不是一个简单的变量而是一个类实例,不同的方法会得到 不同的结果,如下所示:
1.
String str1="ABCD";
String str2="ABCD"; (或 String str2="AB"+"CD"; )
if (str1==str2)
out.print("yes");
else
out.print("no");
结果是"yes"。
2.
String str1,str2,str3;
str1="ABCD";
str2="AB";
str3=str2+"CD";
if (str1==str3)
out.print("yes");
else
out.print("no");
结果是"no"。
3.
String str1=new String("ABCD");
String str2=new String("ABCD");
if (str1==str2)
out.print("yes");
else
out.print("no");
结果是"no"。
4.
String str1=new String("ABCD");
String str2=new String("ABCD");
if (str1.compareTo(str2)==0)
out.print("yes");
else
out.print("no");
结果是"yes"。