工具类 

public class ServletRequestUtil {
    private static ObjectMapper om = new ObjectMapper();

    public static HashMap<String,Object> getJson(InputStream getInputStream) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(getInputStream));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //将空格和换行符替换掉避免使用反序列化工具解析对象时失败
        String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n","");
        //json转map<String,Object>
        HashMap<String,Object> mmap = om.readValue(jsonString, HashMap.class);
        return mmap;
    }
}

servlet类

将request的输入数据流传到工具类中返回一个map

public class DeleteService extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //添加学生
        /*设置编码*/
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        
        /*输入的学号*/
        //获取数据流中的内容,封装在了ServletRequestUtil中
        HashMap<String,Object> jsonData= ServletRequestUtil.getJson(req.getInputStream());
        int id = (Integer)jsonData.get("id");
        try {
            //删除学生
            StudentDao.delete(id);
            //返回提示信息
            resp.getWriter().write("删除成功");
        } catch (SQLException e) {
            e.printStackTrace();
            resp.getWriter().write("删除失败");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);

    }
}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