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

来源:互联网 发布:淘宝怎么买武士刀 编辑:程序博客网 时间:2024/06/04 11:58

在实际情况中,我们往往需要从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

0 0
原创粉丝点击