Sunday, January 19, 2014

JSF 2.2.x Tip of the Day: Custom JSF Exception Page including the default Facelets Exception Page

If you want to create a custom exception page in JSF and include the default exception page, you simply need to include one line of code.
1
<ui:include src="javax.faces.error.xhtml" />

This is an example of a custom exception page using the code above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    <h:head>
        <title>Custom Exception</title>
        <style type="text/css">
            h1{color: red;}
            span{font-weight: bold;}
        </style>
    </h:head>
    <h:body
        <h1>
Custom Exception</h1>
<ul>
<li id="dte"><span>Date/Time:</span> </li>
<li><span>User Agent:</span> #{header['user-agent']}</li>
<li><span>User IP:</span> #{empty header['x-forwarded-for'] ? request.remoteAddr : fn:split(header['x-forwarded-for'], ',')[0]}</li>
<li><span>Request URI:</span> <a href="#{requestScope['javax.servlet.error.request_uri']}">#{requestScope['javax.servlet.error.request_uri']}</a></li>
<li><span>Ajax Request:</span> #{facesContext.partialViewContext.ajaxRequest ? 'Yes' : 'No'}</li>
<li><span>Status Code:</span> #{requestScope['javax.servlet.error.status_code']}</li>
<li><span>Exception Type:</span> #{requestScope['javax.servlet.error.exception_type']}</li>
<li><span>Exception Message:</span> #{requestScope['javax.servlet.error.message']}</li>
</ul>
<ui:include src="javax.faces.error.xhtml" />
 
        <script type="text/javascript">
            window.onload = function() {
                document.getElementById('dte').innerHTML += (new Date()).toUTCString();
            };
        </script>
    </h:body>
</html>

The resulting page will look like the image below. Please note that we are including the default JSF exception page.

0 comments :

Popular Posts