JSF (JavaServer Faces)

xiaoxiao2021-03-06  106

JavaServer Pages (JSF) have been considered a major event in Java's web programming. With JSF, you can use web components on the web to capture events generated by user behavior. Not far more, Java Tools will support this technology, developing web applications will be similar to how we now develop Swing programs: drag and drop control, write event listeners. This article is a brief introduction of JSF, and provides an example of JSF to show event drive characteristics of JSF. To understand this article, you need to have a certain understanding of servlets, JSP, JavaBeans, with the label library.

First, a JSF application is a servlet / JSP application. It has a configuration descriptor, with a JSP page, customer custom label, static resource, and more. Different, JSF applications are event-driven. You determine the behavior of the application by writing an event listening class. Several steps need to establish a JSF application:

1. Establish a JSP page and package HTML elements with JSF components.

2. Write a JavaBean to keep the user to enter the status of component data.

3. Write an event listener to determine what should be reflected when the event occurs, such as the user clicks on a button or submits a form. JSF supports two events: ActionEvent and ValueChangeeevent. ActionEvent is for the user to submit a form and click button, and ValueChangeeevent is triggered when a JSF component changes.

Now let's take a look at the details of the JSF action.

What is JSF work?

The JSP page is a user interface for the JSF application. Each page includes some JSF components to describe web controls such as forms, input boxes, buttons, and more. Components can be embedded in another component, as the input box can be in the form. Each JSP page is represented as a component tree. JaveBeans get data and stores from the user's request.

This is interesting: Whenever the user does anything, if you click the button or submit a form, there is an event. The event message is then transmitted to the server via HTTP. At the server side, it is a Web container that is configured with a special servlet called Faces Servlet. Faces servlet (javax.faces.webapp.facesservlet) is an engine for all JSF applications. Each JSF application has a separate Faces Servlet in a web container. Another important object is javax.faces.context.facescontext, which includes all necessary information about the current user request.

The background processing of the Faces Servlet is quite complicated. However, you don't have to understand these details, just remember that the Faces Servlet creates a component tree for the JSP page, and the control of the component tree is correspondingly. Faces Servlet knows how to create a component tree because it has accessed all JSP pages in the current application. Faces Servlet also creates an EVENT object and passes it to all registered listeners. You can get the components of this page by FacesContext corresponding to the current request.

The event generated by the web control on the client browser is included in an HTTP request, and there is also other information such as browser types, request addresses. Therefore, all requests that need Faces Servlet processing must point to this servlet. Then how do you handle each HTTP request by calling Faces ServelT? It is easy, just use a servlet-mapping element with a servlet-maping element in the configuration descriptor to map to the Faces Servlet. Usually, you will use / faces / * style, as shown below:

faces servlet

javax.faces.webapp.facesservlet

1

faces servlet

/ faces / *

The request address must contain the style described in the element. This requirement is not easy to reach. It is also important to note that the element, which contains the Faces Servlet, has a element to determine if the application is loaded when the application is first started.

In order to capture the event generated by the component, you need to write a listener for this component and register it to this component. This can be done by embedding elements in the client tag indicating the component. For example, in order to let a run listener named jsfapp.myactionListener, the event generated by the command button called Submitbutton is captured, and the code as follows is written in your JSP page:

CommandName = "Submit">

An Action Listener must implement a javax.faces.event.ActionListener interface, and a value-change listner must implement a java.faces.event.valueChangeDLister interface. Let's create a simple JSF application to show how JSF is driven.

A simple JSF application

We will create a simple application that can be added to the two numbers. To run this app, you need to prepare Tomcat5 with JSF V1.0 EA4 (included in Java Web Services Developer Pack (JWSDP) 1.2). This app includes:

Adder.jsp JSP page.

Numberbean's JavaBean stores user data

MyActionListener event listener web.xml configuration description file

In order to make this application work normally, there are several JAR files, including JSF standard implementation and other class libraries. If you have a JWSDP 1.2, you can find these files you need under the JSFLIB directory. Copy these .jar files into the web-inf / lib directory. Here is the list of the entire .jar and .tld file:

JSF-API.JAR contains classes with Faces Servlet and other related javax.faces packets

JFS-ri.jar is the reference implementation of JSF

JSTL_L.JAR

Standard.jar

In addition, a JSF application requires the following libraries, which are part of the Apache Jakarta project:

Commons-beanutils.jar

Commons-digester.jar

Commons-logging.jar IS

The following few segments discuss each part of this JSF example. The last small segment, "compile and run", explain how JSF applications run.

Create a directory structure

First create a directory structure for your JSF application. In Tomcat, it is in a webApps directory. "Figure 1" describes the directory structure of an application called MyJSFAPP.

Write configuration descriptor

Like other Servlet / JSP applications, this application also requires a configuration description file. Such as "Listing 1" means.

Listing 1. The Deployment Descriptor (The Web.xml File)

"- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En"

"http://java.sun.com/dtd/web-app_2_3.dtd" ;;>

