文章目录
SpringMVC注解
①@RequestHeader、@CookieValue
@RequestMapping("/test")
public void test(@RequestHeader("host") String host,@CookieValue("JSESSIONID" String cookie)){}
@RequestHeader
可以把Request header
部分的值绑定到方法的参数上。@CookieValue
可以把Request header
中关于cookie
的值绑定.
②@RequestBody
将请求体映射实体类,需要指定http header
中content-type
为application/json charset=utf-8
③restful请求
使用场景 | |
---|---|
@GetMapping |
查询 |
@PostMapping |
新增 |
@PutMappiing |
修改 |
@DeleteMapping |
删除 |
④SpringBoot注解映射配置文件
扫描配置文件注解:@PropertySource({"classpath:resource.properties"})
映射属性:@Value("${test.name}")
json框架常用注解
指定字段不返回:@JsonIgnore
指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
空字段不返回:@JsonInclude(Include.NON_NUll)
指定别名:@JsonProperty
SpringBoot注解映射配置文件
扫描配置文件注解:@PropertySource({"classpath:resource.properties"})
映射属性:@Value("${test.name}")
个性化banner
springboot
默认的启动banner
图为下
我们可以修改这个banner
信息,添加配置文件,然后指定spring-banner-location
,默认值为:classpath:banner.txt
修改后:
异常处理
自定义一个处理异常的类,使用@RestControllerAdvice
或@ControllerAdvice
,使用@ExceptionHandler
捕获异常,一下给出异常处理的两种方式,一种是返回json数据,第二种是返回错误页面。
@RestControllerAdvice
public class CustomExtController {
//捕获全局异常,返回json数据
@ExceptionHandler(value = Exception.class)
Object handleException(Exception e, HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
//捕获特定异常,返回错误页面
@ExceptionHandler(value = MyException.class)
Object handleMyException(Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg",e.getMessage());
return modelAndView;
}
}
SpringBoot项目打包成war包
①在pom.xml
中添加<packaging>war</packaging>
,然后maven install
打包。
②以war
包的方式启动,主启动类需要改动,如下:
@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringbootApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}