原生servlet处理get和post请求

1.配置:web.xml--


        API
        com.servlet.api.Api


        API
        /api

2.建立类Api.java
2.1.继承HttpServlet
2.2.重写方法doGet\doPost,并向HttpServletResponse 写数据

public class Api extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //处理请求,回写数据
            outPutOutputStream(resp, data);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //处理请求,回写数据
            outPutOutputStream(resp, data);
    }
    private void outPutOutputStream(HttpServletResponse resp, String data) throws IOException {
        // 获取OutputStream输出流
        OutputStream outputStream = resp.getOutputStream();
        // 将字符转换成字节数组,指定以UTF-8编码进行转换
        byte[] dataByteArr = data.getBytes("UTF-8");
        // 使用OutputStream流向客户端输出字节数组
        outputStream.write(dataByteArr);
    }
}

你可能感兴趣的:(原生servlet处理get和post请求)