Combine JSP and JSF to create a perfect web application-JSP instance learning tutorial

Source: Internet
Author: User
JavaIn recent years JavaSe 5 and JavaThe launch of Se 6, JavaThe future is even more brilliant. However JavaBasic JSPIn JavaSe 5 has been unable to lift its head before its launch. The most important reason is JSPAlthough the function is very powerful, its biggest advantage is its biggest disadvantage. Its powerful function means complexity. In particular, there are not many visualization tools to design the front-end interface, and it is not powerful enough. Therefore, design JSPThe page becomes very complex and cumbersome. However JavaWhile se 5 was launched, sun wanted to simplify JSPDevelopment difficulty, launched a new JavaServer faces (JSF) specification. So that JSPOn the road to kangzhuang.

  1. What is JSF?

JSF andJSPIs a new partner.JSPIs used for background logic processing technology, while JSF is the opposite, enabling developers to quickly develop based onJavaWeb application technology is a presentation layer technology. Currently, jsf1.2 has been officially added as a standardJavaEe 5.

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 sunJavaStudio creator 2 andOracleJdeveloper 10 Gb is released as a free development tool supporting JSF, which makes JSF very 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.

  2. HowJSPUsing JSF

JSF only passes andJSPIn order to make full use of its functions. JSF uses the tag library andJSPFor integration. The tag library is equivalentASP. Net. JSF provides rich tag libraries that can generate various client models, suchHtml, 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 how to make JSF andJSPExamples of working 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 database isHtmlCorresponds to various JSF labels. Each JSF tag corresponds to oneHtmlComponent. For example, the uiinput tag correspondsHtmlText Box or password box in.

In the JSF tag, the text input box is called inputtext, And the password input library is called inputsecret. Below is a simple JSF andJSPUser Interface Program.

<% @ 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 consistentJSPIntegrated. 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 declareJSPWhich JSF tag library is used in. The kernel library uses the prefix F statement, whileHtmlThe database uses the prefix H Statement. 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. WhileHtmlThe tag converts the JSF tagHtmlComponent. This H prefix is not mandatory, but recommended by the JSF specification. In this way, our JSF program is easier to read.

Several lines of standards after the declarationHtmlStatement. 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 createsHtmlForm. The outputtext tag is equivalentHtmlLabel component. The inputtext label is equivalentHtmlTextfield component in. The commandbutton label is equivalentHtml. Run thisJSPProgram.

JSP and JSF combined src = "http://www.webjx.com/upfiles/20070116/20070116105931_01.jpg" _ fcksavedurl = "" http://www.webjx.com/upfiles/20070116/20070116105931_01.jpg "" _ fcksavedurl = "" http://www.webjx.com/upfiles/20070116/20070116105931_01.jpg "" to create a perfect web application>
Figure 1 running result of the first JSF Program

  III,JSPHow to respond to JSF requests

From the above example, we already know howJSPIn 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 andHtmlLibrary, which has been discussed earlier and will not be detailed here.

Let's take a look at how the JSF tag interacts with the backend. Because we areJSP. Therefore, this is the same as the normalJSPThere is no difference;JSPActually, it is servlet.JSPTheJSPThe compiler will.JSPAfter the file is compiled into a servlet, it is called by the servlet, and then the servlet receives the data stream sent from the client. But in generalJSPThe difference between a program is that JSF labels are called by the jsf api (which can be separated by the logic layer and the presentation layer ).JSPThere is no difference between 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 tagHtmlComponent.

Finally, let's take a look.JSPHow to respond to JSF events. The following is a response to the JSF event.JavaCode.

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 are not dependentJSP. Of course, you can also set them to nullJSPLabel to set their colors.
 

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.