SpringBoot的基本使用(一)

SpringBoot的基本使用(一)

环境

InteilliJ IDEA ULTIMATE 2018.1, Gradle.

idea专业版安装

http://idea.lanyus.com/,在页面右上部,点击“使用帮助”,根据页面http://idea.lanyus.com/help/help.html中的破解补丁激活条目下的内容进行激活:

  1. 下载idea专业版zip版

  2. 下载 http://idea.lanyus.com/jar/JetbrainsCrack-2.6.2.jar 并将 JetbrainsCrack-2.6.2.jar 放置到 D盘根目录。

  3. 在 IntelliJ IDEA 安装目录中找到 idea.exe.vmoptions 和 idea64.exe.vmoptions ,以文本格式打开并同时在两个文件最后追加 -javaagent:D:/JetbrainsCrack-2.6.2.jar。

  4. 将系统时间需改为一个比较远的时间,如2050年.

  5. 启动 IntelliJ IDEA , 输入如下激活码激活(激活码中内容可修改)。

    ThisCrackLicenseId-{
    "licenseId":"ThisCrackLicenseId",
    "licenseeName":"Rover12421",
    "assigneeName":"",
    "assigneeEmail":"rover12421@163.com",
    "licenseRestriction":"For Rover12421 Crack, Only Test! Please support genuine!!!",
    "checkConcurrentUse":false,
    "products":[
    {"code":"II","paidUpTo":"2099-12-31"},
    {"code":"DM","paidUpTo":"2099-12-31"},
    {"code":"AC","paidUpTo":"2099-12-31"},
    {"code":"RS0","paidUpTo":"2099-12-31"},
    {"code":"WS","paidUpTo":"2099-12-31"},
    {"code":"DPN","paidUpTo":"2099-12-31"},
    {"code":"RC","paidUpTo":"2099-12-31"},
    {"code":"PS","paidUpTo":"2099-12-31"},
    {"code":"DC","paidUpTo":"2099-12-31"},
    {"code":"RM","paidUpTo":"2099-12-31"},
    {"code":"CL","paidUpTo":"2099-12-31"},
    {"code":"PC","paidUpTo":"2099-12-31"}
    ],
    "hash":"2911276/0",
    "gracePeriodDays":7,
    "autoProlongated":false}
  6. 安装 IntelliJ IDEA ,安装后选择试用,全部步骤完毕并关闭 IntelliJ IDEA 后,将系统时间修改回来。

配置jdk,sdk

welcome to Intellij IDEA —>Config—>project Defaults–>Project Structure—>在弹出界面的左侧选中SDKs,在右侧点击“+”,选择JDK或Android SDK,进行配置。

新建springBoot gradle 项目

  1. File->New->Project –>左侧选择 Spring Initializr—>右侧选择sdk版本 ->next
  2. 输入Group,Artifact名称,选择Type类型为Gradle
  3. 给Spring选择依赖,web必须选,其它根据需要。
  4. 完成,Run Application,运行项目

build.gradle文件设置

