Spring Boot的简单使用

去官网下载或者直接使用IDEA创建

直接下载

操作mysql数据库

1.依赖

       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-jpa</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
       </dependency>

2. 写一个接口继承JpaRepository

public interface DescImgRep extends JpaRepository<DescImg,Integer> {
}

3.写Service接口 、实现类、model

public interface DescImgService {
    List<DescImg> findAll();
    DescImg findById(Integer id);
    void save(DescImg descImg);
    void update(DescImg descImg);
    void deleteById(Integer id);
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service//此注解十分重要
public class DescImgServiceImpl implements DescImgService{

    @Autowired
    DescImgRep descImgRep;

    @Override
    public List<DescImg> findAll() {
        List<DescImg> list = descImgRep.findAll();
        return list;
    }

    @Override
    public DescImg findById(Integer id) {
        Optional<DescImg> descImgRepById = descImgRep.findById(id);
        return descImgRepById.get();
    }

    @Override
    public void save(DescImg descImg) {
        descImgRep.save(descImg);
    }

    @Override
    public void update(DescImg descImg) {
    }
    
    @Override
    public void deleteById(Integer id) {
    }
}

import javax.persistence.*;
@Entity
@Table(name = "desc_img")
public class DescImg {
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Id
    @Column(name = "id")
    Integer id = 0;
    String descs;
    String imgUrl;
    String uploadTime;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDescs() {
        return descs;
    }
    public void setDescs(String descs) {
        this.descs = descs;
    }
    public String getImgUrl() {
        return imgUrl;
    }
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
    public String getUploadTime() {
        return uploadTime;
    }
    public void setUploadTime(String uploadTime) {
        this.uploadTime = uploadTime;
    }
}

4.写Controller

@RestController
public class DescImgController {

    @Autowired
    DescImgService service;//搞不清为啥不是实现类而是那个接口

    @RequestMapping("/getDescImgList")
    @ResponseBody
    public List<DescImg> Hello() {
        List<DescImg> all = service.findAll();
        return all;
    }

    @RequestMapping(value = "/saveDescImgInfo", method = RequestMethod.POST)
    @ResponseBody
    public String saveDescImgInfo(@RequestBody DescImg descImg) {
        try {
            service.save(descImg);
            return "成功";
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return "失败";
        }
    }

    @RequestMapping(value = "/saveImg",method = RequestMethod.POST)
    public String saveImg(@RequestParam MultipartFile params, Integer id) {
        String path = "D://mysql_img/uploads/";
        String fileType = params.getOriginalFilename().substring(params.getOriginalFilename().indexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "");
        DescImg serviceById = service.findById(id);
        String fileEndPath = path + fileName + fileType;
        serviceById.setImgUrl(fileEndPath);
        //保存路劲到数据库
        service.save(serviceById);
        //保存文件到本地(数据库或者硬盘上面)
        try {
            params.transferTo(new File(fileEndPath));
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return fileEndPath;
    }
	
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public DescImg getInfoById(Integer id) {
        return service.findById(id);
    }
	//映射图片
    @RequestMapping(value = "/getPic", method = RequestMethod.POST, produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity getPic(Integer id) {
        try {
            String imgUrl = service.findById(id).getImgUrl();
            System.out.println(imgUrl);
            FileInputStream stream = new FileInputStream(imgUrl);
            byte[] byteArray = getByteArray(stream);

            HttpHeaders headers = new HttpHeaders();
            String fileType = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
            System.out.println(fileType);
            if (fileType == "png" || fileType == "PNG") {
                headers.setContentType(MediaType.IMAGE_PNG);
            }else if (fileType == "gif") {
                headers.setContentType(MediaType.IMAGE_GIF);
            } else {
                headers.setContentType(MediaType.IMAGE_JPEG);
            }
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] getByteArray(FileInputStream inputStream) {
        try {
            int b;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] byteTemp = new byte[1024];
            while ((b = inputStream.read(byteTemp)) != -1) {
                byteArrayOutputStream.write(byteTemp, 0, b);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return new byte[]{};
        }
    }
}
上一篇:微信分享到朋友圈 QQ空间 代码实现


下一篇:C# 保存网络图片至本地项目中