Springboot基础使用2

本文深入探讨SpringBoot中日期格式化、全局数据处理、跨域请求解决方案及拦截器的高级应用,通过具体代码实例,详细讲解如何在项目中灵活运用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、①在对象中可以使用日期的格式化注解,这样输入的时候的传入的是new Date(),但是在输出的时候获取的String类型。这个是springBoot中默认使用jackson-databind。 这样必须在返回对象的时候,会自动经过jackson将对象转化成json,这样就会将date转化成"yyyy-MM-dd HH:mm:ss"的格式。

class Teacher{
....
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date date;

}

② 可以换成Gson和fastJson,但是需要设置配置文件。

二、@ControllerAdvice是用来处理全局数据,一般搭配@ExceptionHandle @ModelAttribute @InitBinder使用

①全局异常处理

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(Exception.class)  // 这里可以修改为其他的异常
    public void exceptionHandler(Exception e, HttpServletResponse response) throws IOException {
      response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
	    e.printStackTrace();
     writer.write("发现异常"+   e.toString());
	    writer.flush();
	    writer.close();
  }
}

②添加全局数据

@ControllerAdvice
public class GlobalConfig {

@ModelAttribute(value = "info")
public Map<String,String> userInfo(){
    HashMap<String, String> stringStringHashMap = new HashMap<>();
    stringStringHashMap.put("name","小妞");
    return stringStringHashMap;
}

/**    使用的时候
*  可以用model.asMap(); 用相应的map获取
*/
}

三、使用cors,解决前端跨域请求的问题,主要是配置一个WebMvcConfigureAdapter类

https://www.cnblogs.com/shihaiming/p/8716830.html

四、SpringBoot的拦截器的使用,不再是在spring-mvc中配置了。
而是使用@Configuration 注解进行配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

   @Override
    public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor(new MyInterceptor())
     	       .addPathPatterns("/**")  //表示拦截路径
  	          .excludePathPatterns("/hello"); //表示排除的路径
  }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值