buildscript {
    ext {
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.cdcweb'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

文件目录

  1. src/main/java , resources
  2. ApiApplication.java:程序入口类,src/main/java/com/cdcweb/api/ApiApplication.java
  3. com.cdcweb.bean 实体类
  4. com.cdcweb.personapis Controller类
  5. src/main/resources/static
  6. src/main/resources/templates
  7. src/main/resources/application.properites 配置文件

主要文件内容

ApiApplication.java
package com.cdcweb.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}
PersonApis.java
package com.cdcweb.api.personapis;
import com.cdcweb.api.bean.FileResult;
import com.cdcweb.api.bean.Person;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
@RestController
public class PersonApis {
    /**
     * http://ip:8084/api/person/123
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/person/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    public Person after(@PathVariable("id") Integer id) {
        id = id > 4 || id < 0 ? 0 : id;
        return PersonTools.initPersons().get(id);
    }

    /**
     * http://ip:8084/api/100/person
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/person", method = {RequestMethod.GET, RequestMethod.POST})
    public Person before(@PathVariable("id") Integer id) {
        id = id > 4 || id < 0 ? 0 : id;
        return PersonTools.initPersons().get(id);
    }

    /**
     * http://ip:8084/api/100/personList
     *
     * @return
     */
    @RequestMapping(value = "/personList", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<Integer, Person> persons() {
        return PersonTools.initPersons();
    }

    /**
     * http://192.168.0.164:8084/api/person?id=90&name=kkk
     * 使用postman测试时   需要设置x-www-form-urlencoded类型才能正确返回。
     *
     * @param id
     * @param name
     * @return
     */
    @RequestMapping(value = "/person", method = {RequestMethod.GET, RequestMethod.POST})
    public Person origin(@RequestParam(value = "id", required = true, defaultValue = "0") Integer id, @RequestParam(value = "name", required = true, defaultValue = "cdc") String name) {
        id = id > 4 || id < 0 ? 0 : id;
        Person person = PersonTools.initPersons().get(id);
        person.setName(name);
        return person;
    }

    /**
     * http://ip:8084/api/upPerson
     * 上传json数据 并返回json数据
     * <p>
     * Content-Type
     * application/json
     *
     * @param person
     * @return
     */
    @RequestMapping(value = "/upPerson", method = RequestMethod.POST)
    @ResponseBody
    public Person person(@RequestBody Person person) {
        person.setCurrentdate(new Date().toString());
        return person;
    }

    /**
     * http://ip:8084/api/singleFileParams
     * 文件上传具体实现方法(单文件上传)
     * 使用postman测试时 选择form-data  不手动添加content-type
     * <p>
     * 否则会报the request was rejected because no multipart boundary was found错误
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/singleFileParams", method = RequestMethod.POST)
    @ResponseBody
    public FileResult singleFileParams(@RequestParam("file") MultipartFile file, @RequestParam("name") String name, @RequestParam("id") Integer id) {
        FileResult fileResult=null;
        List<String> fileLists=new ArrayList<>();
        if (!file.isEmpty()) {
            doSingleFile(file,fileLists);
            String str="['name:'"+name+",id:"+id+"]";
            fileResult = new FileResult(fileLists, str, FileResult.Result.SUCCESS);
            return fileResult;
        } else {
            fileResult=new FileResult(FileResult.Result.ERROR,"没有上传文件");
            return fileResult;
        }
    }

    /**
     * http://ip:8084/api/singleFile
     * 文件上传具体实现方法(单文件上传)
     * 使用postman测试时 选择form-data  不手动添加content-type
     * <p>
     * 否则会报the request was rejected because no multipart boundary was found错误
     */
    @RequestMapping(value = "/singleFile", method = RequestMethod.POST)
    @ResponseBody
    public FileResult singleFile(@RequestParam("file") MultipartFile file) {
        FileResult fileResult = null;
        List<String> fileLists = new ArrayList<>();
        if (!file.isEmpty()) {
            doSingleFile(file,fileLists);
            fileResult = new FileResult(fileLists, "[]", FileResult.Result.SUCCESS);
            return fileResult;
        } else {
            fileResult = new FileResult(FileResult.Result.ERROR, "没有上传文件");
            return fileResult;
        }
    }

    private FileResult doSingleFile(MultipartFile file,List<String> fileLists){
        FileResult fileResult=null;
        try {
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String prefix = fileName.substring(0, fileName.lastIndexOf("."));
            fileName = prefix + "_" + UUID.randomUUID() + suffix;
            fileLists.add(fileName);
            // 这里只是简单例子,文件直接输出到项目路径下。
            // 实际项目中,文件需要输出到指定位置,需要在增加代码处理。
            // 还有关于文件格式限制、文件大小限制
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(createParentFile(), fileName)));
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            fileResult = new FileResult(FileResult.Result.ERROR, e.getLocalizedMessage());
            return fileResult;
        } catch (IOException e) {
            fileResult = new FileResult(FileResult.Result.ERROR, e.getLocalizedMessage());
            return fileResult;
        }
        return fileResult;

    }

    /**
     * http://ip:8084/api/files
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     * @param request
     * @return
     */
    @RequestMapping(value = "/files", method = RequestMethod.POST)
    public @ResponseBody FileResult uploads(HttpServletRequest request) {
        FileResult fileResult=null;
        List<String> fileLists=new ArrayList<>();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String name=request.getParameter("name");
        String id=request.getParameter("id");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String Fname=file.getOriginalFilename();
                    //文件后缀
                    String suffix=Fname.substring(Fname.lastIndexOf("."), Fname.length());
                    String prefix=Fname.substring(0, Fname.lastIndexOf("."));
                    Fname=prefix+"_"+UUID.randomUUID()+suffix;
                    fileLists.add(Fname);
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(createParentFile(),Fname)));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    fileResult=new FileResult(FileResult.Result.ERROR,e.getLocalizedMessage());
                    return fileResult;
                }
            } else {
                fileResult=new FileResult(FileResult.Result.ERROR,"没有上传文件");
                return fileResult;
            }
        }
        String str="";
        if((name==null || id==null)){
            str="[]";
        }else{
            str="['name:'"+name+",id:"+id+"]";
        }
        fileResult=new FileResult(fileLists,str,FileResult.Result.SUCCESS);
        return fileResult;
    }

    private File createParentFile() {
        File file = new File("e:/sptapi/upload/");
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
        return file;
    }
}
application.properties

