http 301 302重定向跳转

在过滤器的doFilter方法中实现重定向

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) {

// 强转为HttpServletRequest和HttpServletResponse  

HttpServletRequest httpReq = (HttpServletRequest)request; 

HttpServletResponse httpResp = (HttpServletResponse)response;

//拿到URL

String URL = httpReq.getRequestURL().toString();

//假设redirectUrl(HttpServletRequest httpReq)方法可以判定是否重定向,如果重定向则返回目标URL,否则返回空串

String redirectUrl = redirectUrl(httpReq);

if (StringUtils.isNoneBlank(redirectUrl)) {

    //写入状态码301和重定向目标URL      

    httpResp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

    httpResp.setHeader("Location",redirectUrl);

}else {

       //不拦截的放行            

    chain.doFilter(request,response);

}

}

分割线

方法 httpResp.sendRedirect(redirectUrl);

等同于

httpResp.setStatus(302);

httpResp.setHeader(“Location”,redirectUrl);

返回302用这个,一般不建议302,因为SEO无法追踪

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页