AndroidWorld - Diễn đàn Android Việt Nam, forum Android, nơi trao đổi thông tin kiến thức về lập trình Android, phần mềm Android, rom cook điện thoại Android, tin tức công nghệ
Environmental variables are used by the operating system to save settings (default values, locations of resources) to be used by Windows or by processes launched by users. There are two types of environmental variables:
user variables that are specific to a particular Windows user account;
system variables are always visible, regardless of the used user account.
Even if these variables are usually defined and initialized automatically when you install the system or other applications, there are situations in which the user must manually define them to put at the disposal of applications. The considered scenario is to set environment variables to enable the compilation and execution of Java applications from the command line (command prompt) or by using an IDE like Eclipse. By installing the Java SDK, system variables about the location of executables (compiler, java virtual machine) are not defined or initialized automatically. Testing is done by opening command prompt (Start -> cmd) and trying to launch the compiler with the command
C:\Users\Catalin>javac.exe
If there is no system variable to indicate where to look for the this executable, the system will give an error like:
'javac' is not recognized as an internal or external command, operable program or batch file.
The solution to this problem is given by setting the system variables: JAVA_HOME, PATH and CLASSPATH:
Open the Control Panel -> System or Security –> System; the same thing can be done by right-clicking on MyComputer and choosing Properties
System window in Windows 7
2. Choose Advanced System Settings option
System properties window in Windows
3. Choose the Environment Variables option
Environment variables in Windows
4. In the System variables section it is selected New5. Define the variable name, JAVA_HOME and its value C:\Program Files\Java\jdk1.6.0_16 (for this example JDK version 1.6.0 was installed in C:\Program Files\Java\jdk1.6.0_16 folder; if needed, modify this value to reflect the real situation) 6. Insert a new system variable named, CLASSPATH and its value %JAVA_HOME%\jre\lib
New system variable
7. For PATH, if it already exists, select it and choose the Edit option; in the editor add the value;%JAVA_HOME%\bin (the new values are separated by a semicolon from the existing ones) Testing the system variables is done by opening a new command prompt window (Start -> cmd) and trying to launch the compiler with the command:
C:\Users\Catalin>javac Usage: javac where possible options include: -g Generate all debugging info ...
Tạo một package mới với tên tùy ý bên trong của thư mục src. Class Spring Controller extends đến org.springframework.web.servlet.mvc.AbstractController. Để tạo ra một Class Controller mới kích chuột phải vào thư mục src và tạo ra một lớp java mới, hãy nhập tên Controller class và tên super class và nhấn nút Finish.
Copy đoạn mã sau vào trong lớp HelloWorldController.
return new ModelAndView("welcomePage","welcomeMessage", message);
}
public void setMessage(String message) {
this.message = message;
}
}
HelloWorldController class có message property được thiết lập thông qua setter injection. HelloWorldController class sẽ ghi đè lên của phương pháp handleRequestInternal() để xử lý yêu cầu. Sau khi xử lý của yêu cầu handleRequestInternal() phương thức trả về một ModelAndView đối tượng trở về DispatcherServlet.
DispatcherSevlet, như tên cho thấy, là một servlet duy nhất để quản lý quá trình xử lý yêu cầu toàn bộ. Khi yêu cầu được gửi đến của DispatcherServlet nó đại diện công việc bằng cách gọi các bộ điều khiển thích hợp để xử lý yêu cầu. Giống như bất kỳ servlet khác DispatcherServlet cần phải được cấu hình trong mô tả triển khai web như được hiển thị.
Ở đây tên servlet là dispatcher. Theo mặc định các DispatcherServlet sẽ tìm một tên tập tin dispatcher-servlet.xml để nạp cấu hình của Spring MVC. Tên tập tin được tạo thành bởi việc ghép tên servlet ("dispatcher") với "-servlet.xml". Ở đây chúng ta sử dụng của của url-pattern là ". htm" inorder để ẩn công nghệ triển khai cho người sử dụng.
Những redirect.jsp sẽ được gọi đầu tiên khi chúng ta thực thi các ứng dụng web Spring. Đây là file jsp duy nhất bên ngoài thư mục WEB-INF và nó ở đây để cung cấp một chuyển hướng đến của DispatcherServlet. Tất cả của views khác cần được lưu giữ dưới thư mục WEB-INF để họ có thể được gọi chỉ thông qua quy trình controller.
Để tạo một tập tin cấu hình bean kích chuột phải vào thư mục WebContent và chọn New -> Other. Hộp thoại sau xuất hiện.
Chọn cấu hình Spring Bean tập tin và kích Next.
Nhập tên file là "dispatcher-servlet.xml" và nhấn vào nút Finish.
Bây giờ các tập tin cấu hình bean của Spring được tạo ra, chúng ta cần phải cấu hình Controller và các lớp ViewResolver. Những mã sau đây cho thấy làm thế nào để làm điều này.
When your database contains a large amount of data you do not want to load all these items into memory. ZK provides many methods for handling large amounts of data including:
Live data scrolling
Load on demand Trees
Paging components
One of the most convenient ways in which to handle a large amount of data is using a paging mechanism.
Introducing huge data with paging
However, normally the paging mechanism will load all the data into the grid via the model. This Small Talk guides you through a method of handling large amounts (in this case 1,000,000 database entries) of data using a small memory footprint.
The basic premise of the Small Talk is to store a list of users within a database, including their first name, surname and phone number.
Demo
Creating the database
We create a database named livedata and create a table named tblusers. We will provide the following columns, id (INT, AI, PK), first_name (VARCHAR), last_name(VARCHAR) and phone(VARCHAR).
The SQL statement to create the table is provided below
1
2
3
4
5
CREATETABLEtblusers (id int(10) NOTNULLAUTO_INCREMENT,
first_name varchar(200) NOTNULL,
last_name varchar(200) NOTNULL,
phone varchar(20) NOTNULL, PRIMARYKEY(id) )
ENGINE=InnoDB DEFAULTCHARSET=utf8;
The database screen
We have introduced a database screen which allows you to quickly setup and test your database connection. This is the first page that you arrive at when running the sample, if you have any problems you can manually edit the DatabaseInteraction class and recompile it.
Interacting with the database
Linking the application with the database is the easy part and involves creating a DAO to handle the interaction. The DAO, in this instance, only consists of functions to insert and retrieve news items from the database. Please refer to the UserDAO for more details.
The connection is handled via the MySQL J/Connector with a new connection being made for each operation. Please note that a new connection for each operation is NOT the best method of implementation, a connection pool would be far more efficient so please do not use the code for production level software. Building the model
The model needs to represent our user utilizing Java’s Object Orientated features, hence we implement a Java class named User which includes getters and setters for every field present in the database.
The code within the User class is included below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
publicclassUser {
privateint_id;
privateString _firstName;
privateString _lastName;
privateString _phone;
publicString getFirstName() {
return_firstName;
}
publicvoidsetFirstName(String firstName) {
this._firstName = firstName;
}
publicString getLastName() {
return_lastName;
}
publicvoidsetLastName(String lastName) {
this._lastName = lastName;
}
publicString getPhone() {
return_phone;
}
publicvoidsetPhone(String phone) {
this._phone = phone;
}
publicvoidsetId(intid) {
this._id = id;
}
publicintgetId() {
return_id;
}
}
With the User class implemented along with the functions to retrieve them from the database we need to construct the model.
The PagingListModel and the AbstractPagingListModel
To make the implementation of a paging model easier a base class which we can easily extend was created by me.
AbstractPagingListModel
The AbstractPagingListModel was created by myself (it is included in the source zip) to take most of the hard work away when implementing a paging system which limits the memory use. The AbstractPagingListModel extends the AbstractListModel provided by ZK and hence has to override two functions:
1
2
3
publicObject getElementAt(intindex)
publicintgetSize()
These two functions are used to manipulate an internal list which contains the retrieved items from the database. This is not done all at once but on a page per page basis. For example if a database table had 1,000,000 entries and the pageSize was 20, there would only be 20 items in memory at any given time.
The function getElementAt returns an element from a model at a particular index. The getElementAt function accesses a local List which contains the data retrieved from the data source (in the case of this Small Talk it is a database).
It is tempting to use this function to directly access the database and retrieve items one by one, while this is tempting it not the best practice as it would require multiple queries to database and thus be slower than one query.
The getSize function returns the size of the local model, in the case of the example this is 20. It is important that you do not return the total number of items in the database as this would lead to a large amount of memory being used.
Functions we need to override
The AbstractPagingModel requires us to override two functions, these are:
These two functions provide the model with the data for a given page and retrieve the total amount of items in the database table. This information can come from any data source, the decision is up to us.
The constructor
The constructor takes two integer arguments, startPageNumber and pageSize which are multiplied together to retrieve the item number to start from. This item number is then used in a database query to retrieve the list needed. The database query works by using SQL LIMIT to define the starting point (startPageNumber*pageSize) and the number of Users to retrieve (pageSize).
Having retrieved the appropriate number of Users we need to store these in memory, hence the amount of Users in memory will only be your pageSize. This functionality is provided by an internal List.
PagingListModel
The PagingListModel overrides the required functions and provides a constructor as follows:
The basic GUI is very simple and consists of two parts
The button which generates 1,000,000 database entries
The paging area (including Grid and paging components)
Separation of the Paging component and the Grid
One of the most important features of this small talk is the fact that the Paging and Grid component are separated. The interaction between the two is implemented by ourselves and not automatically done by ZK. It is possible to autowire this functionality however, this would require calling the setPaginal function which we have already established is not a good idea in this case.
The markup below is the ZUL code from our index.zul
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<windowtitle="Huge data demo"border="normal"apply="org.zkoss.zklargelivelist.controllers.MainUserController">
<labelvalue="If you need to generate 1,000,000 entries please press this button!"/>
Please note that the Window component uses the MainUserController to respond to any events fired by the GUI. The controller is discussed in the next section.
Controller functionality
The controller handles two GUI events and overrides the doAfterCompose method. Firstly let us deal with the doAfterCompose method and explain what it does. The method is called after the components have been initialized. This allows us to manipulate the components before the user interacts with them.
We create our own custom row renderer to format the data and then refresh the model. The refresh model function will create a new PagingListModel and attach that model to the grid, hence displaying the first page of users. Notice the speed and low memory usage of this as we only pull the amount of users that we require for one page and hold that in memory!
refreshModel
1
2
3
4
5
6
7
8
9
10
11
12
13
privatevoidrefreshModel(intactivePage){
userPaging.setPageSize(_pageSize);
model = newPagingListModel(activePage, _pageSize);
if(_needsTotalSizeUpdate) {
_totalSize = model.getTotalSize();
_needsTotalSizeUpdate = false;
}
userPaging.setTotalSize(_totalSize);
dataGrid.setModel(model);
}
When refreshing the model the first thing we do is set the pageSize of the paging system, this is always set to 20, however in your own custom implementations it can be changed to any value you like. After setting the page size and creating the new PagingListModel we set the total size of the data in the paging system, this is a count of the number of items in the database. Finally the model is attached to the dataGrid using the dataGrid's setModel method.
Messagebox.show("There are already 1,000,000 entries in the database!");
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
The other two functions are related to handling GUI events, the first is onClick$btnGenerate which is used to generate 1,000,000 entries in our database. This functionality is self explanatory and not the focus of the Small Talk so we will move onto the second function onPaging$userPaging.
finalPagingEvent pe = (PagingEvent) event.getOrigin();
_startPageNumber = pe.getActivePage();
refreshModel(_startPageNumber);
}
The function is small but is essential in regulating the model, the function retrieves the active page from the Paging event and then refreshes the model. Upon refreshing the model as described above the model is recreated and then set to the data grid, thus moving the paging along.
Important information
setPaginal
It is important that you do not set the paging element of your listbox or grid. It is not advisable to have grid controlling a paginal component where the total number of items doesn’t match the number of grid’s list items.
pageSize and totalSize
To retrieve the pageSize you need to use the method getPageSize() of the paging component rather than the grid or listbox. In addition we have to make sure we set the total size of the paging component to that of the total number of items in your database table, or what is returned from the query.