This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Thứ Năm, 24 tháng 3, 2016

Cách giải một số bài tập C về kiểu chuỗi ký tự

CÁCH GIẢI MỘT SỐ BÀI TẬP VỀ KIỂU CHUỖI 
1.Đếm có bao nhiêu khoảng trắng trong chuỗi. 
2.Nhập vào một chuỗi, hãy loại bỏ những khoảng trắng thừa trong chuỗi. 
3.Nhập vào hai chuỗi s1 và s2, nối chuỗi s2 vào s1. Xuất chuỗi s1 ra màn hình 
4.Đổi tất cả các kí tự có trong chuỗi thành chữ thường (không dùng hàm strlwr). 
5.Đổi tất cả các kí tự trong chuỗi sang chữ in hoa (không dùng hàm struppr). 
6.Viết chương trình đổi những kí tự đầu tiên của mỗi từ thành chữ in hoa. 
7.Viết chương trình đổi chữ xen kẻ 1 chữ hoa và 1 chữ thường. 
Ví dụ: nhập ABCDEfgh đổi thành AbCdEfGh 
8.Viết chương trình đảo ngược các kí tự trong chuỗi. 
Ví dụ: nhập ABCDE, xuất ra màn hình là:EDCBA 
9.Viết chương trình tìm kiếm 1 kí tự xem có trong chuỗi không, nếu có xuất ra vị trí của từ chứ kí tự đó. (Vd: xâu a là “ho chi minh”: nhập ‘m’=>kết quả là 3) 
10.Viết 1 chương trình đếm một kư tự xuất hiện bao nhiêu lần trong chuỗi.(vd:xâu a nhập là “ho chi minh”, nhập ‘i’ =>kq: 2) 
11.Nhập vào chuỗi s1 và s2, cho biết vị trí xuất hiện của chuỗi s2 trong s1. 
12.Viết chương trình tìm kiếm tên trong chuỗi họ tên. Nếu có thì xuất ra là tên này đă nhập 
đúng, ngược lại thông báo là đă nhập sai. 
13.Viết chương đảo vị trí của từ đầu và từ cuối. 
Ví dụ: nhập “bo an co” xuat ra “co an bo” 
14.Viết hàm cắt chuỗi họ tên thành chuỗi họ lót và chuỗi tên. 
Ví dụ: chuỗi họ tên là:”Nguyễn Văn A” cắt ra 2 chuỗi là chuỗi họ lót:”NguyễnVăn”,chuỗi tên là:”A” 
15.Nhập một chuỗi bất kỳ, sau đó hỏi người dùng cần tách bắt đầu từ đâu trong chuỗi trở về sau. 
Ví dụ: Nhập chuỗi S1:”Trường Đại Học Tôn Đức Thắng”. Người nhập muốn tách bắt đầu từ chữ “Tôn” thì sẽ xuất ra chuỗi “Tôn Đức Thắng” ra màn hình 
16.Viết hàm kiểm tra xem chuỗi có đối xứng hay không?. 
17.Viết hàm tra xem trong chuỗi có kí tự số hay không nếu có tách ra thành một mảng số riêng. 
18.Nhập một chuỗi bất kì, yêu cầu nhập 1 kí tự muốn xóa. Thực hiện xóa tất cả những kí tự đó trong chuỗi. 
19.Đổi các từ ở đầu câu sang chữ hoa và những từ không phải đầu câu sang chữ thường. 
Ví dụ: nGuYen vAN a đổi thành: Nguyen Van A 
20.Viết chương trình đảo ngược thứ tự các từ có trong chuỗi 
Ví dụ: Nhập: lap trinh bang ngon ngu c 
21.Xuất ra màn hình là: c ngu ngon bang trinh lap 
22.Cho chuỗi str, nhập vào vị trí vt và số kí tự cần xóa n, hăy xóa n kí tự tính từ vị trí vt trong chuỗi str. 
23Nhập vào chuỗi str, chuỗi cần chèn strInsert và vị trí cần chèn vt. Hăy chèn chuỗi strInser vào chuỗi str tại vị trí vt. 
23.Cho một xâu, nhập vào một từ ,viết chương trình, xoá từ đó trong xâu đã cho. 
24.Viết chương trình tìm kiếm xem ký tự nào xuất nhiện nhiều nhất trong chuỗi. 
25.Nhập 1 chuỗi bất kì, liệt kê xem mỗi ký tự xuất hiện mấy lần. 
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
    1
    int demkhoangtrang(char *s)
    {
    int d=0;
    while(strstr(s," ")!=NULL)
    {
    d++;
    s=strstr(s," ")+1;
    }
    return d;
    }
    //lam theo ham de quy
    // s=strstr(s," ");
    //if(s==NULL)
    //return 0;
    //else return 1+demkhoangtrang(s+1);
    2
    void xoakhoangtrang(char *s)
    {
    char *c=strstr(s," ");
     
    while(c!=NULL)
    {
    int t=strlen(s)-strlen©;
    for(int i=t;i<strlen(s);i++)
    s[i]=s[i+1];
    c=strstr(s," ");
    }
    if(s[0]==' ')
    s=s+1; //xoa khang trang dau chuoi
    int n=strlen(s);
    if(s[n-1]==' ')
    s[n-1]='\0';//xoa khoang trang cuoi chuoi
     
    cout<<s; //for(int i=0;i
    //cout<
     
    }
    3
    void noichuoi(char *a,char *b)
    {
    strcat(a,b);
    puts(a);
     
    }
    4
    void chuthuong(char *a)
    {
    for(int i=0;i<strlen(a);i++)
    if(a[i]>=65 && a[i]<=90)
    a[i]=a[i]+32;
    puts(a);
    }
    5
    void chuhoa(char *a)
    {
    for(int i=0;i<strlen(a);i++)
    a[i]=toupper(a[i]); //if(a[i]>=97 && a[i]<=122)
    puts(a); //a[i]=a[i]-32;
     
    }
    6
    void chuhoadau(char *s)
    {
    s[0]=toupper(s[0]);
    while(strstr(s," ")!=NULL)
    {
    s=strstr(s," ")+1;
    s[0]=toupper(s[0]);
    }
     
    }
     
    7
    void chuxenke(char *a)
    {
    int n=strlen(a);
    for(int i=0;i<n;i++)
    {
    if(i%2==0)
    if((int)a[i]>=97 && (int)a[i]<=122)
    a[i]=char((int)a[i]-32);
    if(i%2==1)
    if((int)a[i]>=65 && (int)a[i]<=90)
    a[i]=char((int)a[i]+32);
    }
     
    puts(a);
    }
    8
    void daochuoi(char *s)
    {
    puts(strrev(s));
     
    }
    9
    int vitri(char *a,char *b)
    {
    int kq,d=0;
    if(strstr(a,b)!=NULL)
    {
    kq=strlen(a)-strlen(strstr(a,b));
    for(int i=kq;i>=0;i--)
    if(a[i]==' ')
    d++;
    return d+1;
    }
    else return -1;
    }
    10
    int diemtu(char *a,char *b)
    {
    int d=0;
    while(strstr(a,b)!=NULL)
    {
    d++;
    a=strstr(a,b)+1;
     
    }
     
    return d;
    }
    11
    int vitri(char *a,char *b)
    {
    int d=-1;
    if(strstr(a,b)!=NULL)
    d=strlen(a)-strlen(strstr(a,b));
    return d;
    }
    12
    void timten(char *a,char *b)
    {
    int n=strlen(a);
    char *s;
    for(int i=n-1;i>=0;i--)
    if(a[i]==' ')
    {
    s=a+i+1;
    break;
    }
    if(strcmpi(s,b)==0)// strcmp==stricmp
    cout<<s;
    else
    cout<<"ban nhap sai ten\n";
    }
    13
    void daochuoi(char *s)
    {
     
    char t[50],r[50];
    int i,l;
    for(i=strlen(s)-1;i>=0;i--)
    if(s[i]==' ')
    break;
    strcpy(r,s+i+1);//tim dctu cuoi
    s[i+1]='\0';//xau s sau khi bo tu cuoi,co khoang trang o cuoi xau
    l=strlen(s)-strlen(strstr(s," ")); //tim vi tri khoang trang dau tien trong chuoi
    strcpy(t,s+l+1);//l la xau chau cac tu chinh giua
    s[l]='\0'; //hien tai la xau chua tu dautien
    strcat(strcat(strcat(r," "),t),s);//noi cac xau lai voi nhau*/
     
    puts®;
    }
    14
    void cathoten(char *s)
    {
    char *t;
    int i;
    for(i=strlen(s)-1;i>=0;i--)
    if(s[i]==' '&&s[i+1]!=' ')
    break;
    t=s+i+1;
    s[i]='\0';
    cout<<"ho lot: ";
    puts(s);
    cout<<"ho ten: ";
    puts(t);
     
    }
    15
    void timtu(char *a,char *b)
    {
     
    char *t=strstr(a,b);//vi tri xuat hien b dau tien trong chuoi a
    puts(t);
    }
    16
    bool ktdoixung(char *s)
    {
    char c[255];
    strcpy(c,s);
    if(strcmpi(s,strrev©)==0)
    return true;
    else return false;
     
    }
    17
    void tachso(char *s)
    {
    int a[100],j=0;
    for(int i=0;i<strlen(s);i++)
    if(s[i]>='0' && s[i]<='9')
    { a[j]=s[i];//ki tu kieu char chuyen thanh kieu int(vd:1=>49)
    j++;
    for(int t=i;t<strlen(s);t++)
    s[t]=s[t+1];
    i--;
    }
    puts(s);
    for(int i=0;i<j;i++)
    cout<<char(a[i])<<" ";
    }
    18
    void xoakitu(char *a,char b)
    {
    int n=strlen(a);
    for(int i=0;i<n;i++)
     
    if(a[i]==b)
    {
    for(int j=i;j<n;j++)
    a[j]=a[j+1];
    i--;
    n--;
     
    }
     
    cout<<a;
    }
    19
    void chuhoa(char *s)
    {
    s[0]=toupper(s[0]);
    for(int i=1;i<strlen(s);i++) //chua tim dc cach nao toi uu hon
    if(s[i]==' ')
    {
    s[i+1]=toupper(s[i+1]);
    i++;
    }
    else
    {
    if(s[i]>='A' && s[i]<='Z')
    s[i]=s[i]+32;
     
    }
    puts(s);
    }
    20
    void daothutu(char *s)
    {
    char c[255];
    c[0]='\0';//ham strcat noi chuoi tai vi tri NULL
     
    for(int i=strlen(s)-1;i>=0;i--)
     
    if(s[i]==' ')
    {
    strcat(strcat(c,s+i+1)," ");
    s[i]='\0';
     
    }
    strcat(c,s);
    puts©;
     
    }
    21
    void xoa(char *s,int vt,int n)
    {
    strcpy(s+vt,s+vt+n);
    puts(s);
    }
    22
    void chen(char *s,char *d,int vt)
    {
    char c[255];
    strcpy(c,s+vt);
    strcpy(s+vt,d);
    strcat(s,c);
    puts(s);
    }
    23
    void xoatu(char *s,char *c)
    {
    while(strstr(s,c)!=NULL)
    {
    int t=strlen(s)-strlen(strstr(s,c)),d=strlen©;
    if((s[t-1]==' '&& s[t+d]==' ')||(s[t-1]==' '&& t+d==strlen(s)))//truong hop tu giua va tu cuoi
    strcpy(s+t-1,s+t+d);// s+t-1 la khoang trang
    if(s[t+d]==' '&& t==0)//truong hop xoa tu dau tien
    strcpy(s,s+t+d+1);
    }
    puts(s);
    }
    24
    void kituxuathiennhieunhat(char *s)
    {
    int a[100],n=0;
    for(int i=0;i<(int)strlen(s);i++)
    {
    int d=1;
    for(int j=i+1;j<(int)strlen(s);j++)
    if(s[i]==s[j])
    { d++;
    for(int k=j;k<(int)strlen(s);k++)
    s[k]=s[k+1];
    j--;
     
    }
    a[n++]=d;
     
    }
    int max=a[0];
     
    for(int i=1;i<(int)strlen(s);i++)
    if(a[i]>max)
    max=a[i];
    for(int i=1;i<(int)strlen(s);i++)
    if(a[i]==max)
    cout<<"ki tu "<<s[i]<<" xuat hien nhieu nhat la "<<a[i]<<" lan\n";
     
    }
     
    25
    void demkitu(char *s)
    {
    int a[100],n=0;
    for(int i=0;i<(int)strlen(s);i++)
    {
    int d=1;
    for(int j=i+1;j<(int)strlen(s);j++)
    if(s[i]==s[j])
    { d++;
    for(int k=j;k<(int)strlen(s);k++)
    s[k]=s[k+1];
    j--;
     
    }
    a[n++]=d;
     
    }
    for(int i=0;i<(int)strlen(s);i++)
    cout<<"ki tu "<<s[i]<<" xuat hien "<<a[i]<<" lan\n";
     
    }

