【问题标题】:Redirect to a servlet by implicit navigation?通过隐式导航重定向到 servlet?
【发布时间】:2012-08-21 21:22:01
【问题描述】:

如何通过支持方法正确地重定向到 servlet?

class MyBean{ 
    public String doRedirect() {
        //some conditions
        return "newlocation";
    }
}


<h:commandButton value="Test" action="#{myBean.doRedirect}" />

这会将我重定向到 newlocation.xhtml。

但是如果我有一个 WebServlet 呢?

@WebServlet(urlPatterns = "/newlocation")

我怎样才能重定向到 servlet 而不是 xhtml 文件?

【问题讨论】:

    标签: java jsf jakarta-ee servlets


    【解决方案1】:

    您不能使用 JSF 导航处理程序导航到非 JSF 资源。

    直接使用ExternalContext#redirect()方法即可:

    public void doRedirect() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect("newlocation");
    }
    

    或者如果您不确定当前的请求路径:

    public void doRedirect() throws IOException {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ec.redirect(ec.getRequestContextPath() + "/newlocation");
    }
    

    【讨论】:

    【解决方案2】:

    您可以访问原始 HTTPServletResponse 并使用其 API 进行重定向

    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    response.sendRedirect(URL);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多