Reputation: 190
I would like to call a servlet /logout from a templateHeader.xhtml which is located in the folder templates as followed:
webapp
|-- form
| |-- form.xhtml
|-- WEB-INF
| |-- templates
| | |-- template.xhtml
| | |-- templateFooter.xhtml
| | |-- templateHeader.xhtml
|-- resources
|-- admin.xhtml
|-- login.xhtml
:
The problem is that I don't know how to call the servet because the path to servlet is not the same depending on the page you are on. I am looking for an equivalent of #{request.contextPath}/myPage but for the servlet. And just by curiosity, if I wanted to call a method myMethod() from a bean Login, how would I do?
I have followed this Kill session and redirect to login page on click of logout button but I think I am using it wrong. Note that I have also tried to add method="post" to the menuitem. Note also that the first menuitem of the code below is working.
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>
And finally the logout 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");
}
}
Upvotes: 1
Views: 838
Reputation: 12029
A couple of things I think you want to do.
Create a normal JSF controller (e.g LogoutController) method like...
public String logout() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.invalidate();
return "/login.xhtml?faces-redirect=true";
}
Change your menu item to..
<p:menuitem value="Quitter" action="${logoutController.logout}" icon="fa fa-sign-out"/>
Upvotes: 1