iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
1

這篇來寫-先從網站http://localhost:8080/api/products 來看springboot
https://ithelp.ithome.com.tw/upload/images/20210725/20119035JpvfWdTIrQ.png

到springboot增加JPA的管理:
https://ithelp.ithome.com.tw/upload/images/20210725/201190355HWUi5K2DS.png

原來的程式碼:

package com.huang.ecommerce.config;

import com.huang.ecommerce.entity.Product;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.http.HttpMethod;

@Configuration

public class MyDataRestConfig implements RepositoryRestConfigurer {

    

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

        HttpMethod[] theUnsupportedActions={HttpMethod.PUT,HttpMethod.POST,HttpMethod.DELETE};

        config.getExposureConfiguration()
            .forDomainType(Product.class)
                .withItemExposure(((metdata, httpMethods) -> httpMethods.disable(theUnsupportedActions)))
            .withCollectionExposure(((metdata, httpMethods) -> httpMethods.disable(theUnsupportedActions)));


    }
}

新增關於entity的管理和類型後

package com.huang.ecommerce.config;

import com.huang.ecommerce.entity.Product;
import com.huang.ecommerce.entity.ProductCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.http.HttpMethod;

import javax.persistence.EntityManager;
import javax.persistence.metamodel.EntityType;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Configuration

public class MyDataRestConfig implements RepositoryRestConfigurer {

    private EntityManager entityManager;

    @Autowired
    public MyDataRestConfig(EntityManager theEntityManager){
        entityManager = theEntityManager;
    }



    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

        HttpMethod[] theUnsupportedActions={HttpMethod.PUT,HttpMethod.POST,HttpMethod.DELETE};

        config.getExposureConfiguration()
            .forDomainType(Product.class)
                .withItemExposure(((metdata, httpMethods) -> httpMethods.disable(theUnsupportedActions)))
            .withCollectionExposure(((metdata, httpMethods) -> httpMethods.disable(theUnsupportedActions)));

        config.getExposureConfiguration()
                .forDomainType(ProductCategory.class)
                .withItemExposure(((metdata, httpMethods) -> httpMethods.disable(theUnsupportedActions)))
                .withCollectionExposure(((metdata, httpMethods) -> httpMethods.disable(theUnsupportedActions)));

        exposeIds(config);


    }

    private void exposeIds(RepositoryRestConfiguration config) {
        Set<EntityType<?>> entities =entityManager.getMetamodel().getEntities();

        List<Class> entityClasses =new ArrayList<>();

        for(EntityType tempEntityType : entities){
            entityClasses.add(tempEntityType.getJavaType());
        }

        Class [] domainTypes = entityClasses.toArray(new Class[0]);
        config.exposeIdsFor(domainTypes);

    }
}

再重啟springboot可以看到id編號:

https://ithelp.ithome.com.tw/upload/images/20210725/20119035AYUjg16g3v.png


回到angular的VS CODE新增資料夾-使用語法ng generate class common/product-category
會跳出是否允許防火牆開放->按允許才會新增
https://ithelp.ithome.com.tw/upload/images/20210725/2011903583XUAmfHOj.png

到檔案product-category.ts開始新增

export class ProductCategory {
  id: number;
  categoryName: string;


}


然後再新增menu
/images/emoticon/emoticon13.gif


繼續昨天的閒聊~就是資料導入~

Ex. 1 通訊錄
用字元串流 Reader/Writer 輸入/輸出通訊錄

import java.io.*;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */
public class BufferedFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws IOException {
        // TODO code application logic here
        
        System.out.println("要建立的通訊錄檔名");
        System.out.print("➟");
        
        BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
        String filename=br.readLine();
        BufferedWriter bw =new BufferedWriter(new FileWriter(filename));
        String str=new String();
        do{
            System.out.print("請輸入姓名:");
            str=br.readLine();
            bw.write(str,0,str.length());
           bw.write('\t');
           
        System.out.print("請輸入電話號碼:");
        
        str=br.readLine();
        bw.write(str,0,str.length());
        bw.newLine();
        
        System.out.print("還要輸入另一筆資料嗎(y/n):");
        str=br.readLine();
        
    }while(str.equalsIgnoreCase("Y"));
    bw.flush();
    bw.close();
    System.out.println("\n已將資料寫入檔案"+filename);
     System.out.print("您想立即檢視檔案內容嗎(y/n):");  
     str=br.readLine();
     
     if(str.equalsIgnoreCase("Y")){
         BufferedReader bfr=new BufferedReader(new FileReader(filename));
         while((str=bfr.readLine())!=null)
             System.out.println(str);
         bfr.close();
     }
        
}
}


程式碼:


Ex. 2 File Converter
學生成績位元串流檔  字元串流檔

字元串流檔  位元串流檔

程式碼1:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */
public class Student implements Serializable {
    public Student (String s,short e,short m,short j){
        name=s;
        EScore=e;
        MScore=m;
        JScore=j;
    }
    
    public Student(){}
    
    public String getN(){return name;}
    public Short getE(){return EScore;}
    public Short getM(){return MScore;}
    public Short getJ(){return JScore;}
    
    public double getAvg(){
        return(EScore+MScore+JScore);
    }
    private String name;
    private short EScore;
    private short MScore;
    private short JScore;
    
}````

---

程式碼2:
````import java.io.*;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */
public class WriteObject {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        
        System.out.println("請輸入要建立的學生成績檔檔名");
        System.out.print("➡");
        
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String filename=br.readLine();
        ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(filename));
        
        String str=new String();
        int counter=0;
        
        do{
            counter++;
            
            System.out.print("請輸入學生姓名:");
            String name=br.readLine();
            
            System.out.print("請輸入英文分數:");
            str=br.readLine();
            short e=Short.parseShort(str);
            
            System.out.print("請輸入數學分數:");
            str=br.readLine();
            short m=Short.parseShort(str);
            
            System.out.print("請輸入Java分數:");
            str=br.readLine();
            short j=Short.parseShort(str);
            
            Student ss=new Student(name,e,m,j);
            
            os.writeObject(ss);
            
            System.out.print("還要輸入另外一筆資料嗎(y/n)");
            
            str=br.readLine();
            
        }while(str.equalsIgnoreCase("Y"));
        
        os.flush();
        os.close();
        
        System.out.println("\n已寫入"+counter+"筆學生資料至檔案"+filename);
        
    }
    
}



ObjectStream File  FileReader/FileWriter

程式碼3:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */
public class ReadObject {
    public static void main(String[] args) throws IOException,ClassNotFoundException {
        // TODO code application logic here
        
        System.out.println("要讀取的學生成績檔檔名");
        System.out.print("➡");
        
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String filename=br.readLine();
        
        int counter=0;
        double Esum=0;
        double Msum=0;
        double Jsum=0;
        Student ss=new Student();
        
        System.out.println("姓名\t英文\t數學\tJava\t平均");
        System.out.println("-------------------------------------");
        
        try(ObjectInputStream ois=
                new ObjectInputStream(new FileInputStream(filename))){
         while(true){
                ss=(Student)ois.readObject();
                counter++;
                
                Esum +=ss.getE();
                Msum +=ss.getM();
                Jsum +=ss.getJ();
               System.out.println(ss.getN()+'\t'+ss.getE()+'\t'
                       +ss.getM()+'\t'+ss.getJ()+'\t'
                       +ss.getAvg()); 
                
            }
        }
      catch(EOFException e){
          System.out.println("\n已從檔案"+filename+"讀取"+counter+"筆學生資料");
          System.out.println("\n全員英文平均"+(Esum/counter));
          System.out.println("\n全員數學平均"+(Msum/counter));
          System.out.println("\n全員JAVA平均"+(Jsum/counter));
      }  
}
}

DEAR ALL 我們明天見 /images/emoticon/emoticon08.gif


上一篇
倒數第5天
下一篇
倒數第3天
系列文
把前後分離製作的網站組起來30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言