BT CHUỖI_LỜI GIẢI

CÂU 1

#include
#include
#include   //thư viện chuỗi

int main()
{
    char xau[30];
    printf("Nhap vao 1 chuoi: ");
    gets(xau);
    for(int i=strlen(xau)-1;i>=0;i--)  //strlen trả về độ dài của chuỗi
    {
        printf("%c",xau[i]);
    }
    getch();
}



CÂU2


#include
#include
#include

int main()
{
   char xau[50];
   printf("Nhap vao mot chuoi: ");
   gets(xau);
   int a=strlen(xau)-1;
   for(int i=strlen(xau)-1;i>=0;i--)
   {
      if(xau[i]==32 || i==0)
      {
         if(i==0)
         {
            printf(" ");
         }
         for(int j=i;j<=a;j++)
         {
            printf("%c",xau[j]);
         }
         a=i-1;
      }
   }
   getch();
}

CÂU 3

#include
#include
#include

int main()
{
    char xau[30];
    printf("Nhap vao mot chuoi: ");
    gets(xau);
    for(int i=0;i    {
        if(xau[i]!=32)
        {
            printf("%c",xau[i]);
        }
        else
        {
         for(int j=strlen(xau)-1;j>=i;j--)
         {
            if(xau[j]==32)
            {
               for(int k=j;k<=strlen(xau)-1;k++)
               printf("%c",xau[k]);
               break;
            }
         }
         break;
      }
    }
    getch();
}



CÂU 4

#include
#include
#include

int main()
{
    char xau[30];
    printf("Nhap vao mot chuoi: ");
    gets(xau);
    for(int i=0;i<=strlen(xau)-1;i++)
    {
      if(xau[i]!=32)
      {
          printf("%c",xau[i]);
      }
        else
      {
            printf("\n");
      }
    }
    getch();
}


CÂU 5
#include
#include
#include

char doc_so[50];
char *docso(int n)
{
   char doc[10][5]={"","Mot","Hai","Ba","Bon","Nam","Sau","Bay","Tam","Chin"};
   doc_so[0]=0;
   int donvi=n%10;
   n=n/10;
   int chuc=n%10;
   int tram=n/10;
   if(tram>0)
   {
      strcat(doc_so,doc[tram]);
      strcat(doc_so," Tram ");
   }
   if(chuc>0)
   {
      if(chuc==1)
      strcat(doc_so," Muoi ");
      else
      {
         strcat(doc_so,doc[chuc]);
         strcat(doc_so," Muoi ");
      }
   }
   if(donvi>0)
   strcat(doc_so,doc[donvi]);
   return doc_so;
}
int main()
{
   int n;
    printf("Nhap vao mot day so: ");
    scanf("%d",&n);
    if(n==0)
    {
      printf("Khong");
   }
   else
   {
      int tram=n%1000;
      n=n/1000;
      int ngan=n%1000;
      n=n/1000;
      int trieu=n%1000;
      int ty=n/1000;
      if(ty>0)
      {
         printf("%s Ty",docso(ty));
      }
      if(trieu>0)
      {
         printf(" %s Trieu ",docso(trieu));
      }
      if(ngan>0)
      {
         printf(" %s Ngan ",docso(ngan));
      }
      if(tram>0)
      {
         printf(" %s ",docso(tram));
      }
   }
   getch();
}




CÂU 6
 #include
#include
#include

int main()
{
    char xau[50];
    char kitukiemtra;
    int dem;
    printf("Nhap vao mot chuoi: ");
    gets(xau);
    printf("Nhap vao ki tu muon kiem tra: ");
    scanf("%c",&kitukiemtra);
    for(int i=0;i    {
        if(xau[i]==kitukiemtra)
        dem++;
    }
    if(dem==0)
    printf("Ki tu %c khong co trong chuoi",kitukiemtra);
    else
    printf("Ki tu %c xuat hien %d lan trong chuoi",kitukiemtra,dem);
    getch();
}



BT VỀ CHUỖI_ĐỀ


1) Nhập vào 1 chuỗi và xuất chuỗi đó ra theo chiều ngược lại:

VD Nhập vào tran van thoa xuất ra aoht nav nart

2) Nhập vào 1 chuỗi và xuất chuỗi đó ra theo chiều ngược lại:

