一、知识准备
1.springboot
springboot简化了配置编写,可以快速开发web应用,已经成为java主流的开发框架。
2.vue
前端开发也进入框架时代,vue能够满足前后端开发分离的需要,快速独立构建前端应用。
3.mybatis-plus
mybatis-plus是对mybatis的扩展,在保留了mybatis灵活使用sql语句的基础上,又扩展了基本的CRUD功能调用,大大提高了开发效率,程序员不用在编写、调试基本的CRUD映射sql语句。
4.json
前后端分离后,采用json格式作为前后端数据交互标准。
5.Restful API设计规范
RESTFUL是一种网络应用程序的设计风格和开发方式,客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源。
二、前后端集成
1、使用Maven创建springboot项目
2、引入pom配置,添加mybatis-plus、druid、mysql依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- Mysql-Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!-- Mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- Pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
3、添加application.yml配置
server:
port: 8081
spring:
datasource:
name: ShiroJwt
url: jdbc:mysql://127.0.0.1:3306/jwt_shirodb?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
# 使用Druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
druid:
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mybatis:
# Mybatis配置Mapper路径
mapper-locations: classpath:mapper/*.xml
# Mybatis配置Model类对应
type-aliases-package: xzy.yyk.entity
4、添加启动类
@MapperScan("xzy.yyk.mapper") //扫描映射器
@SpringBootApplication
public class WebApp {
public static void main(String[] args) {
SpringApplication.run(WebApp.class, args);
}
}
5、构建框架
Controller:接口定义层,主要用于响应请求,不做业务逻辑处理;
Dao:Mybatise接口层
Service:业务处理层
Repository:Spring Data JPA对应层
entity:JavaBean层
Domain:数据映射层,与数据库对应;
Dto:数据传输层,用于接受请求数据
Vo:视图层,用于封装界面数据
Po:mybatise映射对象
Mapper:mapper.xml
创建统一消息返回类ResponseBean
public class ResponseBean {
/**
* HTTP状态码
*/
private Integer code;
/**
* 返回信息
*/
private String msg;
/**
* 返回的数据
*/
private Object data;
}
6.添加LoginController,处理用户登录
@RestController注解,具有Controller和ResponseBody两个注解的功能,把类标注为控制器,且方法返回数据处理为json格式。按RESTFullApi规范,@GetMapping注解用于处理get请求,@PostMapping处理post请求。
@RestController
public class LoginController {
@Resource
private LoginService loginService;
@GetMapping("hello")
public String hello(){
return "hello springboot 启动成功!";
}
@PostMapping("/api/user/login")
public ResponseBean login(@RequestParam String username,@RequestParam String password) {
System.out.println(username+":"+password);
User userTemp=new User();
userTemp.setPhone(username);
userTemp.setPwd(password);
ResponseBean responseBean=new ResponseBean(-1,"登录失败,错误的用户名称或密码",null);
User loginUser=loginService.get(userTemp);
if(loginUser==null){
//-1,登录失败,用户不存在
return responseBean;
}else {
if (!loginUser.getPwd().equals(userTemp.getPwd())){
responseBean.setCode(-2);//-1,登录失败,密码错误
responseBean.setMsg("登录失败,密码错误");
return responseBean;
}else {
responseBean.setCode(0);//0,登录成功
responseBean.setMsg("登录成功!");
responseBean.setData(loginUser);
return responseBean;
}
}
}
}
服务层处理
@Service
public class LoginServiceImpl implements LoginService{
@Resource
private UserMapper userMapper;
@Override
public User getById(Long id) {
User user=userMapper.selectById(id);
return user;
}
@Override
public User get(User obj) {
QueryWrapper<User> query=new QueryWrapper<>();
query.eq("phone",obj.getPhone());
User user=userMapper.selectOne(query);
System.out.println(user);
return user;
}
}
mapper接口
@Repository
public interface UserMapper extends BaseMapper<User> {
}
7.Vue框架登录处理,登录表单
<el-form :model="loginForm" :rules="rules" ref="login" label-width="0px" class="ms-content">
<el-form-item prop="username">
<el-input v-model="loginForm.username" placeholder="username">
<el-button slot="prepend" icon="el-icon-lx-people"></el-button>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
type="password"
placeholder="password"
v-model="loginForm.password"
@keyup.enter.native="submitForm()"
>
<el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
</el-input>
</el-form-item>
<div class="login-btn">
<el-button type="primary" @click="submitForm()">登录</el-button>
</div>
<p class="login-tips">Tips : 用户名和密码随便填。</p>
</el-form>
8.表单提交事件submitForm()处理
submitForm() {
//this.interceptor() //拦截请求
let that=this; //改变this指向
that.$refs.login.validate(valid => {
if (valid) {
let formData=new FormData()
//把json数据转换为FormData格式
formData.append("username",that.loginForm.username)
formData.append("password",that.loginForm.password)
console.log(that.loginForm)
axios({
method:'post',
url:'/api/user/login', //不带token的验证
data:formData //提交form表单数据
}).then(res=>{//请求成功时
if (res.status==200 && res.data.code==-1){ //返回对象不空时
that.$message.success('用户名称或密码错误,请重新登陆');
}else if(res.status==200 && res.data.code==-2){
that.$message.success('登录失败,密码错误');
} else if (res.status==200 && res.data.code==0){
console.log("成功保存token,准备跳转路由")
that.$router.push('/');//发送跳转路由,登陆页面
}else{//返回空对象时
console.log(res)
that.$message.error('用户名称或密码错误,请重新登陆');
}
}).catch(err=>{
console.log(err)
that.$message.error('登陆失败!')
})
} else {
that.$message.error('请输入账号和密码');
console.log('error submit!!');
return false;
}
});
}
9.跨域处理
由于前后端运行在不同的进程中,至少端口号不相同,分别代表不同的网站,而浏览器不能执行其他网站的脚本(浏览器的同源策略)因此产生了跨域问题,
具体表现是http请求时,会产生异常:
XMLHttpRequest cannot load http://localhost:8081/user/login. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:9520’ is therefore not allowed access. The response had HTTP status code 404.
测试如下:
axios({
method:'post',
baseURL: 'http://localhost:8081',
url:'/user/login', //不带token的验证
data:formData
})
跨域解决方法:修改vue.config.js
devServer: {
host: 'localhost',
port: 9520,
proxy: {//设置代理
'/api':{ //将域名映射到/api,请求时url以/api开头
//target:'http://jsonplaceholder.typicode.com',
target: 'http://localhost:8081', //后端请求服务域名和端口
changeOrigin:true,//设置是否允许跨域,默认为false
pathRewrite:{
'^/api':'/' //路径重写后,就代理到对应后端
}
}
}
}
在用户登录时,url中添加前缀/url
axios({
method:'post',
url:'/api/user/login', //不带token的验证
data:formData //提交form表单数据
})
三、 小结
springboot与vue整合时,数据交互格式采用json,后端springboot需要采用RESTfullApI规范。由于前后端分离,事实成为2个独立运行的网络应用进程,需要注意解决跨域问题。