经过springboot快速构建jar包,这个轻量级的jar能够很方便的部署至任一有java环境的服务器,便于测试。html
经过eclipse-mars新建一个spring starter project项目。java
1. 在eclipse的向导中,新建2.1.5.RELEASE版本的springboot项目,由于选项中包含这个,但是完成以后,在pom.xml的第一行报一个Unknow的错误,在problems中显示spring
Description Resource Path Location Type
Unknown pom.xml /myproject line 1 Maven Configuration Problemjson
百思不得其解,后面发现将其改为2.1.4.RELEASE便可。windows
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
考虑应该是eclipse的bug,固然也有多是个人环境的问题。springboot
2. 通常新建一个springboot项目都会添加Web依赖,而后通常为了测试springboot项目是否正常,会写一个HelloController,这里要注意几个容易搞错的注解。bash
@Controller @RestController服务器
@GetMapping @PostMappingmvc
其实我这里主要说的就是@Controller @RestController这两个注解:app
@Controller public class HelloController { @RequestMapping("/hello") public String hello() { return "hello"; } }
这样去访问localhost:8080/hello获得的是以下错误
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Fri May 17 16:34:41 CST 2019 There was an unexpected error (type=Internal Server Error, status=500). Circular view path [hello]: would dispatch back to the current handler URL [/hello] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
是由于hello()方法返回的hello其实会去找hello.html(这里根据使用的什么模板,好比用thymeleaf能够配置.html的视图)的页面,由于springmvc的视图解析会自动加上默认的后缀,就像咱们通常会配置的prefix suffix WEB-INF .jsp等信息。
因此这里就用到@RestController这个注解,能够看到它里面实际上是包含了@ResponseBody这个注解,也就是将hello方法的return的字符当成json直接返回,而不用进行视图解析。只须要替换以下就能够,固然GetMapping能够很方便的知道这是一个get请求,不像RequestMapping还须要经过属性来区分。
@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "hello"; } }
这时,访问localhost:8080/hello,页面返回了hello字符串,显示正常。
3. 因为用到了静态资源文件,代码中须要读取文件流,一开始我用绝对路径,在本地测试没有问题,可是打成jar包丢到服务器去运行时,发现报错:E:/ssm/workspace-mars/myproject/src/main/resources/static/certs/key-store.p12资源找不到。
打开jar包,发现static资源目录在BOO-INF/classes/static/
起初用到ResourceUtils工具类,对应于org.springframework.util.ResourceUtils,用到的方法org.springframework.util.ResourceUtils.getFile("classpath:key-store.p12");
后面还用到ClassPathResource类,ClassPathResource resource = new ClassPathResource("key-store.p12");
而后就能够直接获取InputStream。
1.File file= ResourceUtils.getFile("classpath:key-store.p12"); 2.ClassPathResource classPathResource = new ClassPathResource("key-store.p12"); 获取文件:classPathResource .getFile(); 获取流:classPathResource .getInputStream(); #这里注意,若是文件不在根目录下,须要用相对路径,好比static/certs/key-store.p12 #经过网上查阅资料,知道springboot项目,经过第一种方式在windows下能够实现,可是放到Linux系统中就找不到File,因此最好是用第二种方式,而后用getInputStream()流的方式来读取文件。
4. springboot项目从1.5开始不支持log4j,仅支持log4j2。这里须要配置。
通常日志咱们采用slf4j在项目中使用接口来调用,而不用关心具体实现类,代码以下:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger logger = LoggerFactory.getLogger(ClassName.class);
通常咱们采用log4j做为实现,只须要配置一个log4j.properties文件