针对vue和andorid和spring boot的开发总结
前后端分离
后端:Spring Boot提供RESTful API(数据接口用@RestController,业务层用@Service,数据层用JPA/MyBatis)。
前端:
Web端:Vue(Vue Router路由管理 + Vuex状态管理 + Axios请求封装)。
Android端:Retrofit/OkHttp处理网络请求,Gson解析JSON。
通信协议:统一使用HTTPS + JSON格式。
认证与授权
JWT方案:
用户登录后,Spring Boot生成JWT返回客户端。
Vue/Android存储Token(Web用localStorage,Android用SharedPreferences)。
每次请求在Header中携带Token(Authorization: Bearer
Spring Security配置鉴权规则(如@PreAuthorize("hasRole('ADMIN')"))。
二、开发实践关键点
后端(Spring Boot)
API设计:
遵循RESTful规范(如GET /api/users,POST /api/login)。
使用Swagger生成接口文档(springdoc-openapi依赖)。
数据库交互:
JPA简化CRUD(CrudRepository接口),复杂SQL用MyBatis。
事务管理:@Transactional注解保证数据一致性。
全局处理:
统一异常处理(@ControllerAdvice返回标准错误JSON)。
跨域配置(@CrossOrigin或全局CORS配置)。
Web前端(Vue)
请求封装:
javascript
// axios实例
const api = axios.create({ baseURL: 'https://api.example.com' });
api.interceptors.request.use(config => {
config.headers.Authorization = Bearer ${localStorage.getItem('token')}
;
return config;
});
状态管理:
Vuex管理用户信息、全局配置等共享状态。
路由守卫:
javascript
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !localStorage.getItem('token')) next('/login');
else next();
});
Android端(Java)
网络请求:
java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
UserService service = retrofit.create(UserService.class);
Call
异步处理:
使用RxJava或Coroutines避免主线程阻塞。
数据持久化:
SharedPreferences存储Token,Room数据库缓存业务数据。