Spring mvc 3 - HTTPS访问

Vir*_*gam 8 spring spring-mvc

如何强制仅通过HTTPS访问页面.需要通过Spring MVC 3配置文件来完成此操作.

Boz*_*zho 14

Spring-security有这样的配置.看到这里是怎么做的.简而言之 - 您强制频道使用https:

<http>
    <intercept-url pattern="/secure/**" access="ROLE_USER" 
        requires-channel="https"/>
    <intercept-url pattern="/**" access="ROLE_USER" 
        requires-channel="any"/>
</http>
Run Code Online (Sandbox Code Playgroud)

如果你不想使用spring-security,这是我写的一个拦截器:

@Component
public class SslInterceptor extends HandlerInterceptorAdapter {

    // no need to inject it for now..
    private PathMatcher pathMatcher = new AntPathMatcher();

    @Value("${base.url.secure}")
    private String secureRoot;

    @Resource(name="secureLocations")
    private List<String> secureLocations;

    @Value("${use.ssl}")
    private boolean useSsl;


    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {

        if (useSsl && !request.isSecure() && shouldForceSecure(request.getRequestURI())) {

            String redirectUrl = secureRoot + request.getRequestURI();
            if (request.getQueryString() != null) {
                redirectUrl += "?" + request.getQueryString();
            }
            // force session creation - thus it will be accessible to both the
            // secure and the insecure contexts
            request.getSession(true);
            response.sendRedirect(redirectUrl);
            return false;
        }

        return true;
    }

    private boolean shouldForceSecure(String path) {
        for (String pattern : secureLocations) {
            if (pathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)