在前端代码中引入Axios.js文件 通过:
axios.get("http://localhost:8080/deptC").then((resp)=>{
console.log(resp,resp.data)
this.deptlist=resp.data;
})
请求后端数据 展示到浏览器控制台
效果图展示:
引入vue.js和axios.min.js 代码展示:
<script src="/vue/vue.min.js"></script>
<script src="/vue/axios.min.js"></script>
并且使用v-for循坏 渲染页面
<div id="app">
<button @click="showDept">点击显示数据</button>
<table border="1" cellpadding="20" cellspacing="0">
<tr>
<th>序号</th>
<th>部门名称</th>
<th>部门位置</th>
<th>部门领导</th>
</tr>
<tr v-for="dept in deptlist">
<td>{{dept.did}}</td>
<td>{{dept.name}}</td>
<td>{{dept.dlocation}}</td>
<td>{{dept.leader}}</td>
</tr>
</table>
</div>
<script>
new Vue({
el:'#app', //挂载app
data:{
deptlist:[] //数组 用于存储数据
},
methods:{
showDept(){
axios.get("http://localhost:8080/deptC").then((resp)=>{
console.log(resp,resp.data)
this.deptlist=resp.data; //通过get请求拿到数据 将数据赋给deptList数组
})
}
}
})
</script>
使用Tomcat服务器部署:
使用WebServlet注解,将Java类标记为处理HTTP请求的servlet
@WebServlet("/deptC")
启用tomcat测试访问:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("测试访问");
List<Dept> list = deptService.list();
System.out.println(list);
//数据转化为json格式 在响应给浏览器
String json_String = JSON.toJSONString(list);
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json_String);
}