温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Servlet怎么跳转

发布时间:2026-09-01 06:12:05 来源:亿速云 阅读:95 作者:小樊 栏目:编程语言

在 Java Servlet 中,“跳转”通常有两种常见方式:请求转发(Forward) 和 重定向(Redirect)。它们区别很大,下面详细说明。


一、请求转发(Forward)

特点:

  • 在服务器内部完成
  • 浏览器地址栏 不变
  • 只有一次请求
  • 可以共享 request 域中的数据

使用方式:

request.getRequestDispatcher("/target.jsp").forward(request, response);

示例:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("msg", "登录成功");
        request.getRequestDispatcher("/success.jsp").forward(request, response);
    }
}

✅ 适合:页面跳转、后台处理、共用数据


二、重定向(Redirect)

特点:

  • 浏览器重新发起请求
  • 地址栏 会改变
  • 有两次请求
  • request 中的数据丢失

使用方式:

response.sendRedirect("target.jsp");

示例:

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.sendRedirect("login.html");
    }
}

✅ 适合:登录退出、防止表单重复提交


三、Forward vs Redirect 对比

对比项 Forward Redirect
地址栏 不变 改变
请求次数 1 次 2 次
数据共享 可以 不可以
跳转范围 同一 Web 应用 任意 URL

四、常见错误

❌ 转发后还写代码:

forward(...);
System.out.println("还会执行");

✅ 建议加 return;

❌ 重定向路径写错:

sendRedirect("/project/page.jsp"); // 易错

✅ 一般写相对路径或加 request.getContextPath()


如果你是想 跳到另一个 Servlet / JSP / HTML / 外部网站,可以告诉我具体场景,我可以给你最合适的写法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手