jsp自动跳转的几种方法

来源:互联网 发布:centos 桥接模式 编辑:程序博客网 时间:2024/06/06 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里,执行的时候是会报错的)