1,springboot 创建一个跨域请求的配置文件,类文件,用注解,配置成配置文件
@Configuration public class CustomCorsConfiguration { public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); // 允许跨域访问的域名 corsConfiguration.addAllowedOrigin("*"); // 请求头 corsConfiguration.addAllowedHeader("*"); // 请求方法 corsConfiguration.addAllowedMethod(HttpMethod.DELETE); corsConfiguration.addAllowedMethod(HttpMethod.POST); corsConfiguration.addAllowedMethod(HttpMethod.GET); corsConfiguration.addAllowedMethod(HttpMethod.PUT); corsConfiguration.addAllowedMethod(HttpMethod.DELETE); corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS); // 预检请求的有效期,单位为秒。 corsConfiguration.setMaxAge(3600L); // 是否支持安全证书 corsConfiguration.setAllowCredentials(true); return corsConfiguration; } }
2,配置服务器的话,选择用jetty,之所以不选择tomcat,因为tomcat总有各种错误,网上找了一大串都没有用,所以就用jetty了,其实jetty这个服务器挺不错的,在pom.xml屏蔽tomcat
<dependency> <groupId>org.springframework.boot </groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> 加上jetty依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
3,mui.ajax 写法如下
js代码:
var data ={ 'username':loginInfo.account, 'passworld':loginInfo.password }; var url ='http://10.2.146.3:8004/users/getvalue'; mui.ajax(url, { data:JSON.stringify(data), type:'POST',//HTTP请求类型 dataType:'json',//服务器返回json格式数据 timeout:100000,//超时时间设置为10秒; headers:{ 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' }, crossDomain:true, success:function(data) { if (data) { //alert(data+'--'+data.stu1+'--'+data.stu1.id) return owner.createState(loginInfo.account, callback); } else { return callback('用户名或密码错误'); } }, error:function(xhr,type,errorThrown) { //异常处理; mui.alert(type); console.log(xhr); console.log(type); console.log(errorThrown); } });
4,springboot controller的写法 如下:
//@CrossOrigin(origins="http://10.2.146.3:8004",maxAge=36000) 这个也可以不需要 @RequestMapping(value="getvalue",method = RequestMethod.POST) @ResponseBody public Map<String, Object> getvalue(HttpServletResponse response,@RequestBody(required = false) String requestJson){ System.out.println(requestJson); /*response.setHeader("Access-Control-Allow-Origin", "*");*/ //可以不需要 Map<String, Object> hashmap = new HashMap<>(); hashmap.put("stu1", new Student(1001, "huk1")); hashmap.put("stu2", new Student(1002, "huk2")); hashmap.put("stu3", new Student(1003, "huk3")); hashmap.put("stu4", new Student(1004, "huk4")); return hashmap; }