我们都知道url的hash部分是不能传到服务器端的,例如 http://projectname/#M_FACTORY:ci,其中url里面的“#M_FACTORY:ci”是hash部分,在前台可以用location.hash取得,在传到后台的时候这部分是被忽略掉的。如果我们想实现登录后自动跳转到这个url,普通的重定向是没法实现的。
1. 配置Spring登录成功的重定向策略
主意这里不能使用always-use-default-target="true",不然无法重定向
2. 配置targetUrlParameter参数和重定向策略
如果这个参数设置后,当前的请求会对含有这个参数名的URL进行检查,然后将其对应的值作为转向的目标url
3. 自定义重定向策略
4. UI端做响应的处理
<form name='f' action='j_spring_security_check' method="post" οnsubmit="return setSubmitUrl(this);">
这里将hash值转换为参数就可以传送到后台,登录成功可以在改写成跳转到的hash url,这样就实现了用户的需求,达到了我们的目标。
注意这里的“redirect要与spring配置文件里面的targetUrlParameter参数值要一致
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参数值要一致