server.port=8089
server.servlet.context-path=/api

#上传文件大小的设置
spring.servlet.multipart.max-file-size=1024Mb
spring.servlet.multipart.max-request-size=1024Mb

SpringBoot 启动报错, has no explicit mapping for /error

SpringBoot 启动报错:This application has no explicit mapping for /error, so you are seeing this as a fallback.



Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Jun 23 19:10:18 CST 2018

There was an unexpected error (type=Not Found, status=404).

No message available



原因是【Application启动类放的位置不对】要将Application放在最外层,也就是要包含所有子包。

比如你的groupId是com.cdcweb,子包就是所谓的com.cdcweb.xxx,所以要将Application放在com.cdcweb包下。

请参考以下结论:spring-boot会自动加载启动类所在包下及其子包下的所有组件.
SpringBoot个用于JavaWeb开发的框架,相比其他框架,它更简化开发,约定大于配置。SpringBoot基于Spring开发,不提供Spring框架的核心特性和扩展功能,而是用于快速、敏捷地开发基于Spring框架的应用程序。SpringBoot并不是用来替代Spring的解决方案,而是与Spring框架紧密结合的工具,旨在提升Spring开发者的体验。 在SpringBoot中,可以通过创建SpringBoot项目来开始开发。可以使用Lombok插件来动态生成get/set/toString等功能。在代码中,可以使用@SpringBootApplication注解来标记应用入口的类,并在main方法中使用SpringApplication.run方法来启动服务。 SpringBoot的语法是基于Spring框架,所以可以使用Spring框架提供的各种注解和配置来进行开发。例如,可以使用@Controller注解来标记控制器类,使用@RequestMapping注解来定义请求映射。同时,可以使用@EnableAutoConfiguration注解来自动配置应用程序,省去了繁琐的配置过程。此外,还可以使用@ConfigurationProperties注解来读取配置文件中的属性值,方便进行配置管理。总之,SpringBoot的语法灵活简洁,让开发者能够更容易地使用Spring框架并集成各种常用的中间件和开源软件。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot高级用法()](https://blog.youkuaiyun.com/AimerDaniel/article/details/119041990)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot详解](https://blog.youkuaiyun.com/qq_34124252/article/details/126246129)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值