jsp自動跳轉的幾種方法

發現存在發表於2017-07-14
需求及前提:
1. 當前頁面是專案的第一個頁面(welcome.jsp)
2. 訪問專案,先進入welcome.jsp後,該頁面自動通過springMVC請求跳轉到index頁面
3. 直接訪問localhost:8080/common/index 是可以直接訪問index頁面的

一:用js跳轉
1. onload + location.href或者location.replace
關鍵程式碼:
。。。
<%
String path=request.getContextPath();
String basepath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
。。。
function commit() {
location.href="<%=basepath%>common/index";
}
。。。
<body onload="commit()">
小結:
1.網上說在head中加入<base href="<%=basepath%>">,就可以該路徑為相對路徑訪問,但我試了不好使,所以我寫成"<%=basepath%>common/index"這樣的絕對路徑(有保障)
2.basepath在jsp中很有用
3.呼叫js函式 別忘了加括號,onload="commit"就不行,關鍵是沒有報錯資訊

2.onload + form.submit()
關鍵程式碼:
。。。
function commit() {
var form = document.getElementById("indexform");
form.action = "<%=basepath%>common/index";
form.submit();
}
。。。
<body onload = "commit()">
<form id="indexform"></form>
。。。
小結:
我看網上有人這麼寫提交form表單:
with(document.getElementById("queryFunction")) {
action="new.jsp";
method="post";
submit();
}
with的作用是設定程式碼在特定物件中的作用域。
雖然這麼寫好看了許多,但是with是執行緩慢的程式碼塊,儘量避免使用。

3. a標籤 + js事件觸發
關鍵程式碼:
<a href="<%=basepath%>common/index"></a>
<script language="javascript">
var comment = document.getElementsByTagName('a')[0];
if (document.all) {
// For IE
comment.click();
}else if (document.createEvent) {
//FOR DOM2
var ev = document.createEvent('MouseEvents');
ev.initEvent('click', false, true);
comment.dispatchEvent(ev);
}
</script>
小結:
這段程式碼判斷瀏覽器的方式可以記一下
也算是一種思路,試了,同樣好用

二:jsp方式
1. jsp:forward
關鍵程式碼:
<jsp:forward page="/common/index"></jsp:forward>
小結:
網上說:它的底層部分是由RequestDispatcher來實現的,因此它帶有RequestDispatcher.forward()方法的印記(我沒深究,先記著吧)

2. response.sendRedirect
關鍵程式碼:
response.sendRedirect(basepath + "common/index");
小結:
response.sendRedirect是一種“客戶端跳轉”方式,總是和它對應的是
RequestDispatcher.forward(伺服器跳轉,或者稱為“轉發”。這個寫在jsp裡,執行的時候是會報錯的)




相關文章