Java实现跨域方式
一、什么是跨域?为什么会出现跨域
定义
- 跨域(CORS)是指不同域名之间相互访问。跨域,指的是浏览器不能执行其他网站的脚本,它是由浏览器的同源策略所造成的,是浏览器对于JavaScript所定义的安全限制策略。
当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。
原因
- 在前后端分离的模式下,前后端的域名是不一致的,此时就会发生跨域访问问题。在请求的过程中我们要想回去数据一般都是post/get请求,所以…跨域问题出现。
- 跨域问题来源于JavaScript的同源策略,即只有 协议+主机名+端口号(如存在)相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。跨域问题是针对JS和ajax的,html本身没有跨域问题,比如a标签、script标签、甚至form标签(可以直接跨域发送数据并接收数据)等
什么情况会跨域
- 同一协议, 如http或https
- 同一IP地址, 如127.0.0.1
- 同一端口, 如8080
以上三个条件中有一个条件不同就会产生跨域问题。
跨域之CorsFilter
CorsFilter
是 Spring 框架提供的一个用于处理跨域请求的过滤器。在开发中,我们常常需要处理前端发来的跨域请求,CorsFilter
就可以帮助我们实现这一功能。
CorsFilter
主要用于设置跨域请求的响应头,以允许跨域请求能够被成功处理。具体来说,CorsFilter
可以设置以下响应头:
- Access-Control-Allow-Origin:允许访问的源地址;
- Access-Control-Allow-Methods:允许访问的请求方法;
- Access-Control-Allow-Headers:允许访问的请求头;
- Access-Control-Allow-Credentials:是否允许发送 Cookie 等身份凭证;
- Access-Control-Max-Age:缓存预检请求的时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); source.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(source); } }
|
Java实现Result
Result: Result类的编写方式,最主要的功能就是为了向前端发送数据的时候能够更高效快捷:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package com.springmvc.demo.commen.vo;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor public class Result<T> { private Integer code; private String message; private T data;
public static <T> Result<T> success(){ return new Result<>(200,"success",null); } public static <T> Result<T> success(T data){ return new Result<>(200,"success",data); } public static <T> Result<T> success(T data,String message){ return new Result<>(200,message,data); } public static <T> Result<T> success(String message){ return new Result<>(200,message,null); }
public static <T> Result<T> fail(){ return new Result<>(201,"success",null); } public static <T> Result<T> fail(Integer code){ return new Result<>(code,"success",null); } public static <T> Result<T> fail(Integer code,String message){ return new Result<>(code,message,null); } public static <T> Result<T> fail(String message){ return new Result<>(201,message,null); } }
|
实现自动填装创建时间和更新时间(工具类)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.springmvc.demo.util;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler {
@Override public void insertFill(MetaObject metaObject) { log.info("start insert fill ...."); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); }
@Override public void updateFill(MetaObject metaObject) { log.info("start update fill ...."); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); } }
|
然后在实体类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.springmvc.demo.entity;
import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.io.Serializable; import java.time.LocalDateTime;
@Data @TableName("o_user") public class User implements Serializable { @TableId(value = "userId", type = IdType.AUTO) private Integer userId; private String username; private String password; @TableField(fill = FieldFill.INSERT ,value = "create_time") private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE ,value = "update_time") private LocalDateTime updateTime; }
|
application.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| server: port: 8888
spring: datasource: username: root password: 123qwe url: jdbc:mysql://localhost:3306/test1?characterEncoding=UTF-8&useSSL=false&useUnicode=true driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource
logging: level: com.ouwen: info
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: table-prefix: o_ id-type: auto
|
mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings>
<environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123qwe"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/**.xml"/> </mappers> </configuration>
|
CodeGenerator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package com.springmvc.demo;
import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.sql.Types; import java.util.Collections;
public class CodeGenerator { public static void main(String[] args) { String url = "jdbc:mysql:///test1"; String username = "root"; String password = "123qwe"; String moduleName = "demo"; String mapperLocation = "C:\\Users\\DIO\\Desktop\\大学\\大三上\\面向对象\\Spring MVC\\demo\\src\\main\\resources\\mapper\\" + moduleName; String tables = "o_user"; FastAutoGenerator.create(url, username, password) .globalConfig(builder -> { builder.author("owc") .outputDir("C:\\Users\\DIO\\Desktop\\大学\\大三上\\面向对象\\Spring MVC\\demo\\src\\main\\java"); }) .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> { int typeCode = metaInfo.getJdbcType().TYPE_CODE; if (typeCode == Types.SMALLINT) { return DbColumnType.INTEGER; } return typeRegistry.getColumnType(metaInfo);
})) .packageConfig(builder -> { builder.parent("com.springmvc") .moduleName(moduleName) .pathInfo(Collections.singletonMap(OutputFile.xml, mapperLocation)); }) .strategyConfig(builder -> { builder.addInclude(tables) .addTablePrefix("o_"); }) .templateEngine(new FreemarkerTemplateEngine()) .execute(); } }
|
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter-test</artifactId> <version>2.3.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.4.3.4</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.31</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency>
|