Springboot基础使用2

倾然丶 夕夏残阳落幕 提交于 2020-01-28 11:17:07

一、①在对象中可以使用日期的格式化注解,这样输入的时候的传入的是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"); //表示排除的路径
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!