1.在目标方法上添加 @CrossOrigin注解
package com.example.control;
import com.example.pojo.Result;
import com.example.pojo.SbUser;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class LoginController {
// @Autowired
@Resource(name = "userServiceImpl") //按名称
private UserService userService;
@RequestMapping( "/login")
@CrossOrigin //可以解决跨域问题,测试玩玩,实际不推荐
public Result login(@RequestBody SbUser sbUser) {
System.out.println(sbUser);
String id_info = sbUser.getLeibie();
String name = sbUser.getName();
String password = sbUser.getPassword();
System.out.println(id_info);
System.out.println(name);
System.out.println(password);
if ("sb_Admin".equals(id_info)) {
boolean flag = userService.sb_login(name, password);
if (flag) {
return Result.success();
} else {
return Result.error("账号或密码错误");
}
} else if ("sys_Admin".equals(id_info)){
boolean flag = userService.sys_login(name, password);
if (flag) {
return Result.success();
} else {
return Result.error("账号或密码错误");
}
}else if ("system_Admin".equals(id_info)){
boolean flag = userService.sys_login(name, password);
if (flag) {
return Result.success();
} else {
return Result.error("账号或密码错误");
}
} else {
return Result.error("请选择身份");
}
}
}
2.添加CORS过滤器
步骤:创建一个配置类,在配置类当中添加过滤器。
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){ //配置过滤器 推荐
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
}
3.实现WebMvcConfigurer接口,重写addCorsMappings方法
package com.yuhui.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer { //实现WebMvcConfigurer接口
@Override
public void addCorsMappings(CorsRegistry registry) { //重写addCorsMappings方法
registry.addMapping("/**") //设置映射
.allowedOriginPatterns("*") //设置允许哪些域来访问
.allowedMethods("GET","POST","PUT","DELETE","HEAD","OPTIONS") //允许哪些方法能访问
.allowCredentials(true) //允许是否可以携带cookie
.maxAge(3600) //设置有效期为3600秒,意思是在3600秒以内,浏览器可以不用再次访问(这时间内跨域ok)
.allowedHeaders("*"); //允许携带头部信息
}
}