XMLHttpRequest 发送json 格式的数据,servlet 接收

XMLHttpRequest 实现的浏览器的HTTP异步的请求,在前后端进行数据交互的时候,常常使用json的数据格式,在最为基础的servlet 中来进行接收前台传入的json格式的数据,并且进行处理,下面介绍XMLHttpRequest发送数据和servlet 接收数据

javascript 复制代码
        const xhr=new XMLHttpRequest();
         let params=new FormData();
         let username=document.getElementById("username").value;
         let password=document.getElementById("password").value;
         xhr.open("post","./LoginServlet",true)
         xhr.setRequestHeader("Content-Type", "application/json"); 
        let param={
            "username":username,
            "password":password        
        }
        
        xhr.send(JSON.stringify(param));
        xhr.onreadystatechange=function(){
             console.log(xhr.readyState)
             console.log(xhr.responseText)
         
         }
      

后台接收servlet代码:

java 复制代码
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		StringBuilder sb=new StringBuilder();
		BufferedReader reader=request.getReader();
		String line=null;
		while((line=reader.readLine())!=null) {
		    sb.append(line);
		}
		System.out.println(sb.toString());
	}

上面就是前后端对应的代码,希望对你有所帮助!

相关推荐
January12079 小时前
【AI方法笔记】2026-11-02:模型流式吐 JSON 时,前端会遇到四种崩法
前端·人工智能·笔记·json
瑞码空间1 天前
JSP与Servlet核心开发与CRUD实战笔记
java·笔记·servlet·jsp
Frag0ut1 天前
Notepad++ 零基础入门:从记事本到代码编辑器的平滑过渡(2026最新版)
python·编辑器·html·json·notepad++·markdown·记事本
xiaoye-duck2 天前
《C++ 工具库实战》C++ 解析利器 JsonCpp:从基础使用到封装简易 JSON 工具
c++·json·第三方库
javachen__2 天前
试试Jackson:把JSON拉平成普通属性
json
limanovember2 天前
yq:命令行下的 YAML 和 JSON 处理利器
其他·json
追星星の人3 天前
java web项目(eclipse软件)全流程备份
java·servlet
程序员大阳3 天前
副队长JavaScript教程(65)-详解JSON:轻量级数据交换格式
javascript·json·序列化·反序列化·stringify·parse
光影6274 天前
Unittest单元测试基础速记
测试工具·单元测试·json·测试覆盖率
ZLongTeng4 天前
EIDE的launch.json文件
json