掌握Javaweb 开发 实现前后端交互

在前端代码中引入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);


    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值