faces servlet

javax.faces.webapp.facesservlet

1

faces servlet

/ faces / *

There are two parts in this configuration description file.

Element Registration Faces Servlet,

Elements declare that any request address containing / faces / model must be passed to the Faces Servlet.

Create a JSP page

A JSP page called Adder.JSP provides a user interface, such as "Listing 2":

Listing 2.jsp Page

<% @ Taglib Uri = "http://java.sun.com/jsf/html" ;;

prefix = "h"%>

<% @ Taglib URI = "http://java.sun.com/jsf/core" ;; prefix = "f"%>

add 2 numbers </ title></p> <p></ hEAD></p> <p><body></p> <p><JSP: Usebean ID = "Numberbean" class = "jsfapp.numberbean"</p> <p>Scope = "session" /></p> <p><f: USE_FACES> <br /></p> <p><h: form id = "addform" formname = "addform"> <br /></p> <p>First Number: <br /></p> <p><h: infut_number id = "firstnumber" valueref =</p> <p>Numberbean.firstnumber /> <br /></p> <p>SECOND NUMBER:</p> <p><h: infut_number id = "secondnumber" valueref =</p> <p>"Numberbean.secondNumber" /> <br /></p> <p>RESULT:</p> <p><h: Output_number ID = "Output" ValueRef =</p> <p>"Numberbean.Result" /> <br></p> <p><h: command_button id = "submitbutton"</p> <p>Label = "add" CommandName = "Submit"></p> <p><f: an action_listener</p> <p>TYPE = "jsfapp.myactionListener" /></p> <p></ h: Command_Button></p> <p></ h: form></p> <p></ f: USE_FACES></p> <p></ body></p> <p></ html></p> <p>We first defined two labels, which used two label libraries for JSF: HTML and Core. The definition of this two label library can be found in the jsf-ri.jar file, so you don't have to worry about it. Their prefix is ​​H / f, respectively.</p> <p><% @ Taglib Uri = "http://java.sun.com/jsf/html" ;;</p> <p>prefix = "h"%></p> <p><% @ Taglib Uri = "http://java.sun.com/jsf/core" ;;</p> <p>prefix = "f"%></p> <p>This action element defines NumberBean Javabean as Session Scope.</p> <p><JSP: Usebean ID = "Numberbean" class = "jsfapp.numberbean"</p> <p>Scope = "session" /></p> <p>Then the JSF control is. Note that the JSF control needs to be embedded</p> <p>Tags:</p> <p><f: USE_Faces></p> <p>...</p> <p></ f: USE_FACES></p> <p>In this, there is a form.</p> <p><h: form id = "addform" formname = "addform"> ...</p> <p></ h: form></p> <p>Embedded in this form is two input_numbers, an Output_Number, with a command_button.</p> <p>The first number:</p> <p><h: input_number id = "firstnumber"</p> <p>VALUEREF = "Numberbean.firstnumber" /> <br /></p> <p>Second number:</p> <p><h: infut_number id = "secondnumber"</p> <p>VALUEREF = "Numberbean.secondNumber" /> <br /></p> <p>result:</p> <p><h: Output_number ID = "Output"</p> <p>VALUEREF = "Numberbean.Result" /> <br /></p> <p><h: command_button id = "submitbutton"</p> <p>Label = "add" CommandName = "Submit"></p> <p><f: an action_listener type = "jsfapp.myactionListener" /></p> <p></ h: Command_Button></p> <p>Attention to the event listener of the command button. "Figure 2" describes the components of this JSP page (slightly omitted).</p> <p>The primary component is a form, which has four subcomponents.</p> <p>Write object model</p> <p>In this app, you need to use a JavaBean to save two numbers and add results. "List 3" is this Javabean content: Numberbean</p> <p>Listing 3. The Numberbean Javabean</p> <p>Package JSFAPP;</p> <p>Public class numberbean {</p> <p>INT firstnumber = 0;</p> <p>INT secondnumber = 0;</p> <p>Public numberbean () {</p> <p>System.out.println ("CREATING Model Object");</p> <p>}</p> <p>Public void setfirstnumber (int Number) {</p> <p>Firstnumber = Number;</p> <p>System.out.println ("Set Firstnumber" Number);</p> <p>}</p> <p>Public int getFirstnumber () {</p> <p>SYSTEM.OUT.PRINTLN</p> <p>("Get Firstnumber" FirstNumber);</p> <p>Return firstnumber;</p> <p>}</p> <p>Public void setsecondnumber (int number) {</p> <p>SecondNumber = Number;</p> <p>System.out.println ("Set SecondNumber" Number;</p> <p>}</p> <p>Public int GetSecondNumber () {</p> <p>System.out.println</p> <p>("Get SecondNumber" SecondNumber;</p> <p>Return SecondNumber;</p> <p>}</p> <p>Public int getResult () {</p> <p>System.out.println</p> <p>("Get Result" (FirstNumber SecondNumber);</p> <p>Return firstnumber secondnumber;</p> <p>}</p> <p>Write an event listener</p> <p>The event listener of the command button is the most interesting part of this JSF application. It expresses an event to cause a listener to listen. The listener simply only output information to the console. However, it shows important information, such as the hierarchy of the JSP page component tree, is whose events are triggered. "Listing 4" display event listener:</p> <p>Listing 4. The action listener for the command button (MyActionListener.java)</p> <p>Package JSFAPP;</p> <p>Import java.util.iterator;</p> <p>Import javax.faces.component.uicomponent;</p> <p>Import javax.faces.context.facescontext;</p> <p>Import javax.faces.event.Actionevent;</p> <p>Import javax.faces.event.ActionListener;</p> <p>Import javax.faces.event.phaseid;</p> <p>Import javax.faces.tree.tree;</p> <p>Public class myActionListener imports anctionsListener {</p> <p>Public phaseid getphaseid () {</p> <p>System.out.println ("GetPhaseid Called");</p> <p>Return Phaseid.Apply_Request_VALUES;</p> <p>}</p> <p>Public void processaction (ACTIONEvent Event) {</p> <p>System.out.println ("ProcessAction Called");</p> <p>// the component what triggered the action event</p> <p>UIComponent component = event.getComponent ();</p> <p>System.out.println</p> <p>("THE ID of the component That Fired The Action</p> <p>Event: " Component.getComponentId ());</p> <p>// the action command</p> <p>String anctioncommand =</p> <p>Event.getActionCommand ();</p> <p>System.out.println</p> <p>("Action Command: ActionCommand);</p> <p>FacesContext FacesContext =</p> <p>FacesContext.getcurrentInstance ();</p> <p>Tree Tree = FacesContext.gettree ();</p> <p>UIComponent root = tree.getroot ();</p> <p>System.out.println</p> <p>("----------- Component Tree -------------");</p> <p>NavigateComponentTree (root, 0);</p> <p>System.out.println</p> <p>("------------------------------------");</p> <p>}</p> <p>Private void NavigateComponenttree</p> <p>(UIComponent Component, INT Level) {</p> <p>Itel caredren = component.getchildren ();</p> <p>// Indent</p> <p>For (int i = 0; i <level; i )</p> <p>System.out.print (""); //print company</p> <p>System.out.println (Component.getComponentId ());</p> <p>// Navigate Children</p> <p>While (children.hasnext ()) {</p> <p>UIComponent Child =</p> <p>(UIComponent) Children.next ();</p> <p>NavigateComponenttree (Child, Level 1);</p> <p>}</p> <p>}</p> <p>}</p> <p>Compilation and operation</p> <p>To compile this app, we go to myjsfapp / web-inf / class. If you use a Windows system, you can play the following command:</p> <p>Javac -classpath ../lib/jsf-api.jar;../lib/jsf-ri.jar;../../../../common/lib/servlet.jar jsfapp / *. Java</p> <p>Note that you must use the class library in the lib directory with the servlet.jar library.</p> <p>Then run Tomcat, enter the following address in the address bar:</p> <p>Http: // localhost: 8080 / myjsfapp / assets / adder.jsp</p> <p>Note that you use / faces / model before the file name of the JPS page. You can then see "Figure 3" as shown in the browser:</p> <p>At the console, you can see the following information:</p> <p>Model Object Created</p> <p>Get firstnumber 0</p> <p>Get SecondNumber 0</p> <p>Get Result 0</p> <p>getPhaseid Called</p> <p>Now enter two numbers in the two input boxes, then click the Add button. The browser will display the calculation result "as shown in Figure 4":</p> <p>More important, check the console and see the following information:</p> <p>Get firstnumber 0</p> <p>Get SecondNumber 0</p> <p>Processaction Called</p> <p>The ID of the component: SubmitButton</p> <p>Action Command: Submit</p> <p>----------- Component Tree -------------</p> <p>NULL</p> <p>AddForm</p> <p>FirstNumber</p> <p>SecondNumber</p> <p>OUTPUT</p> <p>SubmitButton</p> <p>----------------------------------------</p> <p>Set firstnumber 10</p> <p>Set SecondNumber 20</p> <p>Get firstnumber 10</p> <p>Get SecondNumber 20</p> <p>Get Result 30</p> <p>to sum up</p> <p>In this article, you have learned the most important feature of JSF from other servlet / JSP applications: Event drivers. You also created a simple application that contains a JSP page. More important, you write a listener that can respond to events.</p> <p>The JSF application in practical applications is much more complicated, usually a lot of JSP pages. In this case, you need to navigate from a page to another page. However, this should be the subject of another article.</p> <p>figure 1</p> <p>figure 2</p> <p>image 3</p> <p>Figure 4</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-103810.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="103810" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.054</b>, SQL: <b>12</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'ekQPdEgRvSzIReq6cMwnUYrn2pgmJmOSl9xAIXz4QEWBDU1ylpjK8MJ6vSMZVmApwDbwbTlPC0mkcuI49yyM_2FA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>