JSP頁面中相關代碼:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String url = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+request.getServletPath().substring(0,request.getServletPath().lastIndexOf("/")+1);
if(request.getQueryString()!=null)
{
url+="?"+request.getQueryString();
}
System.out.println("path:"+path);
System.out.println("basePath:"+basePath);
System.out.println("URL:"+url);
session
System.out.println("URL參數:"+request.getQueryString());
%>url
訪問以後輸出的結果:
1.這是不帶參數
path:/CS
basePath:http://localhost:8080/CS/
URL:http://localhost:8080/CS/
URL參數:null
2.帶參數時
path:/CS
basePath:http://localhost:8080/CS/
URL:http://localhost:8080/CS/?userid=3
URL參數:userid=3
爲了在servlet中,讓異常時跳到帶有參數的URL,找了好久才找到。原來這麼簡單。把url存到session裏,異常的時候再取出來加上去就好啦。
String url = session.getAttribute("url");
out.println("<script>alert('出錯啦。');window.location.href='"+url+"';</script>");spa