---
title: "如何利用Spring的redirectStrategy进行url hash tag的重定向"
author: "jobar"
date: "2013-11-25T13:55:30Z"
tags: []
categories: ["编程语言"]
slug: "spring-redirectstrategy-url-hash-tag"
draft: false
lastmod: "2013-11-25T13:54:44Z"
id: 1980202
url: "https://jobar.iteye.com/blog/1980202"
---

我们都知道url的hash部分是不能传到服务器端的，例如 http://projectname/#M\_FACTORY:ci,其中url里面的“#M\_FACTORY:ci”是hash部分，在前台可以用location.hash取得，在传到后台的时候这部分是被忽略掉的。如果我们想实现登录后自动跳转到这个url，普通的重定向是没法实现的。 1. 配置Spring登录成功的重定向策略 主意这里不能使用always-use-default-target="true"，不然无法重定向 \[code="xml"] \[/code] 2. 配置targetUrlParameter参数和重定向策略 如果这个参数设置后，当前的请求会对含有这个参数名的URL进行检查，然后将其对应的值作为转向的目标url \[code="xml"] \[/code] 3. 自定义重定向策略 \[code="java"] public class MyRedirectStrategy extends DefaultRedirectStrategy { @Override public void sendRedirect(final HttpServletRequest request, final HttpServletResponse response, final String url) throws IOException { if (url != null && !url.startsWith("/") && !url.startsWith("http://")) { final String redirectUrl = request.getContextPath() + "/index.html#" + url; response.sendRedirect(redirectUrl); } else { super.sendRedirect(request, response, url); } } } \[/code] 4. UI端做响应的处理

\[code="java"] function setSubmitUrl(form){ var action = form.action; var hash = location.hash; if(hash){ hash = hash.substring(1); action += "?redirect=" + hash; } form.action = action; return true; } \[/code] 这里将hash值转换为参数就可以传送到后台，登录成功可以在改写成跳转到的hash url，这样就实现了用户的需求，达到了我们的目标。 注意这里的“redirect要与spring配置文件里面的targetUrlParameter参数值要一致