【疑难解答】如何通过servlet跳转到jsp的锚点位置

在实际情况中,我们往往需要从servlet中跳转到jsp上的某一个特殊位置,而不只是首部,遗憾的是servlet中并不可以只在url后面加#参数的方式来跳转到描点,下面,我们就来探讨一下问题的解决方案
1.Servlet跳转之前在request中加入一个参数(锚记的id)
2.Jsp中加入一段js代码,获取1中的参数值,然后模拟锚记的点击

假设我们有这样一个网页
代码为

<style type="text/css">
    #div1{
        height: 1000px;
        background-color: gray;
    }
    #div2{
        height: 1000px;
        background-color: green;
    }
</style>
</head>
<body>
    <div id="div1">

    </div>
    <a name="here" id="here" href="#here"></a>
    <div id="div2">

    </div>
</body>

预览为
这里写图片描述
如果我们需要直接翻滚到绿色的部分
直接在url后面接上#here即可,如http://localhost:8080/ex150512_testHref/index.jsp#here,输入回车
这里写图片描述

OK,很好,
但是当我们需要请求Servlet,然后再返回Jsp页面需要翻滚到绿色部分时,又可以直接在url后面加上#here来实现吗?
在页面上加上一个超链接来访问servlet

<body>
    <a href="servlet1">GOTOGREEN</a>
    <div id="div1">

    </div>
    <a name="here" id="here" href="#here"></a>
    <div id="div2">

    </div>
</body>

Servlet核心代码为

request.getRequestDispatcher("/index.jsp#here").forward(request, response);

点击之后
这里写图片描述
发现出现404错误

解决方案
1.在request中加入一个参数(锚记的id)
servlet核心代码为

request.setAttribute("location", "here");
    request.getRequestDispatcher("/index.jsp").forward(request, response);

2.在页面加入一段js代码,跳转到相应的锚记

<script type="text/javascript">
    window.onload=function(){
    //如果location存有数据,跳到锚点
    var location_id='${location}';
    if(location_id!=''){
        document.getElementById(location_id).click();
    }

}
</script>

3.在页面上加上一个超链接来访问servlet2
最后的完整页面代码为

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #div1{
        height: 1000px;
        background-color: gray;
    }
    #div2{
        height: 1000px;
        background-color: green;
    }
</style>
<script type="text/javascript">
window.onload=function(){
    //如果location存有数据,跳到锚点
    var location_id='${location}';
    if(location_id!=''){
        document.getElementById(location_id).click();
    }

}
</script>
</head>
<body>
    <a href="servlet1">GOTOGREEN</a>
    <a href="servlet2">GOTOGREEN2</a>
    <div id="div1">

    </div>
    <a name="here" id="here" href="#here"></a>
    <div id="div2">

    </div>
</body>
</html>

最后点击GOGREEN2,然后你会发现,你成功了!
这里写图片描述

项目源代码下载地址:
http://download.csdn.net/detail/ht1456749/8693315

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值