Combining JSP and JSF to create a perfect Web application

Source: Internet
Author: User

Java has gradually warmed up in recent years. With the introduction of Java SE 5 and Java SE 6, the future of Java is even more brilliant. However, Java-based JSP has been unable to lift the header before Java SE 5 was launched. The most important reason is that although JSP is very powerful, however, its biggest advantage is its biggest disadvantage. Its powerful functionality means complexity. In particular, there are not many visual tools for designing front-end interfaces, and they are not powerful enough. Therefore, designing JSP pages becomes complicated and cumbersome. However, at the same time as Java SE 5 was launched, Sun introduced a new assumerver Faces (JSF) specification to simplify JSP development. Thus, JSP is on the road to prosperity.

1. What is JSF?

JSF and JSP are new partners. JSP is a logic processing technology used in the background, while JSF is the opposite. It enables developers to quickly develop Java-based Web applications and 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 drag-and-drop edit operations with the support of some development tools. Users only need to drag the JSF component to the page, you can easily perform Web development. This is its biggest advantage as a componentized technology. The components we can use are not only simple input boxes, but also more complex components, such as table components such as able and Tree components.

As a standard technology, JSF has received support from many tool providers. At the same time, we will also have a lot of good free development tools available, not long ago Sun Java Studio Creator 2 and Oracle JDeveloper 10g were released as free development tools supporting JSF, it makes JSF quite angry. In addition, we also have some excellent commercial development tools to choose from, such as BEA Workshop (formerly M7 NitroX), Exadel, and MyEclipse plug-in development tools based on Eclipse, it brings great convenience to the vast majority of Eclipse users. IBM's Rational Application Developer and Borland's JBuilder are also good commercial development tools that support JSF visual development.

JSF is essentially different from traditional Web technologies. In traditional Web technologies, users need to capture browser requests, save the client status, and manually control page redirection. The emergence of JSF undoubtedly brings us great convenience. JSF provides an event-driven page navigation model that enables application developers to design the page stream of applications. Similarly to Struts, all page stream information is defined in the JSF configuration XML file (faces-config.xml), rather than hardcoded in the application. This greatly simplifies the development difficulty of developers and application development.

JSF is also a framework that follows the Model-View-controller (MVC) pattern. The View code and the application logic (Model) are completely separated, so that the applications using the JSF technology can well implement the separation of pages and code. All requests to the JSF page are processed by a front-end controller (FacesServlet). The system automatically processes the user's requests and returns the results to the user. This is not much different from the traditional MVC framework.

In JSF, not only the POJO technology is used, but also the IoC (or dependency injection-DI) technology similar to Spring is used. In the Backing Bean of JSF, we can put the data and operations required by the view into a Backing Bean. At the same time, thanks to the DI technology used by JSF, We can initialize the Managed Bean in the configuration file, and we can also easily integrate with Spring using similar technologies through this technology.

Ii. How to Use JSF in JSP

JSF can make full use of its functions only by combining it with JSP. JSF is integrated with JSP through the tag library. The tag library is equivalent to the server component of ASP. NET. JSF provides rich tag libraries that can generate various client models, such as HTML, WML, XML, and JavaScript. With these tags, you can easily create a large-scale client model and use these tags to automatically process client requests.

Next let's look at an example of how to make JSF and JSP work together. There are two libraries in JSF. The first is the kernel library, which contains various major labels, such as configuration components, management events, and verification input information. The main function of the second library is to correspond HTML and JSF tags. Each JSF tag corresponds to an HTML component. For example, the UIInput tag corresponds to the text box or password box in HTML.

In the JSF tag, the text input box is called inputText, And the password input library is called inputSecret. The following is a simple user interface program that combines 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> first JSF Program </title>
</Head>
<Body>
<F: view>
<H: form id = "simpleForm">
<H: outputText id = "favoriteLabel" value = "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 see how JSF is integrated with JSP. First, we can see a kernel label: view. Then there are several JSF components. Such as form, outputText, inputText, and commandButton. These components are put into the form to form a part. At the beginning of the program, you must use import to import two tag libraries. 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 the JSF tag library to be used in JSP. The kernel library uses the prefix f declaration, while the HTML library uses the prefix h declaration. These two prefixes are not mandatory, but only a suggestion. In the program, the kernel library must be used, because view must be used in all JSF pages. While HTML tags convert JSF tags into HTML components at runtime. This h prefix is not mandatory, but is recommended by the JSF specifications. In this way, our JSF program is easier to read.

There are several standard HTML statements after declaration, which will not be detailed in this article. Starting from <f: view>, It is a JSF statement. The Code is as follows:

<F: view>
<H: form id = "simpleForm">
<H: outputText id = "favoriteLabel" value = "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> A tag indicates the beginning of JSF, and its next tag form creates an HTML Form. The outputText label 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. Run the JSP program and get the result 1.


Figure 1 running result of the first JSF Program

Iii. How does JSP respond to JSF requests?

The above example shows how to use JSF in JSP. In this section, we can see how JSF processes requests.

Let's look at an example. This example is to convert degrees Fahrenheit to degrees Celsius. The program is converted when you click 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 = "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>

The first two lines of the program are to import the JSF core library and HTML library, which have been discussed earlier and will not be detailed here.

Let's take a look at how the JSF tag interacts with the backend. Since we use JSF in JSP, there is no difference between this and normal JSP. JSP is actually a Servlet. During the first run of JSP, the JSP compiler will. the JSP file is compiled into a Servlet and then called by the Servlet. Then, the Servlet receives data streams from the client. However, unlike general JSP programs, the JSF tag is called by the jsf api (in this way, the logic layer and the presentation layer can be separated). In addition, they are no different from common JSP labels.

When the UIComponent tag receives the doStartTag method, JSF uses these attributes to set the tag value. In this example, the inputText label is set based on its property value. The following is a JSF code snippet.

<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 label sets the attributes of id and value based on the corresponding values. In JSF, each attribute value is set through setAttribute (String name, Object value. However, we need to note that the JSF tag can specify the corresponding default value. This is similar to the system attribute in java. If you give an attribute sub-name, the system will return the value of this attribute. If you specify its default value and this property does not exist, the default value is returned.

Next let's take a look at the most important part of the above program, that is, the event processing of the UIInput component.

<F: valuechangeListener type = "tempconv. page. TCChangedListener"/>

In JSF, event processing is performed by the valuechangeListener tag. The event indicated by this label triggers an event when the value of the text box changes. However, it is interesting that this event is not submitted immediately, but is submitted to the backend only after the user clicks the "Submit" button. Therefore, this event request is also called a pre-commit. Finally, let's look at the code implementation of UICommand.

<Div>
<H: commandButton value = "convert" action = "# {tc. convert}">
</H: commandButton>
</Div>

The code above connects the convert () method to the UICommand. That is to say, after you click "Submit", the convert () method is executed. After the view label is encountered, JSFAPI calls the doEnd method to end the JSF program. After parsing this program, the JSF engine converts the corresponding JSF tag to an HTML component.

Finally, let's take a look at how JSP responds to the JSF event. The following is a Java code that responds to the JSF event.

Public class TCChangedListener implements ValueChangeListener
{
Public TCChangedListener ()
{
Super ();
}
// Event processing
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. The above program should pay attention to setting the corresponding color based on the input value. These values do not depend on JSP. Of course, you can also set them to null, and set their colors by JSP labels.

 

Related Article

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.