Search code examples
jsfurljsf-2navigation

Why does the page change in JSF, but not the URL?


I have simple test web-application: First Page - index.xhtml:

<?xml version='1.0' encoding='UTF-8' ?>
<html>
 <h:head>
    <title>Facelet Title</title>
 </h:head>
 <h:body>
    First page
    <h:form>
        <h:commandButton value="Go to Next page" action="next"/>
    </h:form>
 </h:body>
</html>

and Next Page - next.xhtml:

<?xml version='1.0' encoding='UTF-8' ?>
<html>
<h:head>
    <title>Facelet Title</title>
 </h:head>
 <h:body>
    Next page
    <h:form>
        <h:commandButton value="Go to First page" action="index"/>
    </h:form>
 </h:body>
</html>

When I run my application i have that url on browser:

http://localhost:8080/Test/ 

and index.xhtml as first page.

Then when I click "Go to Next page" i have url

http://localhost:8080/Test/index.xhtml

and next.xhtml page. And when I click "Go to First page" page changes (to index.xhtml) but url its

http://localhost:8080/Test/next.xhtml

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <context-param>
     <param-name>javax.faces.PROJECT_STAGE</param-name>
     <param-value>Development</param-value>
 </context-param>
 <listener>
     <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
 </listener>
 <servlet>
     <servlet-name>Faces Servlet</servlet-name>
     <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
     <servlet-name>Faces Servlet</servlet-name>
     <url-pattern>*.xhtml</url-pattern>
 </servlet-mapping>
 <session-config>
     <session-timeout>
         30
     </session-timeout>
 </session-config>
 <welcome-file-list>
     <welcome-file>index.xhtml</welcome-file>
 </welcome-file-list>
</web-app>

What should I do to make that the first page in my application has a URL,

http://localhost:8080/Test/index.xhtml 

rather than

http://localhost:8080/Test/

?

I use Tomcat (TomEE)/7.0.37


Solution

  • You're using command buttons (POST form submit buttons) for plain page-to-page navigation. This is completely wrong. You should be using plain buttons (GET navigation buttons) for this instead.

    Replace the

    <h:form>
        <h:commandButton value="Go to Next page" action="next"/>
    </h:form>
    

    by

    <h:button value="Go to Next page" outcome="next" />
    

    Note: you don't need a <h:form> at all.

    Your concrete problem of "one URL behind" is caused because you're seeing the URL of <h:form> itself being reflected in browser address bar instead of the URL of the form submit's result page. Open the JSF page in your webbrowser, rightclick and View Source and look closer at <form action> value.

    See also: