1 使用 idea 新建 springboot 项目##
- 打开 file -> new Project
- 选择 Spring Initializr
- 根据提示引导创建项目
image
2 配置数据源
application.yml 中添加数据源配置信息
spring:
datasource:
url: jdbc:mysql://localhost:3306/hellen?characterEncoding=utf8&allowMultiQueries=true&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
- url 是数据库链接
- name 是数据库登录名
- password 是数据库登录密码
- driver-class-name 是数据库驱动名
3 集成 mybatis
- 创建 domain 包
- 创建 mappper 接口的包
-
创建 mapper 的 xml 映射文件的文件夹
image.png
在application.xm文件中增加
mybatis:
mapper-locations: classpath:mapper/*.xml
在启动类上贴标签 @MapperScan(value = "com.example.demo.mapper"),
这样 mybatis 就集成了
4 跨域处理##
使用 filter 过滤器的方式进行跨域处理
@Component
@Slf4j
public class CorsFilter implements Filter {
/**
* json web token 在请求头的名字
*/
private String tokenHeader = "X_Auth_Token";
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String token = request.getHeader("X_Auth_Token");
System.out.println(token + "token");
String Origin = request.getHeader("Origin");
System.out.println("Origin:" + Origin);
System.out.println("tokenHeader:" + this.tokenHeader);
log.info("Origin: " + Origin);
response.setHeader("Access-Control-Allow-Origin", Origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, " + this.tokenHeader);
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
到此,springboot项目就基本创建完了
网友评论