Search code examples
jsfprettyfaces

How to disable all URIs which are not mapped in pretty-config.xml


I want to whenever user types in address bar uri which isn't mapped in my pretty-config.xml file to get 404 error. My pretty-config looks like:

<?xml version="1.0" encoding="UTF-8"?>
<pretty-config xmlns="http://ocpsoft.org/schema/rewrite-config-prettyfaces" 
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
               xsi:schemaLocation="http://ocpsoft.org/schema/rewrite-config-prettyfaces>

<url-mapping id="landing">
    <pattern value="/" />
    <view-id value="/faces/index.xhtml" />
</url-mapping>

<url-mapping id="login">
    <pattern value="/login" />
    <view-id value="/faces/login.xhtml" />
</url-mapping>

</pretty-config>

For example when user types myapp.com/faces/login.xhtml application should return 404 error. How to do that?


Solution

  • I'd recommend using Rewrite (https://www.ocpsoft.org/rewrite) for this. It's already included in your project with PrettyFaces:

    package com.example;
    
    @RewriteConfiguration
    public class ExampleConfigurationProvider extends HttpConfigurationProvider
    {
       @Override
       public int priority()
       {
         return 10000000; // Very large priority # should occur last.
       }
    
       @Override
       public Configuration getConfiguration(final ServletContext context)
       {
         return ConfigurationBuilder.begin()
           .addRule()
             .when(
                // filter inbound requests only
                Direction.isInbound()
                // match all paths
                .and(Path.matches("/{p}"))
                // only catch requests if they were not already internally forwarded by another rule
                .and(Not.any(DispatchType.isForward())) 
             )
             // Show the 404 page.
             .perform(Forward.to("/404"))
             // Allow "p" to match any URL path
             .where("p").matches(".*");
        }
    }