SpringBoot的基本使用(一)
环境
InteilliJ IDEA ULTIMATE 2018.1, Gradle.
idea专业版安装
http://idea.lanyus.com/,在页面右上部,点击“使用帮助”,根据页面http://idea.lanyus.com/help/help.html中的破解补丁激活条目下的内容进行激活:
下载idea专业版zip版
下载 http://idea.lanyus.com/jar/JetbrainsCrack-2.6.2.jar 并将 JetbrainsCrack-2.6.2.jar 放置到 D盘根目录。
在 IntelliJ IDEA 安装目录中找到 idea.exe.vmoptions 和 idea64.exe.vmoptions ,以文本格式打开并同时在两个文件最后追加 -javaagent:D:/JetbrainsCrack-2.6.2.jar。
将系统时间需改为一个比较远的时间,如2050年.
启动 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}
安装 IntelliJ IDEA ,安装后选择试用,全部步骤完毕并关闭 IntelliJ IDEA 后,将系统时间修改回来。
配置jdk,sdk
welcome to Intellij IDEA —>Config—>project Defaults–>Project Structure—>在弹出界面的左侧选中SDKs,在右侧点击“+”,选择JDK或Android SDK,进行配置。
新建springBoot gradle 项目
- File->New->Project –>左侧选择 Spring Initializr—>右侧选择sdk版本 ->next
- 输入Group,Artifact名称,选择Type类型为Gradle
- 给Spring选择依赖,web必须选,其它根据需要。
- 完成,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')
}
文件目录
- src/main/java , resources
- ApiApplication.java:程序入口类,src/main/java/com/cdcweb/api/ApiApplication.java
- com.cdcweb.bean 实体类
- com.cdcweb.personapis Controller类
- src/main/resources/static
- src/main/resources/templates
- 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会自动加载启动类所在包下及其子包下的所有组件.