javascript
angular java_带有Angular JS的Java EE 7 –第1部分
angular java
今天的帖子將向您展示如何使用Java EE 7和Angular JS構(gòu)建一個非常簡單的應(yīng)用程序。 在去那里之前,讓我告訴您一個簡短的故事:
我必須承認,我從來都不是Java語言的忠實擁護者,但是我仍然記得我第一次使用它。 我不記得確切的年份,但大概是90年代中期。 我的頁面上有3幀(是的幀!還記得嗎?那段時間很受歡迎),當(dāng)我單擊第3幀上的鏈接時,我想重新加載2幀。 當(dāng)時,Javascript被用來在網(wǎng)頁上做一些花哨的事情,并不是每個瀏覽器都支持Javascript,甚至有些瀏覽器甚至要求您打開它。 快速發(fā)展到今天,景觀發(fā)生了巨大變化。 Javascript現(xiàn)在是完整的開發(fā)堆棧,您可以開發(fā)僅用Javascript編寫的整個應(yīng)用程序。 對我來說不幸的是,有時我仍然認為我回到了90年代,并且對Javascript的評價不高,因此這是我嘗試更好地了解Javascript的嘗試。
為什么選擇Java EE 7?
好吧,我喜歡Java,新的Java EE版本非常不錯。 使用Wildfly或Glassfish時 不會太詳細,速度很快。 它為您提供了滿足您需要的大量規(guī)范,這是Java世界的標準。
為什么選擇Angular JS?
我可能正在關(guān)注有關(guān)Angular的大肆宣傳。 由于我對Javascript的經(jīng)驗不足,所以我不太了解這些提議,因此我只是聽從一些朋友的建議,并且我也注意到上一個Devoxx對Angular的廣泛接受。 每個進行Angular演講的房間都坐滿了,所以我想嘗試一下,自己找個機會。
應(yīng)用程序
對于應(yīng)用程序,這是一個帶有分頁的簡單列表,以及一個提供列表數(shù)據(jù)的REST服務(wù)。 每次我啟動一個新的企業(yè)項目時,通常通常是我們編寫代碼的第一件事:創(chuàng)建表,存儲一些數(shù)據(jù)并列出一些隨機數(shù)據(jù),所以我認為這是適當(dāng)?shù)摹?
設(shè)置
- Java EE 7
- 角JS
- ng-grid
- UI引導(dǎo)程序
- 野蠅
代碼(最終!)
后端– Java EE 7
從后端開始,讓我們定義一個非常簡單的Entity類(為簡單起見,省略了一些代碼):
人.java
@Entity public class Person {@Idprivate Long id;private String name;private String description;}如果您不熟悉Java EE JPA規(guī)范,則可以通過使用注釋@Entity連接到具有相同名稱的數(shù)據(jù)庫表和使用注釋@Id標識表主數(shù)據(jù)庫來將對象類建模到數(shù)據(jù)庫表中鍵。
接下來是persistence.xml :
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1"xmlns="http://xmlns.jcp.org/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"><persistence-unit name="myPU" transaction-type="JTA"><properties><property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/><property name="javax.persistence.schema-generation.create-source" value="script"/><property name="javax.persistence.schema-generation.drop-source" value="script"/><property name="javax.persistence.schema-generation.create-script-source" value="sql/create.sql"/><property name="javax.persistence.schema-generation.drop-script-source" value="sql/drop.sql"/><property name="javax.persistence.sql-load-script-source" value="sql/load.sql"/></properties></persistence-unit> </persistence>我在Java EE 7上最喜歡的兩個新功能:現(xiàn)在,您可以使用屬性javax.persistence.schema-generation.*以標準方式運行sql,并且如果您不提供默認數(shù)據(jù)源,它還將您綁定到默認數(shù)據(jù)源。 因此,在這種情況下,將為我們的應(yīng)用程序使用內(nèi)部Wildfly H2數(shù)據(jù)庫。
最后,要提供列表數(shù)據(jù),我們需要查詢數(shù)據(jù)庫并將其公開為REST服務(wù):
PersonResource.java
@Stateless @ApplicationPath("/resources") @Path("persons") public class PersonResource extends Application {@PersistenceContextprivate EntityManager entityManager;private Integer countPersons() {Query query = entityManager.createQuery("SELECT COUNT(p.id) FROM Person p");return ((Long) query.getSingleResult()).intValue();}@SuppressWarnings("unchecked")private List<Person> findPersons(int startPosition, int maxResults, String sortFields, String sortDirections) {Query query = entityManager.createQuery("SELECT p FROM Person p ORDER BY " + sortFields + " " + sortDirections);query.setFirstResult(startPosition);query.setMaxResults(maxResults);return query.getResultList();}public PaginatedListWrapper<Person> findPersons(PaginatedListWrapper<Person> wrapper) {wrapper.setTotalResults(countPersons());int start = (wrapper.getCurrentPage() - 1) * wrapper.getPageSize();wrapper.setList(findPersons(start,wrapper.getPageSize(),wrapper.getSortFields(),wrapper.getSortDirections()));return wrapper;}@GET@Produces(MediaType.APPLICATION_JSON)public PaginatedListWrapper<Person> listPersons(@DefaultValue("1")@QueryParam("page")Integer page,@DefaultValue("id")@QueryParam("sortFields")String sortFields,@DefaultValue("asc")@QueryParam("sortDirections")String sortDirections) {PaginatedListWrapper<Person> paginatedListWrapper = new PaginatedListWrapper<>();paginatedListWrapper.setCurrentPage(page);paginatedListWrapper.setSortFields(sortFields);paginatedListWrapper.setSortDirections(sortDirections);paginatedListWrapper.setPageSize(5);return findPersons(paginatedListWrapper);} }該代碼與普通的Java POJO完全一樣,但是使用Java EE批注來增強行為。 @ApplicationPath("/resources")和@Path("persons")將在url yourdomain/resources/persons處公開REST服務(wù), @GET標記要由http GET方法和@Produces(MediaType.APPLICATION_JSON)調(diào)用)的邏輯@Produces(MediaType.APPLICATION_JSON)將REST響應(yīng)格式化為JSON格式。 只需幾個注釋就可以了。
為了更容易地交換分頁列表所需的信息,我還創(chuàng)建了以下包裝器類:
PaginatedListWrapper.java
public class PaginatedListWrapper<T> {private Integer currentPage;private Integer pageSize;private Integer totalResults;private String sortFields;private String sortDirections;private List<T> list; }我們已經(jīng)完成了后端工作。
UI – Angular JS
為了顯示數(shù)據(jù),我們將使用Angular JS。 Angular通過附加的自定義標簽屬性擴展了傳統(tǒng)HTML,以遵循MVC方法來綁定以Javascript變量表示的數(shù)據(jù)。 因此,讓我們看一下我們的html頁面:
index.html
<!DOCTYPE html> <!-- Declares the root element that allows behaviour to be modified through Angular custom HTML tags. --> <html ng-app="persons"> <head><title></title><script src="lib/angular.min.js"></script><script src="lib/jquery-1.9.1.js"></script><script src="lib/ui-bootstrap-0.10.0.min.js"></script><script src="lib/ng-grid.min.js"></script><script src="script/person.js"></script><link rel="stylesheet" type="text/css" href="lib/bootstrap.min.css"/><link rel="stylesheet" type="text/css" href="lib/ng-grid.min.css"/><link rel="stylesheet" type="text/css" href="css/style.css"/> </head><body><br><div class="grid"><!-- Specify a JavaScript controller script that binds Javascript variables to the HTML.--><div ng-controller="personsList"><!-- Binds the grid component to be displayed. --><div class="gridStyle" ng-grid="gridOptions"></div><!-- Bind the pagination component to be displayed. --><pagination direction-links="true" boundary-links="true"total-items="persons.totalResults" page="persons.currentPage" items-per-page="persons.pageSize"on-select-page="refreshGrid(page)"></pagination></div> </div></body> </html>除了Javascript和CSS聲明外,其中幾乎沒有代碼。 非常令人印象深刻。 Angular也有大量現(xiàn)成的組件,因此我使用ng-grid來顯示數(shù)據(jù)和提供分頁組件的UI Bootstrap 。 ng-grid也具有分頁組件,但是我更喜歡UI Bootstrap分頁組件。
仍然缺少一些東西。 發(fā)生所有情況的Javascript文件:
person.js
var app = angular.module('persons', ['ngGrid', 'ui.bootstrap']); // Create a controller with name personsList to bind to the html page. app.controller('personsList', function ($scope, $http) {// Makes the REST request to get the data to populate the grid.$scope.refreshGrid = function (page) {$http({url: 'resources/persons',method: 'GET',params: {page: page,sortFields: $scope.sortInfo.fields[0],sortDirections: $scope.sortInfo.directions[0]}}).success(function (data) {$scope.persons = data;});};// Do something when the grid is sorted.// The grid throws the ngGridEventSorted that gets picked up here and assigns the sortInfo to the scope.// This will allow to watch the sortInfo in the scope for changed and refresh the grid.$scope.$on('ngGridEventSorted', function (event, sortInfo) {$scope.sortInfo = sortInfo;});// Watch the sortInfo variable. If changes are detected than we need to refresh the grid.// This also works for the first page access, since we assign the initial sorting in the initialize section.$scope.$watch('sortInfo', function () {$scope.refreshGrid($scope.persons.currentPage);}, true);// Initialize required information: sorting, the first page to show and the grid options.$scope.sortInfo = {fields: ['id'], directions: ['asc']};$scope.persons = {currentPage : 1};$scope.gridOptions = {data: 'persons.list',useExternalSorting: true,sortInfo: $scope.sortInfo}; });Javascript代碼非常干凈且井井有條。 請注意如何將所有內(nèi)容添加到應(yīng)用程序控制器中,從而使您可以將業(yè)務(wù)邏輯上的關(guān)注點多重分離。 為了實現(xiàn)所需的行為,我們只需要添加一些函數(shù)即可通過調(diào)用REST服務(wù)來刷新列表,并監(jiān)視網(wǎng)格數(shù)據(jù)以刷新視圖。 這是最終結(jié)果:
下一步:
對于與這些系列相關(guān)的以下帖子,我打算:
- 實施過濾
- 實施細節(jié)視圖
- 實施下一個/上一個瀏覽
- 部署在云端
- 管理Javascript依賴項
資源資源
您可以從我的github存儲庫中克隆完整的工作副本,然后將其部署到Wildfly。 您可以在此處找到有關(guān)部署它的說明。 也應(yīng)該在Glassfish上工作。
Java EE – Angular JS源
更新資料
同時,我用有關(guān)“ 管理Javascript依賴項”的帖子更新了原始代碼。 請從1.0版下載此文章的原始來源。 您還可以克隆存儲庫,并使用以下命令從發(fā)行版1.0中檢出標記: git checkout 1.0 。
希望您喜歡這個帖子! 讓我知道您是否對此有任何評論。
翻譯自: https://www.javacodegeeks.com/2014/07/java-ee-7-with-angular-js-part-1.html
angular java
總結(jié)
以上是生活随笔為你收集整理的angular java_带有Angular JS的Java EE 7 –第1部分的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果11拍照夜间模式如何打开
- 下一篇: 通过TLS发送的Java邮件