Java Servlet Technology - 网页重定向

Redirections in HTTP

URL redirection, also known as URL forwarding, is a technique to give more than one URL address to a page, a form, or a whole Web site/application. HTTP has a special kind of response, called a HTTP redirect, for this operation.

Redirects accomplish numerous goals:

  • Temporary redirects during site maintenance or downtime
  • Permanent redirects to preserve existing links/bookmarks after changing the site’s URLs, progress pages when uploading a file, etc.

302 Found

The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header. A browser redirects to this page but search engines don’t update their links to the resource (in ‘SEO-speak’, it is said that the ‘link-juice’ is not sent to the new URL).

Location

The Location response header indicates the URL to redirect a page to. It only provides a meaning when served with a 3xx (redirection) or 201 (created) status response.

In cases of redirection, the HTTP method used to make the new request to fetch the page pointed to by Location depends on the original method and the kind of redirection:

  • 303 (See Also) responses always lead to the use of a GET (See Also) responses always lead to the use of a GET method.
  • 307 (Temporary Redirect) and 308 (Temporary Redirect) and 308 (Temporary Redirect) and 308 (Temporary Redirect) and 308 (Temporary Redirect) and 308 (Permanent Redirect) don’t change the method used in the original request.
  • 301 (Moved Permanently) and 302 (Found) don’t change the method most of the time, though older user-agents may (so you basically don’t know).

All responses with one of these status codes send a Location header.

In cases of resource creation, it indicates the URL to the newly created resource.

实践

环境

操作系统:

Windows 10 x64

集成开发环境:

Eclipse IDE for Enterprise Java and Web Developers (includes Incubating components)

Version: 2021-09 (4.21.0)

Build id: 20210910-1417

服务器:

apache-tomcat-9.0.55

客户端:

谷歌浏览器:版本 96.0.4664.93(正式版本) (64 位)

新建项目

新建 Dynamic Web Project

在这里插入图片描述

使用 HttpServletResponse.sendRedirect(String) 进行重定向

RedirectServlet 类:

package com.mk.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/redirect")
public class RedirectServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(response.getClass().getCanonicalName());
        
        /*
         * Sends a temporary redirect response to the client using the specified
         * redirect location URL. This method can accept relative URLs; the servlet
         * container must convert the relative URL to an absolute URL before sending
         * the response to the client. If the location is relative without a leading
         * '/' the container interprets it as relative to the current request URI.
         * If the location is relative with a leading '/' the container interprets
         * it as relative to the servlet container root.
         */
        response.sendRedirect("index");
    }
}

IndexServlet 类:

package com.mk.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/index")
public class IndexServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("index.html");
    }
}

src/main/webapp/index.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>首页</title>
    </head>
    <body>
        <p>首页</p>
    </body>
</html>

测试

启动服务器,启动谷歌浏览器,打开开发者工具网络选项卡,访问 http://localhost:8080/hello-servlet/redirect,请求成功之后,可以看到:

同理,如果你直接访问 http://localhost:8080/hello-servlet/index,最终也会被重定向至 http://localhost:8080/hello-servlet/index.html

在这里插入图片描述

使用状态码和响应头进行重定向

重定向的本质是服务器向客户端(浏览器)发送 302 状态码和 Location 响应头。

修改 RedirectServlet 类,使用状态码和响应头进行重定向:

package com.mk.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/redirect")
public class RedirectServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(response.getClass().getCanonicalName());
        
        String url = "index";
        
        response.setStatus(HttpServletResponse.SC_FOUND);
        response.setHeader("Location", url);
    }
}

修改 IndexServlet 类,使用状态码和响应头进行重定向:

package com.mk.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/index")
public class IndexServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        
        String url = scheme + "://" + serverName + ":" + serverPort + "/" + contextPath + "/index.html";
        
        response.setStatus(HttpServletResponse.SC_FOUND);
        response.setHeader("Location", url);
    }
}

测试

启动服务器,启动谷歌浏览器,打开开发者工具网络选项卡,访问 http://localhost:8080/hello-servlet/redirect,请求成功之后,可以看到:

在这里插入图片描述

参考

Servlet 网页重定向

Web technology for developers > HTTP > Redirections in HTTP

Web technology for developers > HTTP > HTTP response status codes > 302 Found

Web technology for developers > HTTP > HTTP headers > Location

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值