How to redirect to another page when an authenticated user accesses the login page

I was wondering if it is possible to redirect users if the specific c:if clausule is true ?

 <c:if test="#{loginController.authenticated}"> //redirect to index page </c:if> 
+6
source share
2 answers

Yes it is possible.

But I would suggest you apply a filter to /login.jsp and go to another page in the filter if the user has already logged in.

Here is an example that tells how to do this using a filter:

 public class LoginPageFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if(request.getUserPrincipal() != null){ //If user is already authenticated response.sendRedirect("/index.jsp");// or, forward using RequestDispatcher } else{ filterChain.doFilter(servletRequest, servletResponse); } } public void destroy() { } } 

Add this filter to the web.xml file

 <filter> <filter-name>LoginPageFilter</filter-name> <filter-class> com.sample.LoginPageFilter </filter-class> <init-param> <param-name>test-param</param-name> <param-value>This parameter is for testing.</param-value> </init-param> </filter> <filter-mapping> <filter-name>LoginPageFilter</filter-name> <url-pattern>/login.jsp</url-pattern> </filter-mapping> 
+8
source

Besides the Filter approach, you can also use <f:event type="preRenderView"> . Put this somewhere at the top of the view:

 <f:event type="preRenderView" listener="#{loginController.checkAuthentication}" /> 

And add this listener method to LoginController :

 public void checkAuthentication() throws IOException { ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); if (externalContext.getUserPrincipal() != null) { externalContext.redirect(externalContext.getRequestContextPath() + "/index.xhtml"); } } 

What all.

See also:

+3
source

Source: https://habr.com/ru/post/902184/


All Articles