jax-rs (sử dụng jersey) (P1)


jax-rs (sử dụng jersey) (P1)

  1. Tạo Rest service trên java sử dụng gói jersey
  2. Gọi Rest service từ trang html với java script

Trong bài này chúng ta sẽ tìm hiểu các tạo dich vụ vụ web theo kiến trúc Rest. Bài này chúng ta sẽ cài đặt cách giao tiếp qua phương thức GET.
B1: Tạo java web project
B2: Tạo rest service
rest1
rest2
rest3
Sau khi xong, mở file web.xml chúng ta sẽ thấy xuất hiện thêm đoạn xml sau:

<servlet>
        <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

Hiệu chỉnh lại nội dung của lớp Student như sau:

package codes;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

@Path("student")
public class Student {
    public Student() {
    }
    /**
     * Phuong thuc se duoc kich hoat khi nhan duoc
     * yeu cau tu phia client theo phuong phap get
     * Ket qua tra ve chuyen thanh chuoi
     */
    @GET
    @Produces("text/plain")
    public String getText() {
        return "hello moto";
    }
    
    /**
     * Phuong thuc se duoc kich hoat khi nhan duoc
     * yeu cau tu phia client theo phuong phap get
     * Ket qua tra ve chuyen thanh chuoi XML
     */
    @Path("/xml")
    @GET
    @Produces("text/xml")
    public String getXML(@QueryParam("id") int id) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            Customer customer = new Customer(id, "Nguyen Van Mit", "Can Tho");
            StringWriter sw = new StringWriter();
            jaxbMarshaller.marshal(customer, sw);
            String xmlString = sw.toString();
            return xmlString;
        } catch (JAXBException ex) {
            return ex.toString();
        }
    }
    
    /**
     * Phuong thuc se duoc kich hoat khi nhan duoc
     * yeu cau tu phia client theo phuong phap get
     * nhan tham so id theo cach gan them vao URL
     * Ket qua tra ve chuyen thanh chuoi xml
     */
    @Path("/xml/{id}")
    @GET
    @Produces("text/xml")
    // @PathParam("id") tim phan id tren URL
    public String getXMLID(@PathParam("id") int id) {
        return "<rs><id>"+id+"</id>"
                + "<name>hello moto</name>"
                + "</rs>";
    }
    
     /**
     * Phuong thuc se duoc kich hoat khi nhan duoc
     * yeu cau tu phia client theo phuong phap get
     * Ket qua tra ve chuyen thanh chuoi JSON
     */
    @Path("/json")
    @GET
    @Produces("text/json")
    public String getJSON() {
        return "{'id':1, "
                + "'name':'Nguyen Van Mit'}";
    }
}

Biên dịch và deploy website.
Mở trình duyệt và gõ địa chỉ như sau để test:
rest4

rest5

Như vậy là chúng ta đã có được dịch vụ web theo kiến trúc Rest
Các bước thực hiện chi tiết và tạo client để gọi dịch vụ với ajax tham khảo video này:

Thử xem sao !

Advertisements

Hai cách quản lý một tập hợp trong Java


Trong java, bạn có thể quản lý tập hợp các phần tử theo 2 cách:

  • Sử dụng mảng
  • Sử dụng danh sách

Trong khuôn khổ bài này, chúng ta cùng tìm hiểu ArrayList – một lớp đơn giản để quản lý tập hợp.
Yêu cầu:
Tạo một chương trình để người dùng quản lý 5 phần tử kiểu int và lưu vào một mảng.

  • In giá trị các phần tử trong mảng.
  • In các phần tử theo thứ tự giảm dần.
  • In các phần tử trong mảng mà chia hết cho 5.
  • Cho người dùng nhập vào một số, hiển thị số lần xuất hiện của số vừa nhập có trong mảng ban đầu.

Output:
1

1. Cách 1: Khởi tạo mảng int theo cách thông thường:

int[] array = new int[5];

Nếu khởi tạo mảng dạng này, khi chúng ta gán mảng 5 phần tử thì số phần tử đó là cố định. Chúng ta muốn tăng số phần tử lên để quản lý nhiều hơn thì phải tốn nhiều công sức cho bước tăng trưởng. Đây cũng là sự bất tiện của cách quản lý này.

Code tham khảo:

public class Array_PrimitiveDataType {

    int[] array;

    public Array_PrimitiveDataType() {
        array = new int[5];
    }
    