VD Nhập vào tran van thoa xuất ra thoa van tran

3) Nhập vào họ và tên tách ra họ, tên;

VD Nhập vào tran van thoa xuất ra tran thoa

4) Nhập vào họ và tên xuất ra họ, tên đệm, tên mỗi từ 1 dòng;

VD Nhập vào tran van thoa xuất ra
tran
van
thoa


5) Nhập vào 1 dãy số và đọc dãy số đó.

VD: 123 đọc là một trăm hai mươi ba

6) Nhập vào 1 chuỗi sau đó nhập váo 1 từ và kiểm tra xem từ đó có xuất hiện trong chuỗi trên hay không, nếu có thì xuất hiện bao nhiêu lần.

VD Nhập vào tran van thoa. Nhập kí tự t --> có 2 lần

Thứ Ba, 22 tháng 3, 2016

Lịch sử MLM ?

Lịch sử của ngành Kinh Doanh Theo Mạng gắn liền với tên tuổi của nhà hóa học người Mỹ có tên là Karl Renborg (1887-1973). Ông là người đầu tiên đã đưa tư tưởng của kinh doanh theo mạng, tạo ra một hệ thống kinh tế có triển vọng nhất của thế kỷ 21.
Ông Renborg có 20 năm sống tại Trung Quốc và bị bắt vào tù khi chính quyền thuộc về tay Tưởng Giới Thạch. Trong điều kiện sống rất vất vả thiếu thốn ông bắt đầu suy nghĩ về những chất dinh dưỡng và vitamin để duy trì sức khoẻ. Năm 1927 Ông Renborg về lại Mỹ và bắt đầu chế biến các chất bổ sung dinh dưỡng khác nhau. Ông đề nghị những người quen của ông thử nghiệm miễn phí sản phẩm nhưng không ai dám dùng thử. Sau đó ông đã nghĩ ra một tư tưởng vĩ đại: đề nghị các bạn của ông tự truyền bá thông tin về chất bổ sung dinh dưỡng này cho người quen của họ và trả hoa hồng nếu họ bán được sản phẩm. Ông cũng quyết định trả hoa hồng bất cứ ai bán được sản phẩm.

