从 template.xhtml 调用 servlet /logout

Calling a servlet /logout from a template.xhtml

我想从位于文件夹模板中的 templateHeader.xhtml 调用 servlet /logout,如下所示:

webapp
 |-- form
 |    |-- form.xhtml
 |-- WEB-INF
 |    |-- templates
 |    |    |-- template.xhtml
 |    |    |-- templateFooter.xhtml
 |    |    |-- templateHeader.xhtml
 |-- resources
 |-- admin.xhtml
 |-- login.xhtml
 :

问题是我不知道如何调用 servet,因为 servlet 的路径因您所在的页面而异。我正在寻找 #{request.contextPath}/myPage 的等价物,但用于 servlet。出于好奇,如果我想从登录 bean 调用方法 myMethod(),我该怎么做?

我遵循了这个 Kill session and redirect to login page on click of logout button 但我认为我用错了。请注意,我还尝试将 method="post" 添加到菜单项。另请注意,下面代码的第一个菜单项正在运行。

templateHeader.xhtml

<ui:composition 
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">
 <p:layoutUnit id="top" position="north" size="50">
  <h:form> 
   <p:menubar>
    <p:menuitem value="Satisfact'IT" url="#{request.contextPath}/admin.xhtml" icon="fa fa-home" />
    <p:menuitem value="Quitter" action="${pageContext.request.contextPath}/logout" icon="fa fa-sign-out"/>
   </p:menubar>
  </h:form>
 </p:layoutUnit>
</ui:composition>

template.xhtml

<?xml version='1.0' encoding='ISO-8859-1' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"
      >    
    <h:head>
 </h:head>
    <h:body>
  <p:layout fullPage="true" >   
      <ui:insert name="header" >
          <ui:include src="commonHeader.xhtml" />
      </ui:insert>
        
      <ui:insert name="footer" >
          <ui:include src="commonFooter.xhtml" />
      </ui:insert>
  </p:layout>
    </h:body>
</html>

最后注销 servlet

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
 @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/login.xhtml");
    }
}

我认为你想做的几件事。

创建一个普通的 JSF 控制器(例如 LogoutController)方法,例如...

public String logout() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    session.invalidate();
    return "/login.xhtml?faces-redirect=true";
}

将您的菜单项更改为..

<p:menuitem value="Quitter" action="${logoutController.logout}" icon="fa fa-sign-out"/>