Detailed description of facescontext objects in JSF

Source: Internet
Author: User
Tags abstract tree cookie names map class

Two classes are frequently used in the faces API. One is facescontext and the other is externalcontext. First, we will explain how to use facescontext.

For each JSF request, the facesservlet object obtains a javax. Faces. context.
An instance of the facescontext class. The facesservlet object transmits the following three objects from the Web container to the getfacescontext method of the javax. Faces. Context. facescontextfactory object to achieve this:

● Javax. servlet. servletcontext ● javax. servlet. servletrequest ● javax. servlet. servletresponse this means that the facescontext instance contains the status information of all requests required to process JSF requests. Figure 3-1 shows some other objects encapsulated in the facescontext instance. 3.2.1 obtain the current instanceA frequently used method is the static getcurrentinstance method, which returns the current facescontext instance. The signature of this method is as follows: public static facescontext getcurrentinstance () the following code obtains the current instance of facescontext using this method: facescontext = facescontext. getcurrentinstance (); 3.2.2 retrieve and modify the component treeThe most important content in the facescontext instance is the component tree of the Request page. The component tree is represented by the javax. Faces. Tree. Tree class (This section will discuss "use tree classes" later ). The tree attribute of the facescontext instance is a tree object. To obtain or modify a tree object, you can use the tree attribute reading method and the value assignment method: public abstract tree gettree () public abstract void settree (TREE tree) 3.2.3 add and retrieve messagesAn error may occur during the request processing lifecycle. For example, when the validators perform input verification, the verification may fail because the user entered an incorrect value; when a component tries to convert the input value to the type required by the module object bound to the component, it may also fail. All messages must be stored in the facescontext instance for later processing. For example, you may want to display an error message on the page to help you correct the error. The error message is represented by the javax. Faces. application. Message interface (further discussed in chapter 11th). You can add a message object to the facescontext instance by using the addmessage method of the facescontext class. The signature of this method is as follows: public abstract void addmessage (uicomponent component, message) If component is not empty, the newly added message is associated with component. Otherwise, it is not related to instances of any specific component. For example, when the validators fail to verify the component value, they can call the addmessage method of facescontext to pass in components with invalid values and a message object containing specific error messages. All the message objects added to the facescontext instance are added to a collection. You can call one of the two overload methods of the getmessages method to obtain the added message object: public abstract iterator getmessages () public abstract iterator getmessages (uicomponent component) the first form of call returns all message objects in an iterator, while the second form of call returns only the message objects associated with the given uicomponent. 3.2.4 Add and retrieve request processing eventsUicomponent can generate facesevent objects. For example, when you click a uicommand component, it generates an actionevent object (the actionevent class is a subclass of the facesevent class ). This facesevent object needs to be saved in the facescontext instance for processing the next event in the request lifecycle. You can use the addfacesevent method of the facescontext class to add a facesevent object to the facescontext instance. The signature of this method is as follows: public abstract void addfacesevent (facesevent event) to extract the previously added facesevent object, you can call the getfacesevents method. The signature is as follows: public abstract iterator getfacesevents () this method returns facesevent in the same order as in the queue. 3.2.5 write information to the response objectTo write information to the response object, the facescontext class provides two attributes: javax. Faces. Context. responsestream and javax. Faces. Context. responsewriter. Responsestream objects are used to output binary data, while responsewriter objects are used to output characters. The read and assign values of these attributes are as follows: public abstract responsestream getresponsestream () public abstract void setresponsestream (responsestream) public abstract responsewriter getresponsewriter () public abstract void setresponsewriter (responsewriter) 3.2.6 obtain and set regionsChapter 1 will discuss that JSF supports internationalization and localization. This means that you can decide what kind of response information to send based on your region. The Locale attribute stores the locale objects used in the pre-processing. In the initial state, the value of the locale attribute is the same as that specified in the web browser, but you can modify this value, therefore, the region used for sending the output will be independent of the region used by the browser. The read and assign values for this attribute are as follows: public abstract locale getlocale () public abstract void setlocale (locale) 3.2.7 operation request processing LifecycleThe facescontext class also provides two methods to interact with the request processing life cycle: ● after the processing in the current stage is complete, call the renderresponse method to notify the JSF implementation to transfer the control to the rendering response stage. That is to say, all other stages between the current stage and the present response stage are no longer executed. ● Call the responsecomplete method to tell JSF that the HTTP response to this request has been completed (for example, when HTTP redirection is used ). Therefore, after the current stage is complete, you must stop processing the request processing lifecycle. The signature of these methods is as follows: public abstract void renderresponse () public abstract void responsecomplete () 3.2.8 obtain other Request status informationThe status information of each other request is encapsulated in the externalcontext object. You can use the getexternalcontext method to obtain the object: public abstract externalcontext getexternalcontext. Use the methods provided by the externalcontext class to obtain the objects servletcontext, servletrequest, and servletresponse. These objects are required when constructing a facescontext instance. In addition, the externalcontext instance provides the wrapper method to obtain information that was originally required to be obtained from the servletcontext, servletrequest, and servletresponse objects by calling some methods. 3.3.1 obtain servletcontext, servletrequest, and servletresponse objectsYou can use the following method to obtain Servlet Information: ● getcontext this method can be used to obtain the servletcontext object associated with the current request in the Web application. The signature is as follows: public abstract object getcontext () ● getrequest this method can obtain the servletrequest object representing the request being processed. The signature is as follows: public abstract object getrequest () ● getresponse this method can obtain the servletresponse object representing the current response. The signature is as follows: all public abstract object getresponse () Methods return a java. lang. object object is not a servlet-specific type, so that JSF can be implemented independently of its running environment. For example, JSF can be used for both web containers and other containers, such as Portlet. 3.3.2 obtain the servletcontext featureThe getapplicationmap method returns a map object containing all feature name/value pairs in the servletcontext object. The signature of this method is as follows: public abstract Java. util. map getapplication () is an example. The following code obtains a feature called databaseutility: Object contextattribute = NULL; facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map contextmap = externalcontext. getapplicationmap (); If (contextmap! = NULL) contextattribute = contextmap. Get ("databaseutility "); 3.3.3 obtain the session object and Its FeaturesYou can access the session object associated with the current request through the externalcontext object. The getsession method can retrieve the current user's javax. servlet. HTTP. httpsession object. If the current user does not have a corresponding session object, the behavior of this method is determined by the input parameter: If a true value is input for this method, it creates a session object; otherwise, it returns NULL. The following is the signature of the getsession method: public abstract object getsession (Boolean create) This method is actually the package of the getsession method in the javax. servlet. http. httpservletrequest interface. The getsessionmap method returns a map object that contains all feature name/value pairs in the session object associated with the current request. The following is its method Signature: to obtain the features in the session object, public abstract java. util. getsessionmap () can call the get method of the map class and pass in the feature name to be obtained. The document does not specify whether to return null or an empty map object if the current request does not have a corresponding session object. Therefore, before calling the map get method, you must first check whether the map is null. The following code is used to obtain the session feature: Object sessionattribute = NULL; facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map sessionmap = externalcontext. getsessionmap (); If (sessionmap! = NULL) sessionattribute = sessionmap. Get (key); the key in the last row is a string containing the feature name. 3.3.4 obtain the initial parameters of the servletcontext objectThe getinitparameter method is the package of the getinitparameter method of the servletcontext object. This method can be used to extract the initial parameter value specified by the context-init element in the deployment descriptor (Web. xml file. The signature of this method is as follows: public abstract string getinitparameter (string parametername) for example, if the following context-init element is declared in the deployment descriptor: <context-param> <param-Name> contactperson </param-Name> <param-value> Scott Jobim </param-value> </context-param> A string in the following code the value of initparam is Scott Jobim. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); string initparam = externalcontext. getinitparameter ("contactperson"); The getinitparametermap method returns a map object containing all the initial parameters in the servletcontext object. The signature is as follows: public abstract java. util. Map getinitparametermap () uses the get method of the map object to obtain the value of an initial parameter and transmits the name of the initial parameter. For example, the following code outputs the value of the initial parameter databasename to the console. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map parammap = externalcontext. getinitparametermap (); If (parammap! = NULL) {system. Out. println (parammap. Get ("databasename "));} 3.3.5 obtain the features of the request objectThe getrequestmap method returns a map object containing all feature name/value pairs in the current request object. The method signature is as follows: public abstract Java. util. map getrequestmap () is an example. The following code can be used to extract the features in the request object: Object requestattribute = NULL; facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map requestmap = externalcontext. getrequestmap (); If (requestmap! = NULL) requestattribute = requestmap. Get (key); the key in the last row is a string containing the name of the property to be extracted. 3.3.6 access the parameter names and values in the request objectThe getrequestparametermap, getrequestparameternames, and getrequestparametervaluesmap methods can be used to access the parameter names and values in the request object. Getrequestparametermap returns a map object that contains all the parameter name/value pairs in the request object. The signature is as follows: public abstract Java. util. map getrequestparametermap () is an example. The following code can extract the value of the request parameter named ID: String id = NULL; facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map requestparametermap = externalcontext. getrequestparametermap (); If (requestparametermap! = NULL) id = (string) requestparametermap. Get ("ID"); The getrequestparameternames method returns an iterator containing all request parameter names. This method is actually the package of the servletrequest. getparameternames method. The difference is that getrequestparameternames of the externalcontext class returns an iterator instead of Java. util. enumeration. The signature of this method is as follows: public abstract java. util. iterator getrequestparameternames () as an example. The following code outputs all request parameter name/value pairs to the console. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map requestparametermap = externalcontext. getrequestparametermap (); iterator parameternames = externalcontext. getrequestparameternames (); While (parameternames. hasnext () {string parametername = (string) parameternames. next (); string parametervalue = (string) requestparamete RMAP. get (parametername); system. out. println (parametername + ":" + parametervalue);} The getrequestparametervaluesmap method returns a map object containing all the parameter name/value pairs in the request object. This method is similar to the getrequestparametermap method, but getrequestparametervaluesmap can return all values with the same parameter name. The get (key) method is called on the map object returned by this method, which is equivalent to obtaining the servletrequest of the current request and calling getparametervalues (key) on it ). That is to say, the map object returns a string number group. The signature of the getrequestparametervaluesmap method is as follows: public abstract java. util. Map getrequestparametervaluesmap () the Code in the following example outputs all the value of the Request Parameter ID to the console. String [] id = NULL; facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map requestparametervaluesmap = externalcontext. Equals (); If (requestparametervaluesmap! = NULL) {id = (string []) requestparametervaluesmap. get ("ID"); // print all values of idfor (INT I = 0; I <ID. length; I ++) {system. out. println (ID [I]) ;}} 3.3.7 obtain the name and value of the Request HeaderThe getrequestheadermap method returns a map object containing all the header/value pairs in the current request. The method signature is as follows: public abstract Java. util. map getrequestheadermap () For example, the following code extracts the Host Header Value: String host = NULL; facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map headermap = externalcontext. getrequestheadermap (); If (headermap! = NULL) {Host = (string) headermap. Get ("host"); system. Out. println (host);} note: the header name is case insensitive. For example, if the map objects returned by getrequestheadermap use host, host, and host as parameters to call the get method, the results are the same. The getrequestheadervaluesmap method is similar to the getrequestheadermap method. However, in the getrequestheader
Call the get method on the map object returned by the valuesmap method to obtain an array of strings. The signature of the getrequestheadervaluesmap method is as follows: public abstract java. util. Map getrequestheadervaluesmap () calls the get method on the map object returned by the getrequestheadervaluesmap method and returns a java. util. Enumeration value. The following code uses the getrequestheadervaluesmap method to obtain a map object containing all the header/value pairs, and then calls the get Method on this map object to obtain the values of all the accept-encoding headers, and output the result to the console. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map headervaluesmap = externalcontext. getrequestheadervaluesmap (); If (headervaluesmap! = NULL) {enumeration headers = (enumeration) headervaluesmap. get ("Accept-encoding"); While (headers. hasmoreelements () {string value = (string) headers. nextelement (); system. out. println (value );}} 3.3.8 obtain cookieThe getrequestcookies method is the package of the httpservletrequest. getcookies method. It returns an array of javax. servlet. http. Cookie objects, which are all cookies in the current request object. The signature of this method is as follows: public abstract cookie [] getrequestcookies (). For example, the following code Retrieves all cookie objects in the current request and then loops in the result array, output the names and values of all cookies. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); cookie [] cookies = externalcontext. getrequestcookies (); For (INT I = 0; I <cookies. length; I ++) {cookie = Cookies [I]; string cookiename = cookie. getname (); string cookievalue = cookie. getvalue (); system. out. println (cookiename + ":" + cookievalue);} getrequestcookiemap Returns a map object that contains all the cookies in the current request and uses the cookie name as the key. When the get method is called on this map object, a javax. servlet. http. Cookie object is returned. The signature of the getrequestcookiemap method is as follows: public abstract java. util. Map getrequestcookiemap (). For example, the following code retrieves the cookie object named password and outputs its value to the console. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); map cookiemap = externalcontext. getrequestcookiemap (); If (cookiemap! = NULL) {cookie = (cookie) cookiemap. Get ("password"); If (cookie! = NULL) system. Out. println ("value:" + Cookie. getvalue ();} Note: Cookie names are case sensitive. 3.3.9 locationsThe getrequestlocale method is the package of the servletrequest. getlocale method. It returns the locale object in the request object. The signature of this method is as follows: public abstract java. util. locale getrequestlocale () For example, the following code retrieves the user's location and outputs The Display language and country of the location. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); locale = externalcontext. getrequestlocale (); system. out. println ("language:" + locale. getdisplaylanguage (); system. out. println ("Country:" + locale. getdisplaycountry ()); 3.3.10 obtain the context pathGetrequestcontextpath is the wrapper of the httpservletrequest. getcontextpath method. It returns the context path of the Request context specified in the request URI. The method signature is as follows: the code segment under public abstract string getrequestcontextpath () outputs the context path of the request URI to the console: facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); system. out. println ("context path:" + externalcontext. getrequestcontextpath (); for URL http: // localhost: 8080/jsfch03/faces/test. for JSP, the return value of the getrequestcontextpath method is/jsfch03. The getrequestpathinfo method is the package of the httpservletrequest. getpathinfo method. It returns the additional path information associated with the URL sent by the client when the client initiates a request. This part of information follows the Servlet Path information, but before the query string. The signature of the getrequestpathinfo method is as follows: public abstract string getrequestpathinfo (). For example, the following code outputs the path information of the request URL. Facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); system. out. println ("Path Info:" + externalcontext. getrequestpathinfo (); for URL http: // localhost: 8080/jsfch03/faces/test. for JSP, the return value of the getrequestpathinfo method is test. JSP. 3.3.11 obtain the resource pathThe getresourcepaths method is the package of the getresourcepaths method of the servletcontext class. It returns a set object, which contains the resource path that matches the oldest path in the Web application with the input path parameter. Indicates that the path of the subdirectory ends. The returned path is relative to the Web application root path and starts. The signature of this method is as follows: public abstract Java. util. set getresourcepaths (string path) for example, consider the following code: facescontext = facescontext. getcurrentinstance (); externalcontext = facescontext. getexternalcontext (); Set resourcepaths = externalcontext. getresourcepaths ("/"); iterator = resourcepaths. iterator (); While (iterator. hasnext () {string Path = (string) iterator. next (); system. out. println (Path );} System. out. println ("----------------------------"); resourcepaths = externalcontext. getresourcepaths ("/WEB-INF"); iterator = resourcepaths. iterator (); While (iterator. hasnext () {string Path = (string) iterator. next (); system. out. println (PATH);} This code calls the getresourcepaths method twice, the first incoming "/", the second incoming "/WEB-INF ". If you run the above Code in a web application with a directory structure 3-2, the first set returned contains the following path:/order. JSP/index. JSP/styles.css/images // details. JSP/WEB-INF // checkout. JSP/browse. JSP/shoppingcart. JSP/search. JSP/menu. JSP second set contains the following path:/WEB-INF/faces-config.xml/WEB-INF/web. XML/WEB-INF/classes // WEB-INF/lib/Figure 3-2 test the getresourcespath directory structure getresourceasstream method is servletcontext. getresourceasstream package, which returns the java. io. the resource of the inputstream object. The method signature is as follows: public abstract java. Io. inputstream getresourceasstream (string path) 3.3.12 URL EncodingThe encodeurl method is httpservletresponse. the wrapper of the encodeurl method, which encodes a given URL by adding the session ID information. Alternatively, if this step is not required, the given URL is directly returned. The method signature is as follows: when the public abstract string encodeurl (string URL) uses JSF In the Portlet, The encodeactionurl and encoderesourceurl methods are very useful. Encodeactionurl forces the URL to be passed as a parameter, causing the action to play a role in the portal/Portlet. The signature of this method is as follows: the public abstract string encoderesourceurl (string SB) encoderesourceurl method forces the URL to be passed as a parameter and references the resource to play a role in the portal/Portlet. This method causes the URL to be redirected according to the specific entry. In fact, it simply returns an absolute URL. The following is the signature of the encoderesourceurl method: public abstract string encoderesourceurl (string SB) 3.3.13 dispatch requestsThe dispatchmessage method can distribute requests based on the current context. For servlet, it implements this by calling forward; For Portlet, it implements this by calling the include method. The signature of this method is as follows: public abstract void dispatchmessage (string requesturl) throws java. Io. ioexception, facesexception

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.