Java has gradually heated up in recent years. With the launch of Java SE 5 and Java SE 6, the future of Java is even more brilliant. However, Java-based JSP has been unable to raise its head before the launch of Java SE 5. The most important reason is that although JSP is very powerful, its biggest advantage is also its biggest disadvantage. Powerful functions mean complexity, especially There are not many visual tools for designing front-end interfaces, and they are not powerful enough. Therefore, designing JSP pages becomes very complicated and cumbersome...
Java has gradually heated up in recent years. With the launch of Java SE 5 and Java SE 6, the future of Java is even more brilliant. However, Java-based JSP has been unable to raise its head before the launch of Java SE 5. The most important reason is that although JSP is very powerful, its biggest advantage is also its biggest disadvantage. Powerful functions mean complexity, especially There are not many visual tools for designing front-end interfaces, and they are not powerful enough. Therefore, designing JSP pages becomes very complicated and cumbersome. However, at the same time as Java SE 5 was launched, Sun launched a new JavaServer Faces (JSF for short) specification in order to simplify the development of JSP. This puts JSP on the bright road.
1. What is JSF?
JSF and JSP are a new pair. JSP is a technology used for background logic processing, while JSF is just the opposite. It is a technology that enables developers to quickly develop Java-based Web applications. It is a presentation layer technology. Currently, JSF1.2 has been officially added to Java EE 5 as a standard.
As a highly componentized technology, developers can implement drag-and-drop editing operations with the support of some development tools. Users only need to simply drag JSF components onto the page to easily perform Web development. This is the biggest benefit of it as a componentized technology. The components we can use are not only relatively simple input boxes, but also more complex components, such as table components like DataTable. Tree components like Tree and so on.
As a standard technology, JSF is also supported by quite a few tool providers. At the same time, we will also have many good free development tools available. Not long ago, Sun Java Studio Creator 2 and Oracle JDeveloper 10g were released as free development tools that support JSF, which brought a lot of vitality to JSF. In addition, we also have some excellent commercial development tools to choose from. Eclipse-based plug-in development tools such as BEA Workshop (formerly M7 NitroX), Exadel, and MyEclipse have brought great convenience to the majority of current Eclipse users. IBM's Rational Application Developer and Borland's JBuilder are also very good commercial development tools that support JSF visual development.
JSF is fundamentally different from traditional Web technology. Traditional Web technology requires users to capture browser requests, save client state, and manually control page redirection, etc. The emergence of JSF has undoubtedly brought us great convenience. JSF provides an event-driven page navigation model, which enables application developers to design the page flow of applications. Similar to the Struts approach, all page flow information is defined in the JSF configuration XML file (faces-config.xml) rather than hard-coded in the application. This greatly simplifies the development difficulty for developers and simplifies the development of applications.
At the same time, JSF is also a framework that follows the model-view-controller (MVC) pattern. It achieves the complete separation of view code (View) and application logic (Model), allowing applications using JSF technology to achieve a good separation of pages and code. All requests for JSF pages will be processed through a front-end controller (FacesServlet). The system automatically processes the user's request and returns the result to the user. This is not much different from the traditional MVC framework.
JSF not only uses POJO technology, but also uses Spring-like Inversion of Control (IoC) (or Dependency Injection-DI) technology. In JSF's Backing Bean, we can put the data and operations required by the view Put it into a Backing Bean. At the same time, thanks to the DI technology used by JSF, we can initialize Managed Bean in the configuration file. At the same time, we can also use this technology to easily integrate with Spring, which uses similar technology.
2. How to use JSF in JSP
JSF can fully exert its effect only by combining it with JSP. JSF is integrated through tag libraries and JSP. The tag library is equivalent to the server-side component of ASP.NET. JSF provides a very rich tag library, through which various client models can be generated, such as HTML, WML, XML and JavaScript. Through these tags, you can easily build large-scale client models and automatically handle client requests through these tags.
Next let's look at an example of how to make JSF and JSP work together. There are two libraries in JSF. The first one is called the kernel library, which contains various major tags, such as configuring components, managing events, validating input information, etc. The main function of the second library is to correspond to various tags of HTML and JSF. Each JSF tag corresponds to an HTML component. For example, the UIInput tag corresponds to the text box or password box in HTML.
The text input box in the JSF tag is called inputText, and the password input library is called inputSecret. The following is a simple user interface program combining JSF and JSP.
<%@ taglib uri=" http://java.sun.com/jsf/html " prefix="h" %>
<%@ taglib uri=" http://java.sun.com/jsf/core " prefix ="f" %>
<html>
<head>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=GB2312">
<title>The first JSF program </title>
</head >
<body>
<f:view>
<h:form id="simpleForm">
<h:outputText id="favoriteLabel" value="Please enter a number:"/>
<h:inputText id="favoriteValue" value= "#{simple.longValue}">
<f:validateLongrange maximum="30" minimum="0"/>
</h:inputText>
<p/>
<h:commandButton id="submit" value="Submit" action ="#{simple.simpleActionMethod}"/>
</h:form>
</f:view>
</body>
</html>
In the above code, we can understand how JSF is integrated with JSP. We can first see a kernel label: view. Then there are several JSF components. Such as form, outputText, inputText and commandButton. These components are placed in the form and become part of the form. At the very beginning of the program, two tag libraries must be imported using import. The code is as follows.
<%@ taglib uri=" http://java.sun.com/jsf/html " prefix="h" %>
<%@ taglib uri=" http://java.sun.com/jsf/core " prefix ="f" %>
The above two lines of code declare which JSF tag library to use in JSP. The kernel library is declared with the prefix f, while the HTML library is declared with the prefix h. These two prefixes are not required, but are only a suggestion. In the program, the kernel library must be used, because the view must be used in all JSF pages. The HTML tag converts the JSF tag into an HTML component at runtime. This h prefix is not necessary, but recommended by the JSF specification. In this way, we make our JSF program more readable.
After the declaration are several lines of standard HTML statements, which will not be described in detail in this article. Starting from <f:view>, it is a JSF statement. This code is as follows:
<f:view>
<h:form id="simpleForm">
<h:outputText id="favoriteLabel" value="Please enter a number:"/>
<h:inputText id="favoriteValue " value="#{simple.longValue}">
<f:validateLongrange maximum="30" minimum="0"/>
</h:inputText>
<p/>
<h:commandButton id="submit" value=" Submit "
action="#{simple.simpleActionMethod}"/>
</h:form>
</f:view>
</f:view> tag heralds the beginning of JSF, and its next tag form will create an HTML Form. The outputText tag is equivalent to the label component in HTML. The inputText tag is equivalent to the textField component in HTML. The commandButton tag is equivalent to the submit button in HTML. When you run this JSP program, you will get the effect shown in Figure 1.
3. How does JSP respond to JSF requests?
From the above example, we already know how to use JSF in JSP. In this part, let us take a look at how requests are processed in JSF.
First let's look at an example of converting Fahrenheit to Celsius. The program will make the transition when the user clicks the submit button.
<%@ taglib uri=" http://java.sun.com/jsf/html " prefix="h" %>
<%@ taglib uri=" http://java.sun.com/jsf/core " prefix ="f" %>
<html>
<head>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=GB2312">
<title>Temperature conversion program</title>
</head>
< body>
<f:view>
<h:form>
<div>
<h:outputText id="fahrenheitLabel" value="Please enter the Fahrenheit temperature:"/>
<span>
<h:inputText id="temperature" value=" #{tc.fahrenheitTemp}">
<f:validateDoublerange minimum="-100.0" maximum="100.0"/>
<f:valuechangeListener type="tempconv.page.TCChangedListener"/>
</h:inputText>
</span>
</div>
<div>
<h:outputText id="celsiusLabel" value="Celsius temperature:"/>
<span>
<h:outputText id="celsiusValue" value="#{tc.celsiusTemp}">
<f :convertNumber maxFractionDigits="3" type="number"/>
</h:outputText>
</span>
</div>
<div>
<h:commandButton value="Convert" action="#{tc.convert}" >
</h:commandButton>
</div>
</h:form>
</f:view>
</body>
</html>
In the first two lines of the program, the JSF core library and HTML library are imported. This has been done before. has been discussed and will not be discussed in detail here.
Let's take a look at how JSF tags interact with the backend. Since we are using JSF in JSP, there is no difference between this and normal JSP; JSP is actually a Servlet. When the JSP is run for the first time, the JSP compiler compiles the .JSP file into a Servlet and then calls it by the Servlet. The Servlet then receives the data stream from the client. But unlike ordinary JSP programs, JSF tags are called by the JSF API (this allows the separation of the logic layer and the presentation layer). Other than that, they are no different from ordinary JSP tags.
When a UIComponent tag receives the doStartTag method, JSF will use these properties to set the tag's value. For example, the inputText tag in this example will be set according to its attribute value. Below is the code snippet from JSF.
<h:inputText id="temperature" value="#{tc.fahrenheitTemp}">
<f:validateDoublerange minimum="-100.0" maximum="100.0"/>
<f:valuechangeListener type="tempconv.page.TCChangedListener" />
</h:inputText>
The inputText tag sets the id and value attributes according to the corresponding values. In JSF, each attribute value is set through setAttribute(String name, Object value). But what we need to note is that JSF tags can specify corresponding default values. This is somewhat similar to the system properties in Java. If you give a property name, the system will return the value of the property. If you specify its default value and the property does not exist, the default value will be returned.
Next, let's take a look at the most important part of the above program, which is the event handling of the UIInput component.
<f:valuechangeListener type="tempconv.page.TCChangedListener"/>
In JSF, event processing is completed by the valuechangeListener tag. The event represented by this label triggers an event when the value of the text box changes. But what's interesting is that this event is not submitted immediately. Instead, the event and the corresponding data are not submitted to the backend until the user clicks the "Submit" button. Therefore, this event request is also called pre-commit. Finally, let's look at the code implementation of UICommand.
<div>
<h:commandButton value="Conversion" action="#{tc.convert}">
</h:commandButton>
</div>
The above code connects the convert() method and UICommand, that is to say , after clicking the "Submit" button, the convert() method will be executed. After encountering the view tag, the JSF program results, and JSFAPI finally calls the doEnd method to end the JSF program. After parsing this program, the JSF engine converts the corresponding JSF tags into HTML components.
Finally, let's take a look at how JSP responds to JSF events. Below is a piece of Java code that responds to JSF events.
public class TCChangedListener implements ValueChangeListener
{
public TCChangedListener()
{
super();
}
// Event handling
public void processValueChange(ValueChangeEvent event)
throws AbortProcessingException
{
UIComponent comp = event.getComponent();
Object value = event.getNewValue();
if ( null != value)
{
float curVal = ((Number) value).floatValue();
Map values = comp.getAttributes();
if (curVal < 0)
{
values.put("styleClass", "red");
}
else
{
values.put("styleClass", "black");
}
}
}
To respond to JSF events, you must implement the ValueChangeListener interface in the JSF library. What should be noted in the above program is that the corresponding color is finally set according to the input value. These values are not dependent on JSP. Of course, you can also set them to null and let the JSP tags set their colors.