Lịch sử ngành kinh doanh theo mạng
Lịch sử ngành kinh doanh theo mạng


Kết quả thật bất ngờ: thông tin về các chất bổ sung dinh dưỡng có lợi bắt đầu được truyền bá rộng rãi. Doanh thu bán hàng của công ty tăng vượt quá sức tưởng tượng, mọi người đề nghị gặp ông để tham khảo về thông tin sản phẩm mới này. Từ đó ngành Kinh Doanh Theo Mạng bắt đầu ra đời.

Năm 1934 ông Karl Renborg sáng lập ra công ty "Vitamins California" và nhờ hệ thống bán hàng kiểu mới này, khi người tiêu dùng cũng trở thành người truyền bá sản phẩm công ty của ông đã nhanh chóng đạt doanh số 7 triệu USD mà không hề mất một đồng quảng cáo nào. Nhờ tiết kiệm được quảng cáo và các khâu trung gian (đại lý bán buôn, bán lẻ, kho bãi.) nên những người tham gia vào hệ thống của ông có thể nhận được thù lao rất cao.
Thành quả từ kinh doanh theo mạng
Thù lao từ kinh doanh theo mạng

Sau đó kinh doanh theo mạng tiếp tục phát triển mạnh mẽ trải qua 3 thời kỳ: thời kỳ hình thành (1940-1979), thời kỳ bùng nổ (1979-1990), thời kỳ phát triển mạnh mẽ (1990 trở đi). Các công ty áp dụng phương pháp bán hàng truyền thống như Ford, Colgate, Canon, Coca-cola và nhiều công ty nổi tiếng khác đã bắt đầu áp dụng hình thức kinh doanh theo mạng.

