第一种:添加@CrossOrigin
注解
在Controller层对应的方法上添加@CrossOrigin或者类上添加@CrossOrigin
package com.example.controller;import com.example.model.Book;
import com.example.service.InBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;@RestController
@CrossOrigin
public class BookController {@Autowiredprivate InBookService bookService;String message = "";@RequestMapping("/queryAllBooks")public List<Book> getAllBooks(){List<Book> allBooks = bookService.getAllBooks();return allBooks;}@RequestMapping("/addBook")public String addBook(@RequestBody Book book){//用Mybatis执行insert语句的时候,插入成功会返回1,不成功则会抛出异常,捕获一下异常就好try {bookService.addBook(book);message = "增加用户成功";}catch (Exception exception){message = "增加用户异常";}return message;}@RequestMapping("/updateBookById")public String updateBook(@RequestBody Book book){//用Mybatis执行insert语句的时候,插入成功会返回1,不成功则会抛出异常,捕获一下异常就好try {bookService.updateBookById(book);message = "更新用户成功";}catch (Exception exception){message = "更新用户异常";}return message;}@RequestMapping("/deleteBookById")public String deleteBookById(@RequestBody Map<String,Integer> params){//用Mybatis执行insert语句的时候,插入成功会返回1,不成功则会抛出异常,捕获一下异常就好try {Integer id = params.get("id");bookService.deleteBookById(id);message = "删除用户成功";}catch (Exception exception){message = "删除用户异常";}return message;}@RequestMapping("/getBookById")public Book getBookById(@RequestBody Map<String,Integer> params){int id = params.get("id");Book b = bookService.getBookById(id);return b;}}
第二种:添加CORS过滤器
新建配置类CorsConfig,创建CorsFilter
过滤器,允许跨域
@Configuration
public class CorsConfig {// 跨域请求处理@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();//允许所有域名进行跨域调用config.addAllowedOrigin("*");//允许所有请求头config.addAllowedHeader("*");//允许所有方法config.addAllowedMethod("*");// 添加映射路径,我们拦截一切请求UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return new CorsFilter(source);}
}
第三种:实现WebMvcConfigurer
,重写addCorsMappings
方法
@Configuration
public class CorsConfig implements WebMvcConfigurer {// 跨域请求处理@Overridepublic void addCorsMappings(CorsRegistry registry) {registry// 设置允许跨域的路径.addMapping("/**")// 设置允许跨域请求的域名.allowedOriginPatterns("*")// 是否允许证书.allowCredentials(true)// 设置允许的方法.allowedMethods("GET", "POST", "DELETE", "PUT")// 设置允许的header属性.allowedHeaders("*")// 跨域允许时间.maxAge(3600);}
}
全局配置有可能出现跨域失败的情况,改为过滤器解决跨域问题之后就解决了,在此附上过滤器跨域代码:
@Component
public class CorsFilter implements Filter {//销毁时候调用的方法@Overridepublic void destroy() {}@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "*");chain.doFilter(req, res);}//初始化调用的方法//当服务器 被启动的时候,调用@Overridepublic void init(FilterConfig arg0) throws ServletException {}
}
参考:
Springboot解决跨域问题的三种方式_springboot跨域注解-CSDN博客