后端——eclipse实现前端后端的交互(2)

1.新建前后端文件

新建HTML文件和后端交互Servlet文件。新建文件的地址也有所要求,Servlet文件要在JavaResources下的src中。HTML文件在WebContent下

2. 引入jqury文件

后端与前端的互传需要通过jQuery的ajax,所以要传入jQuery的包到eclipse中,传入位置与HTML文件一致,放在WebContent下(同样css文件或其他img等都可以放在该目录下)

3.前端内容

在前端界面书写jquery内容。ajax格式如下。

html 复制代码
<script src="js/jquery.js"></script>
<script>

    $.ajax({
    	url:"testServlet",
    	type:"get", //请求方式 get post
    	success:function(value){
    		console.log(value)
    	},
    	error:function(){
    		alert("出错啦")
    	},
    })
</script>

其中,**"url"**为所连接后端的文件名称。

"success"为请求成功时执行的代码 ,"error"为// 请求失败时执行的代码

"type"为不同的请求方式,get post传参形式不同,请求方式post需要传入data域(账户密码为例)

javascript 复制代码
data:{
            account:account,
            password:password
        }

只要能写地址的地方,都可以发起get请求 浏览器地址栏 a location.herf='' 查找,而post方式必须通过jquery +ajax实现 。

get请求通常用来查找, 而post请求用于增删改

4.后端内容

新建一个Servlet文件,我们会发现,Servlet中有两个函数doGet和doPost.分别用于接受不同请求方式。

doGet函数中一些简单的语法示例:(从本地数据库的tests表中返回name,num,date三类数据)

其中MysqlUtil是提前写好的方法包,当然方法也可以自己写。导入即可。

java 复制代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 //解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //设置后端给前端返回的数据为json格式(大量数据)
        response.setContentType("text/json;charset=utf-8");
		//接收参数
		 //查找
		String sql="SELECT * from tests";
		String[] colums= {"name","num","date"};
		String res=MysqlUtil.getJsonBySql(sql, colums);
		
		 //后端给前端返回数据
        response.getWriter().write(res);
	}

**doPost函数中一些简单的语法示例:**与doGet不同doPost需要接受前端的参数。

java 复制代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //设置后端给前端返回的数据为json格式(大量数据)
        response.setContentType("text/json;charset=utf-8");
		
        //接受前端的参数
		String account=request.getParameter("account");
		String password=request.getParameter("password");
		
		//执行sql语句(查找数据库里是否有目的账号)
		String sql="select count(*) FROM user WHERE account=\""+account+"\"";

		int num=MysqlUtil.add(sql);
	
		if(num>0) {
			res="{\"code\":1,\"message\":\"该账号存在\"}";
		}else {
			res="{\"code\":0,\"message\":\"该账号不存在\"}";
		}
		response.getWriter().write(res);
	}
相关推荐
kyriewen2 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_23334 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
倔强的石头_4 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
天蓝色的鱼鱼6 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
SelectDB6 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
泯泷7 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花7 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷7 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜7 小时前
Spring Boot 核心知识点总结
前端