Theo thống kê, cứ 100 người đang là triệu phú trên thế giới thì có đến 40 người xuất phát theo ngành Kinh doanh theo mạng và trong thế kỷ 21 này thì 70% hàng hóa và dịch vụ sẽ phát triển theo phương thức kinh doanh này.
Bạn đang muốn Khởi nghiệp kinh doanh nhưng không có nhiều vốn hãy xem gợi ý cho bạn




Nguon http://www.imlm.vn/kinh-doanh-theo-mang/kinh-doanh-theo-mang-co-tu-khi-nao.html

Tạo Web API: Spring Boot - Maven - Swaggershare





NGUON!
Hi all,
Hôm nay rãnh rỗi, làm cái tutorial tạo web API bằng Spring boot hướng dẫn anh em.
Trước hết, mình dùng maven để built project nên ai thiếu maven thì cài vào, maven - eclipse trong dạy nhau học đã có topic hướng dẫn anh em tìm setup xem nhé.
Mình dùng eclipse và Ubuntu nhưng nó cũng tương tự với window,nên không vấn đề gi.
Đầu tiên, tạo maven project, nếu bạn không có plugin maven hoặc muốn dùng command line thì gõ lệnh như sau:
mvn archetype:generate -DgroupId=com.canh
   -DartifactId=JavaSpring 
   -DarchetypeArtifactId=maven-archetype-quickstart 
   -DinteractiveMode=false
