解决axios.post 请求HttpServletRequest.getParameter获取不到值
工具类public class ServletRequestUtil {private static ObjectMapper om = new ObjectMapper();public static HashMap<String,Object> getJson(InputStream getInputStream) throws IOException {BufferedReade
·
工具类
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);
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)