如何利用Spring的redirectStrategy进行url hash tag的重定向

我们都知道url的hash部分是不能传到服务器端的,例如 http://projectname/#M_FACTORY:ci,其中url里面的“#M_FACTORY:ci”是hash部分,在前台可以用location.hash取得,在传到后台的时候这部分是被忽略掉的。如果我们想实现登录后自动跳转到这个url,普通的重定向是没法实现的。

1. 配置Spring登录成功的重定向策略
主意这里不能使用always-use-default-target="true",不然无法重定向

<security:http>
<security:form-login login-page="/login.action" default-target-url="/index.html" authentication-success-handler-ref="successHandler"
authentication-failure-url="/loginfailed.action" />
</security:http>

2. 配置targetUrlParameter参数和重定向策略
如果这个参数设置后,当前的请求会对含有这个参数名的URL进行检查,然后将其对应的值作为转向的目标url

<bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="targetUrlParameter" value="redirect"></property>
<property name="redirectStrategy">
<bean class="xxx.MyRedirectStrategy"></bean>
</property>
</bean>

3. 自定义重定向策略

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);
}
}
}

4. UI端做响应的处理
<form name='f' action='j_spring_security_check' method="post" οnsubmit="return setSubmitUrl(this);">

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;
}

这里将hash值转换为参数就可以传送到后台,登录成功可以在改写成跳转到的hash url,这样就实现了用户的需求,达到了我们的目标。

注意这里的“redirect要与spring配置文件里面的targetUrlParameter参数值要一致
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值