DgroupId là tên package, thông thường nếu có domain riêng thì dùng tên domain nhưng ghi ngược lại, điều này đảm bảo khi public ra cộng đồng sẽ không bị trùng.
DartifactId là project name.
DarchetypeArtifactId=maven-archetype-quickstart để chỉ rằng bạn chỉ muốn generate cấu trúc project Maven đơn giản:
.
└── JavaSpring
    ├── pom.xml
    └── src
        ├── main
        │   └── java
        │       └── com
        │           └── canh
        │               └── App.java
        └── test
            └── java
                └── com
                    └── canh
                        └── AppTest.java
Tiếp đó, tạo project eclipse với maven. nếu có plugin maven trong eclipse thì có thể sử dùng plugin đó để tạo, nếu không có hoặc muốn dùng command line thì gõ lệnh:
mvn eclipse:eclipse
Lệnh này sẽ đọc file pom và generate eclipse project cho nên nhớ cd đến thư mục chứa file pom trước khi dùng lệnh này.
Lúc này cấu trúc thư mục vừa tạo sẽ như sau:
.
└── JavaSpring
    ├── .classpath
    ├── pom.xml
    ├── .project
    └── src
        ├── main
        │   └── java
        │       └── com
        │           └── canh
        │               └── App.java
        └── test
            └── java
                └── com
                    └── canh
                        └── AppTest.java