    /**
     * input array
     */
    void inputArray(){
        System.out.println("-----Nhap mang-----");
        Scanner input = new Scanner(System.in);
        for (int i = 0; i &amp;lt; array.length; i++) {
            System.out.print("Nhap phan tu thu " + (i+1) + ":");
            array[i] = input.nextInt();
        }
        System.out.println("");
    }
    
    void printArray(){
        System.out.println("-----In----");
        for (int i = 0; i &amp;lt; array.length; i++) {
            System.out.print(array[i] + "\t");
        }
        System.out.println("");  
    }
    
    void sortDescArray(){
        System.out.println("-----Sap xep-----");
        for (int i = 0; i &amp;lt;= array.length - 2; i++) {
            for (int j = i+1; j &amp;lt;= array.length -1; j++) {
                if(array[i] &amp;lt; array[j]){
                    int temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
        }
    }
    
    void searchNumber(){
        System.out.println("----Tim mot so-----");
        Scanner input = new Scanner(System.in);
        System.out.print("Nhap mot so can tim:");
        int so = input.nextInt();
        int dem = 0;
        for (int i = 0; i &amp;lt; array.length; i++) {
            if(array[i] == so) dem++;
        }
        System.out.println("Co " + dem + " phan tu trong mang co gia tri " + so);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Array_PrimitiveDataType demo = new Array_PrimitiveDataType();
        demo.inputArray();
        demo.printArray();
        demo.sortDescArray();
        demo.printArray();
    }  
}

Video:

2. Cách 2: Khởi tạo một đối tượng của lớp ArrayList được hỗ trợ sẵn trong API của Java.

Với việc quản lý này, người dùng tự do thêm bớt phần tử nếu muốn thông qua các phương thức của nó. Vì nó không giới hạn số phần tử được quản lý. Đây là sự thuận tiện khi sử dụng lớp ArrayList so với cách khai báo thông thường.

ArrayList array = new ArrayList();

Đặc biệt: đối tượng trong tập hợp trên chỉ quản lý các đối tượng mà không quản lý các biến kiểu dữ liệu nguyên thủy. Vì vậy, khi thêm dữ liệu mới hoặc lấy ra một phần tử trong tập hợp, chúng ta luôn thao tác với đối tượng (Có thể sử dụng Wrapper Class để quản lý các kiểu dữ liệu nguyên thủy khi cần thiết).

Code tham khảo:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;

/**
 *
 * @author maithicamnhung
 */
public class Bai1_ArrayList {
    ArrayList arr = new ArrayList();
    
    // Nhap du lieu
    public void inputList(){
        System.out.println("Enter elements:");
        Scanner input = new Scanner(System.in);
        for(int i = 0 ; i < 4 ; i++){
            System.out.println("Element " + (i+1) + ":");
            int value = input.nextInt();
            arr.add(value);
        }
    }
    
    // In du lieu mang
    public void printList(){
        System.out.println("======List=====");
        Iterator iarr = arr.iterator();
        while(iarr.hasNext()){
            System.out.println(iarr.next());
        }
    }
    
    // Sap xep mang tang dan
    public void  printListOrderAsc(){
        Collections.sort(arr);
        System.out.println("======List Order Asc=====");
        Iterator iarr = arr.iterator();
        while(iarr.hasNext()){
            System.out.println(iarr.next());
        }
    }
    
    // Sap xep mang giam dan
    public void  printListOrderDes(){
        Collections.sort(arr, Collections.reverseOrder());
        System.out.println("======List Order Des=====");
        Iterator iarr = arr.iterator();
        while(iarr.hasNext()){
            System.out.println(iarr.next());
        }
    }
    
    // Chia het cho 5
    public void divideFive(){
        System.out.println("Element divide 5:"); 
        Iterator iarr = arr.iterator();
        while(iarr.hasNext()){
            Integer value = (Integer) iarr.next();
            if(value.intValue() % 5 == 0){
                System.out.println(value);
            }
        }
    }
    
    public void searchNumber(){
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number to search:");
        int count = 0;
        int number = input.nextInt();
        Iterator iarr = arr.iterator();
        while(iarr.hasNext()){
            Integer value = (Integer)iarr.next();
            if(value.intValue() == number){
                count++;
            }
        }
        System.out.println("Count: " + count);
    }
    
    public static void main(String[] args) {
        Bai1_ArrayList arrList = new Bai1_ArrayList();
        arrList.inputList();
        arrList.printList();
        arrList.printListOrderAsc();
        arrList.printListOrderDes();
        arrList.divideFive();
        arrList.searchNumber();
    }
}

Video:

Chúc các bạn thành công.

Một số câu hỏi ôn tập môn học DBSJ


 

Một số câu hỏi ôn lý thuyết

1. JDBC and ODBC are identical?
A. True
B. False
2. How many kinds of JDBC drivers?
A. 10
B. 3
C. 4
D. many
3. The JDBC API is a Java API for accessing virtually any kind of tabular data
A. False
B. True
4. What is the correct statement about CallableStatement interface? (choose 1)
A. It defines a statement to create a stored-procedure
B. It contains a call to a stored-procedure
C. It defines a store-procedure
5. Which is the default port number of RMI Registry Server?
A. 1023
B. 1099
C. 1069
6. Which of the following statements is correct for retrieving all fields from Student table?
A. String sql=”SELECT FROM Student”;
Statement st=cn.createStatement(sql);
ResultSet rs=st.executeQuery();
B. String sql=”SELECT FROM Student”;
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
7. If you need to use a stored procedure with output parameters, which of the following statement type should be used to call the procedure?
A. PreparedStatement
B. CallableStatement
C. Statement
8. From which object do you ask for DatabaseMetaData?
A. DriverManager
B. ResultSet
C. Connection
D. Driver
9. Which character is used to represent an input parameter in a CallableStatement?
A.
B. #
C. ?
D. %
10. Which one of the following will not get the data from the first column of ResultSet rs, returned from executing SQL statement: SELECT name, rank, serialNo FROM employee.
A. rs.getString(“name”);
B. rs.getString(1);
C. rs.getString(0);
11. Which class contains the transaction control method setAutoCommit, commit, and rollback?
A. Statement
B. Connection
C. ResultSet
12. You can use an applet in RMI program as ________
A. None of the other options
B. Server program
C. Client program
13. Which of the following will not cause a JDBC driver to be loaded and registered with the DriverManager?
A. Class.forName(driverString);
B. new DriverClass();
C. Include driver name in jdbc.drivers system property
D. None of the above
14. SQLWarnings from multiple Statement method calls (like executeUpdate) will build up until you ask for them all with getWarnings and getNextWarning.
A. True
B. False
15. If one intends to work with a ResultSet, which of these PreparedStatement methods will not work?
A. execute()
B. executeQuery()
C. executeUpdate()
16. Can a ResultSet be reliably returned from a method that creates a Statement and executes a query?
A. Yes
B. No
17. How can I use JDBC to create a database?
A. Include create=true at end of JDBC URL
B. Execute “CREATE DATABASE jGuru” SQL statement
C. Execute “STRSQL” and “CREATE COLLECTION jGuru” SQL statements
D. Database creation is DBMS specific
18. Which of the following can you do with a JDBC 2.0 database driver that you cannot with a JDBC 1.x driver?
A. Batch multiple statements, to be sent to the database together
B. Scroll through result sets bi-directionally
C. Work with SQL3 data types directly
D. All of the above
19. A __________ result set has a cursor that moves both forward and backward and can be moved to a particular row
A. scrollable
B. nonscrollable
C. Unscrollable
20. The method___________ is designed for statements that produce a single result set, such as SELECT statement
A. executeUpdate
B. execute
C. Update
D. executeQuery
21. Which three of the following are classes of Java.rmi package?
A. Naming
B. MarshalledObject
C. RMISecurityManager
D. Remote
22. Which option of jar file indicates manifest file not created?
A. Jar M
B. Jar t
c. Jar m
D. Jar c
23. _______ option of Jar command makes a Java archive file.
A. JAR -c
B. JAR -m
C. JAR -v
D. JAR –f
24. Which command adds the file file.class to Xyz.jar?
A. jar – uf Xyz . jar file.class
B. jar – xf Xyz . jar
C. jar – tf Xyz . jar
25. Driver types are used to categorize the technology used to connect to the database.
A. True
B. False
26. This is an Application Programming Interface provided by Microsoft for access the database.It uses SQL as its database language.
A. JDBC
B. ODBC
27. JDBC is ODBC translated into an object-oriented interface that is natural for java programmers.
A. True
B. False
28. In this Data processing Model,the client communicates directly to the database server without the help of any middle-ware technologies or another server.
A. Two-tier Data processing Model
B. Three – tier Data processing Model
29. The Type 1 driver is also known as JDBC-ODBC bridge plus ODBC driver.
A. Translates JDBC calls into ODBC calls.
B. Translates JDBC calls into database=specific calls or native calls
C. Maps JDBC calls to the underlying “network” protocol, which in turn calls native methods on the server.
D. Directly calls RDBMS from client machine.
30. This method is used to execute INSERT, DELETE, UPDATE , and other SQL DDL such as CREATE, DROP Table.
A. executeUpdate();
B. execute();
C. executeQuery();
31. This method is used for retrieving a string value (SQL type VARCHAR) and assigning into java String object.
A. getVarchar();
B. getObject();
C. getString();
32. This method is used for retrieving the value from current row as object.
A. getRow();
B. getObject();
C. getString();
33. This object connects to a data source only to read data from a ResultSet or write data back to the data source.
A. A Connected RowSet.
B. A Disconnected RowSet.
34. A client application uses stored procedures increases the network traffic, but it reduces the number of times a database is accessed.
A. True
B. False
35. This parameter is used to pass values into a store procedure.The value of this parameter cannot changed or reassigned within the module and hence is constant.
A. IN
B. OUT
C. IN/OUT
36. OUT Parameter. – 3 choices.
A. pass out of procedure module
B. is a constant
C. is a variable
D. back to the calling block
37. This Parameter behaves like an initialized variable.
A. OUT
B. IN
C. IN/OUT
38. This object does not contain the stored procedure itself but contains only a call to the stored procedure.
A. CallableStatment
B. PreparedStatment
C. prepareCall();
39. This refers to the ability to check whether the cursor stays open after a COMMIT
A. Updatable
B. Holdable
C. Scrollable
40. The prepareStatment() method sends SQL query to the database. and this returns:
A. PrepareStatment Object
B. Callalbalestatment Object
C. PrepareCall () method.
41. The CallableStatment object contains the SQL statments.
A. True
B. False
42. A cursor that can only be used to process from the beginning of a ResultSet to the end of it.It is default type.
A. TYPE_SCROLL_SENSITIVE
B. TYPE_SCROLL_INSENSITIVE
C. TYPE_FORWARD_ONLY
43. A Rowset Object provides scrollability and updatability for any kind of DBMS or drivers.
A. True
B. False
44. A ResultSet object contains a set of rows from a result set or some other source of tabular data, like a file or spreadsheet.
A. true
B. false
45. Which class is a disconnected rowset.
A. A CachedRowSet class.
B. A JDBCRowSet class.
C. A WebRowSet class.
46. Which statments are true?
A. A RowSet has to be make scrollable and updatable at the time of creation.
B. Scrollability and Updatability of a RowSet is independent of the JDBC driver
C. A connect RowSet can read data from a non relational database source also.
D. A RowSet is a JavaBeans component which has to programmatically notify all registered event listener.
47. The Result Set can not be modified and hence, It is not updatable in any way.
A. CONCURENT_READ_ONLY
B. CONCURENT_UPDATABLE
48. This is the mechanism of encoding information in a secret coded form, intented only for the recipient to access the information.
A. Cryptography
B. Encryption
49. The term “encrypting ” pertains to converting plaintext to ciphertext, which is again decrypted into usable plaintext.
A. True
B. False
50. This transforms the input, called the plaintext, to an output, known as ciphertext. this is known as Symmetric cryptography.
A. Hash Function
B. Secret key cryptography
C. Public Key cryptography
51. This is as asymmetric cryptography, It operates under two different keys.
A. Public Key cryptography
B. Hash Function
C. Secret key cryptography
52. This is algorithms that does not use any key, it is known as message digest.
A. Secret key cryptography
B. Public Key cryptography
C. Hash Function
53. Which statements are true?
A. The Tamper-proofing process verifies whether the data received by the receiver is the same data as sent by the sender.
B. Spoofing or identity interception, which means impersonating the identity of a different user and use it in an unauthorized way
C. Authentication is the process that provides tamper-proofing, while it is on the network.
54. The class is use to hash value of the specified data.
A. Message Digest
B. Signature
C. KeyPair Generator
D. KeyFactory
E. Certificate Factory
55. The ‘Native API-Java/Party Java’ is Driver Type
A. I
B. II
C. III
D. IV
56. The ‘Native Protocol – All Java’ is Driver Type
A. I
B. II
C. III
D. IV
57. Statement and PreparedStatement is inherited from Statement Interface. The CallableStatement is inherited from PreparedStatement interface.
A. True
B. False
58. This Method return an Integer value indicating the row count.
A. ExecuteQuery();
B. Execute();
C. ExecuteUpdate();
59. If row value is 0, this method has no effect.If row value is positive, the cursor is moved forward that many row.
A. relative(int row) method
B. absolute(int row) method.
60. Calling absolute(1) is equivalent to calling last()
A. True
B. False
61. Which statements are true? (3 choices)
A. In Scrollable ResultSet, the cursor is positioned on the first row.
B. A default ResultSet object is not updated and has a cursor that moves forward only.
C. The ResultSet should be compulsorily closed after a COMMIT statement.
D. Holdable refers to ability to check whether the cursor stays open after a COMMIT.
E. The createStatement method has two argurments namely resultSetType and resultSetConcurrency
62. Which statements are true? (3 choices)
A. The original message text has to be transmitted separately since the content of a digitally signed message is altered irreversibly.
B. A Certification authority creates a signed certificate by encrypting the digitally signature with its private key.
C. The digital signature and sender’s public key are appended to end of a message.
D. A recipient decrypts a signed signature using its own public key.
E. The integrity of a message cannot be ensure while using message digests
63. This comprises the mapping of one or more permissions with a class.
A. Security Manager
B. Policy File
C. Access Controller
64. The class is use to produce a pair of public and private keys appropriate for a specified.
A. Signature
B. Message Digest
C. KeyPair Generator
D. KeyFactory
E. Certificate Factory
65. The class is used to sign and check the authenticity of digital signature
A. Message Digest
B. Signature
C. Certificate Factory
D. KeyFactory
E. KeyPair Generator
66. The class is used to transform opaque keys of type Key into key specifications and provide transparent representations of the underlying key material and vice versa.
A. Message Digest
B. KeyPair Generator
C. Signature
D. KeyFactory
E. Certificate Factory
67. The class is used to generate public key certificates.
A. Certificate Factory
B. KeyPair Generator
C. Message Digest
D. Signature
E. KeyFactory
68. This class is a database of keys and certificates
A. Algorithm Parameters
B. KeyStore
C. Key
D. KeySpec
69. this ensures that a user or a business organization or a program entity has performed a transaction.
A. Non-repudiation
B. Tampering
C. Integrity
D. Confidentiality
70. Data integrity is to protect data from getting tampered, while it is on the network.
A. True
B. False
71. This is a framework written in java to access and develop cryptographic functionality, and forms part of the java security API.
A. JCA
B. JCE
72. With this padding technique a short block is padded with a repeating byte.
A. DES
B. PKCS5
C. CBC
73. Single-bit ciphers are called:
A. Block cipher
B. Stream cipher
74. Cipher objects are created using this method of the cipher class.
A. getInstance();
B. init();
75. the cipher object is initialized by the init() method?
A. True
B. False
76. The Code : “DES/CBC/PKCS5Padding” is the form of
A. “mode/algorithm/padding”
B. “algorithm/mode/padding”
C. “algorithm/padding/mode”
D. “DeCrypto/Cipher/padding”
77. “(Only)algorithm” such as
A. “DES”
B. “PKCS5”
C. “CBE”
78. Most these implementations mix a random number, known as the “salt” with the password text to derive an encrypted key.
A. Encryption and Decryption
B. Key Agreement
C. Password Base Encryption
79. Single bits or a block of bits can be encrypted into cipher blocks
A. True
B. False
80. In this Environment, the java application is the client and DBMS is the database server.
A. Three-Tier JDBC
B. Two-Tier JDBC

 

Đáp án:

1-B, 2-4,3-B,4-B,5-B,6-B,7-B, 8-C, 9-C, 10-C, 11-B, 12-C, 13-D, 14-B, 15-C, 16-B, 17-B, 18-D, 19-D, 20-D, 21-abc, 25-a, 26-b, 26-a, 27-a, 28-a, 29-a, 30-a, 31-c, 32-b, 33-a, 34-b, 35-a, 36-ad, 37-c, 38-a, 39-b, 40-a, 41-a, 42-c, 43-a, 44-b, 45a, 46b, 47a, 48a, 49a, 50b, 51a, 52c, 53a, 54a, 55a, 56c, 57a, 58c, 59a, 60b, 61ade, 62bce, 63b, 64c, 65b, 66d, 67a, 68b, 69a, 70a, 71a, 72b, 73b, 74a, 75a, 76b, 77a, 78c, 79a, 80b.