如何在 Servlet 中发送重定向到 JSP 页面 [英] How to send redirect to JSP page in Servlet

查看:41
本文介绍了如何在 Servlet 中发送重定向到 JSP 页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 servlet 中完成处理并且结果有效时,我需要将响应重定向到另一个 JSP 页面,例如 Web 内容文件夹中的 welcome.jsp.我该怎么做?

When I'm done processing in a servlet, and the result is valid, then I need to redirect the response to another JSP page, say welcome.jsp in web content folder. How can I do it?

例如:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {

         // Some processing code here ...

         // How do I redirect to another JSP here when I'm ready?

    } catch (Exception e) {
        throw new ServletException(e);
    }
}

推荐答案

HttpServletResponse#sendRedirect(String location) 方法.

将其用作:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

或者,查看 HttpServletResponse#setHeader(String name, String value) 方法.

Alternatively, look at HttpServletResponse#setHeader(String name, String value) method.

通过添加位置头来设置重定向:

The redirection is set by adding the location header:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");

这篇关于如何在 Servlet 中发送重定向到 JSP 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