赞
踩
交互格式:json
假设我们有如下数据表
若实现将数据读取到前端页面显示
package com.lnu.pojo;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
package com.lnu.controller; import com.lnu.pojo.User; import com.lnu.service.UserServer; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; @RestController public class UserController { @Resource private UserServer userServer; @GetMapping("/user/list") public List<User> getUserInfo() { return userServer.getUserInfo(); } }
package com.lnu.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lnu.pojo.User;
public interface UserMapper extends BaseMapper<User> {
}
package com.lnu.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.lnu.pojo.User;
import java.util.List;
public interface UserServer extends IService<User> {
List<User> getUserInfo();
}
import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class UserServerImpl extends ServiceImpl<UserMapper, User> implements UserServer { @Resource private UserMapper userMapper; @Override public List<User> getUserInfo() { List<User> users = userMapper.selectList(null); return users; } }
<template> <el-table :data="users" border style="width: 29%"> <el-table-column prop="id" label="编号" width="100"> </el-table-column> <el-table-column prop="name" label="姓名" width="150"> </el-table-column> <el-table-column prop="age" label="年龄" width="100"> </el-table-column> <el-table-column prop="email" label="邮箱" width="200"> </el-table-column> </el-table> </template> <script> import axios from "axios"; export default { name: "UserInfo", data() { return { users: null } }, mounted() { this.getUserInfo(); }, methods: { getUserInfo() { axios.get('/user/list') .then(res=>{ console.log(res) this.users = res.data }) .catch(error => { console.error(error); }); } } } </script> <style scoped> </style>
<template> <div id="app"> <UserInfo/> </div> </template> <script> import UserInfo from './components/UserInfo.vue' export default { name: 'App', components: { UserInfo } } </script> <style> </style>
由于前端运行在端口8082上而后端运行在8088端口上,Vue存在跨域问题
在后端编写CorsConfig 类解决跨域问题
package com.lnu.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 跨域问题 */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //是否发送Cookie .allowCredentials(true) //放行哪些原始域 .allowedOriginPatterns("*") .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) .allowedHeaders("*") .exposedHeaders("*"); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。