word>
(1)
<%@page buffer="1kb"%>
<%
long i=0;
for(i=0;i<10;i++)
{
out.println("@@@@@@@@@@@@@@@@@");
}
%>
xml:namespace prefix = jsp />
(2)
<%@page buffer="1kb"%>
<%
long i=0;
for(i=0;i<600;i++)
{
out.println("@@@@@@@@@@@@@@@@@");
}
%>
说明:
1. 方法(1),(2)可以使用变量表示重定向地址;方法(3)不能使用变量表示重定向地址。
String add="./index.html";
无法重定向到index.html中去
String add=localhost:7001/index.html
response.sendRedirect(add);
可以重定向到localhost:7001/index.html中去。
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.testdemo test = (demo.testdemo)request.getAttribute("test");
if (test == null)
{
try
{
test = (demo.testdemo) java.beans.Beans.instantiate(getClass().getClassLoader(),"demo.testdemo");
}
catch (
Exception _beanException)
{
throw new
weblogic.utils.NestedRuntimeException("cannot instantiate ’demo.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地址也是区分大小写.如localhost:7001/demo/t.jsp与localhost:7001/Demo/t.jsp是不一样
(3).在jsp中判断字符串要使用compareTo方法,不要用==,因为在java中String变量不是一个简单变量而是一个类实例,不同方法会得到 不同结果,如下所示:
String str1="ABCD";
String str2="ABCD"; (或 String str2="AB"+"CD"; )
if (str1==str2)
out.print("yes");
else
out.print("no");
结果是"yes"。
String str1,str2,str3;
str1="ABCD";
str2="AB";
str3=str2+"CD";
if (str1==str3)
out.print("yes");
else
out.print("no");
结果是"no"。
String str1=new String("ABCD");
String str2=new String("ABCD");
if (str1==str2)
out.print("yes");
else
out.print("no");
结果是"no"。
String str1=new String("