package com.how2java.tmall.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CORSConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
//所有请求都允许跨域
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
}
通过CROS的方式实现跨域访问,目的是避免ajax跨域请求获取不到数据的问题
package com.how2java.tmall.config;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value=Exception.class)
public String defaultErrorHandler(HttpServletRequest req,Exception e)throws Exception{
e.printStackTrace();
Class constraintViolationException=Class.forName("org.hibernate.exception.ConstraintViolationException");
if(null!=e.getCause() && constraintViolationException==e.getCause().getClass()) {
return "违反了约束,多半是外键约束";
}
return e.getMessage();
}
}
全局异常处理,主要是处理异常:违反约束constraintViolationException。由于数据库的表之间存在外键约束,因此在删除和增加时会受到约束,比如某个表的某个字段在新增时不能为空。如果为空则报异常,提示这个异常是由外键约束引起的。



