J2EE学习笔记 用JSON做前后端分离

思路是:

用html写好ajax内容,触发响应的时候把数据通过ajax传给对应servlet,servlet处理好再返回内容给浏览器。

效果:

html:

要注意嵌套的内容,单双引号问题,外层用单里面就用双,外层用双内层就用单。我看站长是特别注意了下的。

这里的ajax的第二部份是省略了的哈,因为没有需要传给servlet的数据。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>还是用JSON方式添加数据</title>
<script type="text/javascript" src="jquery.min.js"></script> 
</head>
<body>
	<input type="button" value="通过AJAX添加多个数据" id="sender">
	<div id="messageDiv"></div>
	<script type="text/javascript">
		$('#sender').click(function(){
			var url="getManyServlet";
			$.post(
				url,
				function(data){
					var heros=$.parseJSON(data);
					for(i in heros){
						var oid=$("#messageDiv").html();
						var hero = heros[i];
						$("#messageDiv").html(oid+"<br>"+hero.name+"  ----  "+hero.hp);
					}
				}
			);
		});
	</script>
	
</body>
</html>

servlet:

把集合转换成JSON,再转换成字符串,传给前端

import java.io.IOException;
import java.io.Writer;
 
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 



import net.sf.json.JSONObject; 
import net.sf.json.JSONSerializer;
public class GetManyServlet extends HttpServlet{
	protected void service(HttpServletRequest request,HttpServletResponse response)
	 throws ServletException,IOException{
		List<Hero> heros=new ArrayList<>();
		for(int i = 0;i <10;i ++)
		{
			Hero hero=new Hero();
			hero.setHp(500+i);
			hero.setName("name "+i);
			heros.add(hero);
		}
		
		String result=JSONSerializer.toJSON(heros).toString();
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().print(result);
	}
	public static void main(String[] args) {
        List<Hero> heros = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Hero hero = new Hero();
            hero.setName("name"+i);
            hero.setHp(500+i);
            heros.add(hero);
        }
         
        System.out.println(JSONSerializer.toJSON(heros).toString());
    }
}

学习网站:https://how2j.cn/p/4582

发布了82 篇原创文章 · 获赞 21 · 访问量 7946

猜你喜欢

转载自blog.csdn.net/qq_41658124/article/details/104411500
今日推荐