利用Servlet给前端传json格式数据和图片

用Servlet给前端发数据

在后端src里面创建一个java文件

继承 HttpServlet 没有提示是因为没有导入tomcat库

添加方式:

1689156230931.png

1689156272108.png

注释@WebServlet("/DeptC")

如:

1689156466056.png

/DeptC :是自己定义的网站路径

当访问到http://localhost:8081/DeptC这个网站路径就会运行这个java

在里面创建继承HtpServlet里的doget方法

给页面输入简单的文字

@WebServlet("/imgC")
public class ImgC extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置文字编码
        resp.setContentType("application/json;charset=utf-8");
        //响应给浏览器
        resp.getWriter().write("Hello,Servlet");
    }
}

resp: 是response的缩写中文对应的响应 就是响应给前端也就是浏览器页面

req: 是request的缩写中文对应的是请求 就是浏览器页面发给服务器的请求

所以要想给前端发数据就要用到resp

转json格式以数据传给前端使用

@WebServlet("/DeptC")
public class DeptC extends HttpServlet {
    //引入服务层
    private IDeptService deptService=new DeptServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取数据库里的Dept表格数据
        List<Dept> list = deptService.list();  //这是我自己已经写好的从数据库中获取数据的方法
        JsonUtil.transJson(list,resp);
    }
}

工具类 JsonUtil

    public static void transJson(Object obj, HttpServletResponse resp){
        try {
            //数据转成json格式
            String josn_string = JSON.toJSONString(obj,SerializerFeature.WriteNullListAsEmpty);
            System.out.println("JsonUtil.java:"+obj);
            System.out.println("JsonUtil.java:"+josn_string);
            //设置文字编码
            resp.setContentType("application/json;charset=utf-8");
            //响应给浏览器
            resp.getWriter().write(josn_string);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

这里使用了阿里巴巴的fastjson jar包

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

1689210429064.png

前端使用 axios.js 和 vue.js 进行数据展示

Script代码

new Vue({
  el:'#app',
  data:{
      yy:{}
  },
  mounted:function (){
    axios.get("http://localhost:8081/DeptC").then((list)=>{
        this.yy = list.data; //把数据给到Vue对象里的data
    })
  }
})

heml代码

<div id="app"> <!--   跟vue绑定   -->
  <table>
    <tr>
      <th>did</th>
      <th>dname</th>
      <th>dlocation</th>
      <th>leader</th>
    </tr>
    <tr v-for="dept in yy">
        <td>{{dept.did}}</td>  
        <td>{{dept.dname}}</td>
        <td>{{dept.dlocation}}</td>
        <td>{{dept.leader}}</td>
    </tr>
  </table>
</div>

给前端传图片

工具类ImgUtil

public class ImgUtil {
    public static void responseImg(String imgPath, HttpServletResponse resp){
        try {
            //1 先把图片读进来
            FileInputStream is = new FileInputStream(imgPath);
            //输出方式 = resp = 输出到页面
            ServletOutputStream os = resp.getOutputStream();
            //构建缓冲流,提高读写效率
            BufferedInputStream bis = new BufferedInputStream(is);
            //用bos输出到页面上
            BufferedOutputStream bos = new BufferedOutputStream(os);
            //设定 每次读 1000个字节
            byte[] bytes = new byte[1000];
            //2 循环,边读边写
            //会把bis读到bytes每次读一千个字节 每次读取回覆盖之前读的
            while ((bis.read(bytes))!=-1){
                bos.write(bytes);
            }
            //关闭资源
            bos.flush();
            bos.close();
            bis.close();
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

控制层

@WebServlet("/imgC")
public class ImgC extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ImgUtil.responseImg("E:\\Adobe\\Blb\\STUDY\\05.js+学习\\img\\a.webp",resp);
    }
}

equest req, HttpServletResponse resp) throws ServletException, IOException {
ImgUtil.responseImg(“E:\Adobe\Blb\STUDY\05.js+学习\img\a.webp”,resp);
}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值