JSP内置对象编程技巧
2024-09-05 00:19:02
供稿:网友
1.1 application
*在jsp中获得application对象
如:getservletcontext().setattribute("counter",new mycount.counter());
如:<jsp:usebean scope="application" id="counter" class="mycounter.counter"/>
*在jsp中处理on application start和on session start事件的方法
使用httpsessionbindinglistener类.
添加session:
session.putvalue("bingdings.listener",new mylistener(getservletcontext());
定义mylistener类:
import javax.servlet.http.*;
import javax.servlet.*;
public class mylistener implements httpsessionbindinglistener{
servletcontext context;
public mylistener(servletcontext context){
this.context=context;
}
public void valuebound(httpsessionbindingevent event){
system.out.println("valuebound:someone just bound my listener to a session!");
}
public void valueunbound(httpsessionbindingevent event){
system.out.println("valueunbound:someone just unbound my listener!");
}
}
1.2 request
*获取一个正在运行时的jsp/servlet文件的绝对url地址
stringf file=request.getrequesturl();
if(requet.getquerystring()!=null{
file+='?'+request.getquerystring();
}
url reconstructedurl=new url(request.getscheme(),request.getservername(),request.getserverport(),file);
out.println(reconstructedurl.tostring());
*获取客户端通过哪一个url访问本页面
string callpage=request.getheader("referer");
*获取当前脚本在当疥文件系统中的真实路径
request.getrealpath(request.getservletpath());
*判断多个submit中的一个
<input type=submit name="sub" value="up">
<input type=submit name="sub" value="down">
在jsp中使用request.getparameter("sub");就可分辨
1.3 response
*网页重定向之三方法
(1)response.sendredirect(url);
(2)<%response.setstatus(httpservletresponse.sc_moved_premanently);
string nowloc="/newpath/index.htm";
response.setheader("location",newloc);%>
(3)<jsp:forward page="/newpage.jsp"/>
注意上法只能在任何输出还没有发送到客户端之前使用这种方法
*禁用缓存
<%response.setheader("cache-control","no-store");
response.setdateheader("expires",0);%>
1.4 session
*存活时间
<%session.setmaxinactiveinterval(300);%>
*注销
session.invalidate();
1.5 exception
*在jsp页面中处理servlet的错误
protected void senderrorredirect(httpservletrequest request,
httpservletresponse response,string errorpageurl,throwable e)
throws servletexception,ioexception{
request.setattibute("javax.servlet.jsp.jspexception",e);
getservletconfig().getservletcontext();
getrequestdispatcher(errorpageurl).forward(request,response);
}
public void dopost(httpservletrequest request,httpservletresponse response){
try{
//
}
catch(exception e){try{
senderrorredirect(request,response,"/jsp/errpage.jsp",e);
}catch(exception e){e.printstacktrace();}
}
}
*在jsp页面中输出错误的stacktrace
(1)
<%@ page iserrorpage="true%>
<%
out.println("<pre>");
printwriter pw=response.getwriter();
exception.printstacktrace(pw);
out.println("</pre>");
%>
(2)
<%@ page iserrorpage="true%>
<pre>
<%
exception.printstacktrace(new printwriter(out));
%>
</pre>
1.6 cookie
*设置cookie
<%
cookie mycookie=new cookie("aname","avalue");
response.addcookie(mycookie);
//mycookie.setmaxage(time);
%>
。