Giờ chỉ cần dùng chức năng add exist project trong eclipse là sử dụng được rồi
Tiếp theo là phần Spring boot.
Sau khi add project vào eclipse, mở file pom.xml lên và add thư viện spring boot vào:
<parent>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-parent</artifactId>
               <version>1.3.1.RELEASE</version>
</parent>
 
<dependencies>
        <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <scope>test</scope>
        </dependency>
</dependencies>
Chú ý khi thêm bất cứ gì vào file pom.xml bạn cần update lại project của mình, ở đây mình dùng lệnh để update:
mvn clean install
Vậy là có thể implement API với Spring boot,
Trong project, mình tạo một số package và folder package như hình dưới:
.
├── main
│   ├── assembly
│   │   └── assembly.xml
│   ├── java
│   │   └── com
│   │       └── canh
│   │           ├── App.java
│   │           ├── config
│   │           │   └── WebConfig.java
│   │           ├── dto
│   │           │   └── UserDto.java
│   │           ├── services
│   │           │   ├── ExampleServicesImpl.java
│   │           │   └── ExampleServices.java
│   │           └── web
│   │               └── api
│   │                   └── ExampleController.java
│   ├── resources
│   │   └── application.properties
│   └── script
│       └── startServer.sh
└── test
    └── java
        └── com
            └── canh
                └── AppTest.java
Giờ các bạn chỉ chú ý đến main.java.com.canh, mấy cái khác liên quan đến config để deploy, có thời gian mình sẽ giải thích.
App.java:
package com.canh;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
 
/**
 * Hello world!
 *
 */
@Configuration
@EnableAutoConfiguration
@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}
App.java là file chính dùng để start program, nhớ add thêm annotation như trên để Spring nhận biết.
UseDto.java: Dùng để chứa json object từ client gửi lên server
/**
 * 
 */
package com.canh.dto;
 
/**
 * @author canh
 *
 */
public class UserDto {
        String userName;
        String password;
 
        /**
         * @return the user
         */
        public String getUserName() {
               return userName;
        }
 
        /**
         * @param user
         *            the user to set
         */
        public void setUserName(String userName) {
               this.userName = userName;
        }
 
        /**
         * @return the password
         */
        public String getPassword() {
               return password;
        }
 
        /**
         * @param password
         *            the password to set
         */
        public void setPassword(String password) {
               this.password = password;
        }
 
}
ExampleServices.java: Inteface định nghĩa 2 services:
/**
 * 
 */
package com.canh.services;
 
/**
 * @author canh
 *
 */
public interface ExampleServices {
        String test(String user, String password);
 
        String getNameForID(String userID);
}
ExampleServicesImpl.java: implement interface:
package com.canh.services;
 
import org.springframework.stereotype.Service;
 
/**
 * 
 * @author canh
 *
 */
@Service
public class ExampleServicesImpl implements ExampleServices {
 
        @Override
        public String test(String user, String password) {
               if (user != null) {
                       return "success";
               }
               return "error";
 
        }
 
