SpringBoot2.x基础

SpringMVC注解

①@RequestHeader、@CookieValue

RequestHeader

@RequestMapping("/test")
public void test(@RequestHeader("host") String host,@CookieValue("JSESSIONID" String cookie)){}

@RequestHeader可以把Request header部分的值绑定到方法的参数上。@CookieValue可以把Request header中关于cookie的值绑定.

②@RequestBody

​ 将请求体映射实体类,需要指定http headercontent-typeapplication/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

​ 我们可以修改这个banner信息,添加配置文件,然后指定spring-banner-location,默认值为:classpath:banner.txt

banner图位置

修改后:
个性化banner

异常处理

​ 自定义一个处理异常的类,使用@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);
    }

}

发布了81 篇原创文章 · 获赞 124 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/qq_38697437/article/details/104169574