一、后端返回json数据
pom.xml
< ! -- fastjson-- >
< dependency>
< groupId> com. alibaba< / groupId>
< artifactId> fastjson< / artifactId>
< version> 1.2 .76 < / version>
< / dependency>
Code类
public enum Code {
SUCCESS ( 0 , "成功!" ) ,
LOGIN_FAIL ( 10001 , "用户名或密码错误" ) ,
RESULT_STRING_METHOD_VALUE_WRONG ( 10000 , "resultString方法参数错误" ) ,
CODE_MISTAKE ( 100002 , "后台代码错误" ) ,
CODE_REGIST_REPEAT ( 100003 , "账户名已存在!" ) ;
private Integer code;
private String message;
Code ( Integer code, String message) {
this . code = code;
this . message = message;
}
public Integer getCode ( ) {
return code;
}
public void setCode ( Integer code) {
this . code = code;
}
public String getMessage ( ) {
return message;
}
public void setMessage ( String message) {
this . message = message;
}
}
Result类
@Data
public class Result < T> implements Serializable {
private Integer code;
private String message;
private T data;
public Result ( Code code, T data) {
this . code = code. getCode ( ) ;
this . message = code. getMessage ( ) ;
this . data = data;
}
public Result ( Code code) {
this . code = code. getCode ( ) ;
this . message = code. getMessage ( ) ;
}
public Result ( String error) {
this . code= 500 ;
this . message = error;
}
}
Utils
import com. alibaba. fastjson. JSON;
import java. util. HashMap;
import java. util. Map;
public class Utils {
public static String FailResult ( Code code) {
Result< Object> result = new Result < > ( code) ;
return toJsonString ( result) ;
}
public static String FailResult ( String message) {
Result< Object> result = new Result < > ( message) ;
return toJsonString ( result) ;
}
public static String result ( Object object) {
Result< Object> result = new Result < > ( Code. SUCCESS, object) ;
String string = toJsonString ( result) ;
return string;
}
public static String resultMulti ( Object. . . args) {
int len = args. length;
HashMap< String, Object> map = new HashMap < String, Object> ( ) ;
Result result = null;
if ( ( len+ 2 ) % 2 != 0 ) {
result = new Result ( Code. RESULT_STRING_METHOD_VALUE_WRONG, null) ;
}
if ( len== 0 ) {
result = new Result < Map> ( Code. SUCCESS, null) ;
}
String name = null;
Object o = null;
for ( int i = 0 ; i< len; i++ ) {
if ( ( i+ 2 ) % 2 == 0 ) {
name = args[ i] . toString ( ) ;
}
if ( ( i+ 2 ) % 2 != 0 ) {
o = args[ i] ;
}
if ( name!= null&& o!= null) {
map. put ( name, o) ;
name= null;
o= null;
}
}
result = new Result < Map> ( Code. SUCCESS, map) ;
String string = toJsonString ( result) ;
return string;
}
public static String toJsonString ( Result re) {
return JSON. toJSONString ( re) ;
}
}
二、跨域
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings ( CorsRegistry registry) {
registry. addMapping ( "/**" )
. allowedOrigins ( "*" )
. allowedMethods ( "GET" , "HEAD" , "POST" , "PUT" , "DELETE" , "OPTIONS" )
. allowCredentials ( true )
. maxAge ( 3600 )
. allowedHeaders ( "*" ) ;
}
}