        @Override
        public String getNameForID(String userID) {
 
               return new String("canh - " + userID);
        }
 
}
chú ý là add thêm annotation @Service để Spring nhận biết.
Cuối cùng là ExampleController.java :
package com.canh.web.api;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.canh.dto.UserDto;
import com.canh.services.ExampleServices;
/**
 * 
 * @author canh
 *
 */
@RestController
@RequestMapping("/example")
public class ExampleController {
        
        @Autowired
        private ExampleServices examplServices;
        
        @RequestMapping(value="/login" ,method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.ALL_VALUE)
        public ResponseEntitylogin(@RequestBody UserDto user){
               String result = examplServices.test(user.getUserName(),user.getPassword());
               return new ResponseEntity(result,HttpStatus.OK);
        }
        
        @RequestMapping(value="/nameForID" ,method = RequestMethod.GET,produces=MediaType.ALL_VALUE)
        public ResponseEntitynameForID(@RequestParam(value = "userID") String userID) {
               String result = examplServices.getNameForID(userID);
               return new ResponseEntity(result, HttpStatus.OK);
        }
        
}
@RequestMapping("/example"): định nghĩa url truy cập các API được tạo trong class này
@RestController: Với annotation này, nó sẽ thông báo cho Spring biết, class này dùng để nhận các request từ client lên.
@Autowired: tự động set method hoặc khởi tạo đối tượng.
Sau khi xong những bước trên các bạn có thể run file App.java để start server. Port mặc định là 8080, nhưng các bạn có thể thây đổi port bằng cách tạo file application.properties như cấu trúc bên trên và đổi port:
server.port=9090
Vậy là xong, các bạn build lại project có thể dùng lệnh
mvn package
hoặc
mvn clean install
Nhưng làm sao để test: Các bạn có thể add addon postman trên chrome để test, hoặc viết code unit test. Mình sẽ hướng dẫn viết unit test trong bài khác nếu anh em muốn :smile:
Đường dẫn test cho login API bên trên: http://localhost:9090/example/login2.
Giờ mình muốn hướng các bạn đến vấn đề này: Khi tạo xong web API làm sao để người khác biết cách sử dụng? viết document, tất nhiên nhưng đừng nghĩ đến mở word hay code một trang html để tạo API document. Đó cũng là một cách nhưng hãy nghĩ để cách tốt nhất có thể. Tốt là cung cấp đủ thông tin cần thiết và nhanh chóng.
Ở bài này mình hướng dẫn dùng Swagger để tạo API document cho web Api vừa tạo xong.
Add thêm thư viện swagger vào pom.xml
<dependency>
               <groupId>io.springfox</groupId>
               <artifactId>springfox-swagger2</artifactId>
               <version>2.2.2</version>
</dependency>
<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
</dependency>
sau đó implement file WebConfig.java như dưới:
package com.canh.config;
 
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 
 
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@Configuration
@EnableWebMvc
@EnableSwagger2
public class WebConfig extends WebMvcAutoConfigurationAdapter {
        @Bean
        public Docket managementDocket(){
               return new Docket(DocumentationType.SWAGGER_2).groupName("my-project").apiInfo(apiInfo()).select().paths( PathSelectors.regex("/.*")).build();
        }
 
        private ApiInfo apiInfo(){
               return new ApiInfoBuilder().title("My-project").description("Document for API").termsOfServiceUrl("https://canh1412.wordpress.com/").contact("Canh").license("Proprietary").licenseUrl("https://canh1412.wordpress.com/").version("1.0").build();
        }
 
}
build lại project và start lại program, lúc này API document API sẽ được tự động generate và anh em có thể test API mình đã tạo trên đó: http://localhost:9090/swagger-ui.html#3 :


Chúc anh em cuối tuần vui vẻ
github: https://github.com/nguyenhuuca/JavaSpringBootExample8