文章目录
前言
springboot与vue的项目开发
一、通过vue脚手架建立vue项目
- 建立空项目文件夹
- 以管理员身份运行cmd
- 通过cd命令定位到你建立的空文件夹
- 通过vue create 项目名 建立项目
- feature -》下图 -》选vue2.x -》Y -》in package.json -》N
- 运行:npm run serve
若下载较慢可以设置淘宝的镜像加速
npm config set registry https://registry.npm.taobao.org
二、安装组件
- element-ui(定位到项目里,并且以管理员身份运行)
在main.js中导入
import ElementUI from ‘element-ui’;
import ‘element-ui/lib/theme-chalk/index.css’;
使用
Vue.use(ElementUI);
- anxios
安装 npm i anxios -S
创建 request.js
import axios from 'axios'
const request = axios.create({
baseURL: '/api', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
在main.js中先注册request对象
import request from "@/utils/request"
Vue.prototype.request = request
使用
request.get("http://localhost:9090/user/page",{
params: {
pagenum: this.pagenum,
pagesize: this.pagesize,
username: this.username,
nickname: this.nickname,
address: this.address
}
} ).then(res=>
{
this.tableData=res.records
this.total=res.total
})
三、创建springboot项目
- 通过idea创建
- next
3.选择依赖
-
在你选择的位置中要再添加一个文件名,否则就会在你选择的位置里创建项目,而不是创建一个新的文件项目
-
创建并配置数据库(更改properties为yml)
server:
port: 9090
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/sv?serveTimezone=GMT%2b8
username: root
password: 123
mybatis:
mapper-locations: classpath:mapper/*.xml
- 在配置文件中更改端口号避免前后端端口冲突
server.port=9090
四、创建实体类
安装lombok插件
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
private String nickname;
private String email;
private String phone;
private String address;
}
五、配置mapper(yml中)
mybatis:
mapper-locations: classpath:mapper/*.xml
简单的增删改查可以通过注释直接写
例如
@Mapper
@Repository
public interface UserMapper {
@Select("select * from user")
List<User> findall();
@Insert("insert into user(username,password,nickname,email,phone,address) values " +
"(#{username},#{password},#{nickname},#{email},#{phone},#{address})")
int insert(User user);
int update(User user);
@Delete("delete from user where id=#{id}")
Integer deleteByid( @Param("id") Integer id);
}
若复杂的可以通过在mapper.xml中写动态SQL实现
例如
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xhq.sv.mapper.UserMapper">
<update id="update" parameterType="com.xhq.sv.entity.User">
update user
<set>
<if test="username != null">
username = #{username},
</if>
<!--<if test="password != null">-->
<!--password = #{password}-->
<!--</if>-->
<if test="nickname != null">
nickname = #{nickname},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="address != null">
address = #{address}
</if>
</set>
<where>
id=#{id}
</where>
</update>
</mapper>
五、service层
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public int insert(User user){
return userMapper.insert(user);
}
public List<User> findall(){
return userMapper.findall();
}
public int update(User user){
if(user.getId()==null){
return userMapper.insert(user);
}
else{
return userMapper.update(user);
}
}
public Integer deleteByid( Integer id){
return userMapper.deleteByid(id);
}
}
六、controller层
@RestController
//返回的是json字符串
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/findall")
public List<User> findall(){
return userService.findall();
}
@RequestMapping("/insert")
//@RequestBody接收前端的json字符串
private Integer save( @RequestBody User user){
return userService.insert(user);
}
@RequestMapping("/update")
private Integer update(@RequestBody User user){
return userService.update(user);
}
@RequestMapping("/delete/{id}")
//@PathVariable接收前端的参数
private Integer delete(@PathVariable Integer id){
return userService.deleteByid(id);
}
}
七、前后端跨域问题
在后端设置,写一个config类
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 {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}