您的位置:首页 > 编程语言 > Java开发

Spring Security 4.X xml配置重定向

2016-05-25 12:24 483 查看
<!-- 后台权限控制 @PreAuthorize -->
<global-method-security pre-post-annotations="enabled" />


<form-login login-page="/login" authentication-success-handler-ref="successHandler"  authentication-failure-url="/login?error=1" authentication-success-forward-url="/main.to" />


<http  use-expressions="false" >
...
<expression-handler ref="webexpressionHandler" ></expression-handler>
</http>


<!--配置web端使用权限控制-->
<beans:bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />


<!-- 重定向 /login?redirect= 重定向url -->
<beans:bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="targetUrlParameter" value="redirect"></beans:property>
<beans:property name="redirectStrategy">
<beans:bean class="com.framework.redirect.MyRedirectStrategy"></beans:bean>
</beans:property>
</beans:bean>


package com.framework.redirect;

import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.util.UrlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyRedirectStrategy extends DefaultRedirectStrategy {
@Override
public void sendRedirect(final HttpServletRequest request, final HttpServletResponse response, final String url)
throws IOException {
String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
redirectUrl = response.encodeRedirectURL(redirectUrl);
if (logger.isDebugEnabled()) {
logger.debug("Redirecting to '{"+redirectUrl+"}'");
}
response.sendRedirect(redirectUrl);
}
private String calculateRedirectUrl(String contextPath, String url) {
if (!UrlUtils.isAbsoluteUrl(url)){
return url;
}
else
{
int contextPathIndex = url.indexOf(contextPath);
int contextPathLength = contextPath.length();

// check to see if there is a context path in this url
if (contextPathIndex >= 0)
{
// strip out the context path
url = url.substring(0, contextPathIndex) + url.substring(contextPathIndex + contextPathLength);
}

// check to see if there is a leading /
if (url.length() > 1 && url.charAt(0) == '/')
{
// remove the leading slash
url = url.substring(1);
}

return url;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: