Java get ajax request

Inside JSF 2.0’s Ajax and HTTP GET Support

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Unlike previous releases of JavaServer Faces (JSF), JSF 2.0 supports HTTP GET requests and full Ajax integration. JSF 1.x releases sent all server requests using HTTP POST (hence, no support for GET requests) and offered virtually no support for Ajax integration. With support for these techniques, this newest version of the Java component UI framework enables developers to build truly dynamic web pages simply and easily.

At the highest level, JSF technology provides an API for creating, managing, and handling UI components and a tag library for using components within a web page. The JSF 2.0 release simplifies the web developer’s life by providing the following:


  • Reusable UI components for easy authoring of web pages
  • Well defined and simple transfer of application data to and from the UI
  • Easy state management across server requests
  • Simplified event handling model
  • Easy creation of custom UI components

In this article, we drill down into JSF 2.0’s support for GET requests and Ajax integration, as well as the productive features that this support makes possible. For demonstration, we refer to aspects of a simple application throughout the article. The demo application is an online quiz that allows a registered user to answer five simple questions that test his or her general knowledge. Towards the end of the quiz, the application displays the score.

Using GET Requests in JSF 2.0

To support GET requests, JSF 2.0 introduced the concept of View Parameters. View Parameters provide a way to attach query parameters to URLs. You use the tag to specify the query parameters.

Take this code for example:

In this example, the value of the parameter previousScore will be automatically picked up and pushed into the property oldScore of the recordBean . So, when a request like this comes for a URL:

displayData.jspx?previousScore=10

The value of the bean property oldScore will be set to 10 when the request is processed, which avoids manually setting the value or using a listener. Another interesting point to notice is that like any other component the tag supports conversion and validation. Hence, there is no need for separate conversion/validation logic.

Table 1 lists the new tags in JSF 2.0 related to support for the GET request.

Figure 1. New Tags Related to GET Requests






































Tag Description
h:button Renders a button that generates a GET request without any handcoding of URLs
h:link Renders a link that generates a GET request without any handcoding of URLs
h:outputStylesheet Refers to a CSS resource
h:outputScript Refers to a JavaScript resource
f:event Registers a specification-defined or a user-defined event
f:ajax Enables associated component(s) to make Ajax calls
f:metadata Declares the metadata facet for this view
f:viewParam Used in to define a view parameter that associates a request parameter to a model property
f:validateBean Delegates the validation of the local value to the Bean Validation API
f:validateRegex Uses the pattern attribute to validate the wrapping component
f:validateRequired Ensures the presence of a value

Bookmarking Support

Because all JSF 1.x interactions with the server use only HTTP POST requests, those JSF versions don’t support bookmarking pages in a web application. Even though some tags supported the construction of URLs, it was a manual process with no support for dynamic URL generation. JSF 2.0’s support for HTTP GET requests provides the bookmarking capability with the help of new renderer kits.

A new UI component UIOutcomeTarget provides properties that you can use to produce a hyperlink at render time. The component allows bookmarking pages for a button or a link. The two HTML tags that support bookmarking are h:link and h:button . Both generate URLs based on the outcome property of the component, so that the author of the page no longer has to hard code the destination URL. These components use the JSF navigation model to decide the appropriate destination.

Take the following code for example:

This bookmarking feature provides an option for pre-emptive navigation (i.e., the navigation is decided at the render response time before the user has activated the component). This pre-emptive navigation is used to convert the logical outcome of the tag into a physical destination. At render time, the navigation system is consulted to map the outcome to a target view ID, which is then transparently converted into the destination URL. This frees the page author from having to worry about manual URL construction.

Support for Ajax

Previous releases of JSF had no or limited support for Ajax integration. The new release provides good support for integration of Ajax in JSF.

The default implementation provides a single JavaScript resource that has the resource identifier jsf.js . This resource is required for Ajax, and it must be available under the javax.faces library. The annotation @ResourceDependency is used to specify the Ajax resource for the components, the JavaScript function jsf.ajax.request is used to send information to the server in an asynchronous way, and the JavaScript function jsf.ajax.response is used for sending the information back from the server to the client.

On the client side, the API jsf.ajax.request is used to issue an Ajax request. When the response has to be rendered back to the client, the callback previously provided by jsf.ajax.request is invoked. This automatically updates the client-side DOM to reflect the newly rendered markup.

The two ways to send an Ajax request by registering an event callback function are:

JavaScript Function jsf.ajax.request

The function jsf.ajax.request(source, event, options) is used to send an asynchronous Ajax request to the server. The code snippet below shows how you can use this function:

 onclick=”jsf.ajax.request(this,event, 
);return false;”/>

The first argument in the function represents the DOM element that made an Ajax call, while the second argument (which is optional) corresponds to the DOM event that triggered this request. The third argument is composed of a set of parameters, which is sent mainly to control the client/server processing. The available options are execute , render , onevent , onerror , and params .

Tag

JSF 2.0 enables page authoring with , which is a declarative approach for making Ajax requests. You can use this tag instead of manually coding the JavaScript for Ajax request calls. This tag serves two roles, depending on the placement. You can nest it within any HTML component or custom component. If you nest it with a single component, it will associate an Ajax action with that component.

The tag has four important attributes:


  • render – ID or a space-delimited list of component identifiers that will be updated as a result of the Ajax call
  • execute – ID or a space-delimited list of component identifiers that should be executed on the server
  • event – The type of event the Ajax action will apply to (refers to a JavaScript event without the on prefix)
  • onevent – The JavaScript function to handle the event

Consider the following code from the login page of the online quiz application. The code validates the input of the email field by sending an Ajax call for every keystroke (see Figure 1). The validation is done by a managed bean method that acts as a value change listener.

” size=”20″ required=”true” valueChangeListener=”#”> 



” />

Figure 1. Using Ajax to Validate the Input: The online quiz application validates email field input by sending an Ajax call for every keystroke.

Here, is nested within the emailId inputText component. For every keyup event that is generated, an Ajax call is sent to the server, which invokes the valueChangeListener . By default, the component in which the tag is nested is executed on the server. So, the execute attribute is not specified. Also, for an input component, the default event is valueChange , so the event attribute is also not used. The render attribute indicates that the outputText component emailResult should be updated after the Ajax call.

If you place this tag around a group of components, it will associate an Ajax action with all the components that support the events attribute.

In this example, input1 and link1 will exhibit Ajax behavior on a mouseover event.

In this example, input1 and link1 exhibit Ajax behavior on keyup and mouseover events, respectively.

Using the Ajax tag enhances the markup of the associated component to include a script that triggers the Ajax request. This the page author to issue Ajax requests without having to write any JavaScript code.

Conclusion In this article, we discussed the new Ajax and HTTP GET support in JSF 2.0. These new features enable developers to build truly dynamic web pages simply and easily.

Acknowledgements

The authors would like to sincerely thank Mr. Subrahmanya (SV, VP, ECOM Research Group, E&R) for his ideas, guidance, support and constant encouragement and Ms. Yuvarani Meiyappan (Lead, E&R) for kindly reviewing this article and for her valuable comments.

About the Authors

Sangeetha S. works as a Senior Technical Architect at the E-Commerce Research Labs at Infosys Technologies. She has over 10 years of experience in design and development of Java and Java EE applications. She has co-authored a book on ‘J2EE Architecture’ and also has written articles for online Java publications.

Nitin KL works at the E-Commerce Research Labs at Infosys Technologies. He is involved in design and development of Java EE applications using Hibernate, iBATIS, and JPA.

Ananya S. works at the E-Commerce Research Labs at Infosys Technologies. She is involved in design and development of Java EE applications using Hibernate, iBATIS, and JPA.

Источник

jQuery Ajax – интеграция сервлетов: создание законченного приложения

В Интернете есть много учебных пособий, которые объясняют некоторые вещи о веб-разработке на Java с использованием сервлетов и страниц JSP, однако я никогда не находил краткого, достаточно простого для начинающих , учебное пособие. Подобное руководство должно объяснить весь процесс создания простого веб-приложения, включая интерфейс, бэкэнд и, что наиболее важно, способы, которые кто-то может использовать для взаимодействия с ними обоими . Недостаточно показать, как получать информацию с сервера, важно также знать, как дифференцировать информацию в структурированном виде , а также знать, как вносить изменения в бэкэнд через среду приложения .

В этом посте мы хотим достичь цели – провести весь процесс создания полноценного «игрушечного» веб-приложения . Это «игрушечное» приложение в том смысле, что оно делает только две вещи, и мы не используем никаких дополнительных функций, чтобы сделать окружающую среду красивой. Цель приложения будет простой:

  • Добавьте название группы со списком альбомов (разделенных запятыми) и нажмите кнопку «Отправить» , чтобы добавить их в базу данных.
  • Нажмите «Показать группы!» кнопку, чтобы получить список групп, или «Показать группы и альбомы!» Кнопка, чтобы получить список групп с их альбомами.

Внешний вид приложения настолько прост, насколько это возможно , но его код – это все, что вам нужно для создания собственных динамических веб-приложений, которые чаще всего называются приложениями CRUD ( C reate, R ead, U pdate, D elete ). Они называются так, потому что все их функциональные возможности могут быть абстрагированы от этих самых основных команд.

Прежде чем приступить к созданию приложения шаг за шагом, давайте рассмотрим все инструменты, с которыми мы будем работать в этом примере:

  • Затмение Луны
  • Java 7
  • Tomcat 7 (сервер веб-приложений)
  • Gson 2.3 (библиотека Google Java)
  • JQuery 2.1.1 (библиотека Javascript)

1. Интерфейс (страница JSP)

Здесь особо нечего сказать. Если вы следовали другим примерам, вы узнаете, как легко создать динамический веб-проект в Eclipse и создать страницу index.jsp в папке WebContent . Это будет главная страница нашего приложения, и мы не будем использовать другие страницы. Конечно, это всегда зависит от типа приложения, которое вам нужно создать, но для наших нужд здесь достаточно одной страницы.

Источник

Читайте также:  Javascript find children element
Оцените статью