servlet+ajax+json实现前后端分离

目录

      • 1. 前后端分离的理解
        • 1.1 以一个简单的例子说明后端渲染的过程
        • 1.2 前后端分离
          • 1.2.1 Servlet产生json数据
          • 1.2.2 前端通过ajax获取json数据,并渲染到前端界面

1. 前后端分离的理解

1.1 以一个简单的例子说明后端渲染的过程

示例:提交表单信息,返回提交的信息

servlet+ajax+json实现前后端分离_第1张图片
点击提交后:注意看url已经发生变化
servlet+ajax+json实现前后端分离_第2张图片

以下是表单html代码

     <form action="HelloForm" method="POST" 
target="_blank" >
          姓名:<input type="text" name="name">br>
          手机号码:<input type="number" name="phoneNumber" >br>
          <input type="submit" value="提交" />
     form>

以下是HelloForm Servlet的处理代码:

     protected void doGet(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, 
IOException {

          response.setContentType("text/html;charset=UTF-8");
          PrintWriter out = response.getWriter();
          String title = "使用GET方法提交表单";
          //对于Post请求,Tomcat会使用request.setCharacterEncoding和response.setCharacterEncoding方法设置的编码格式进行处理。
          //默认的编码方式是ISO-8859-1
          //下面语句为了将ISO-8859-1编码字符串转为utf-8

          String name = new 
String(request.getParameter("name").getBytes("ISO-8859-1"),"utf-8");

          //String name = request.getParameter("name");

          

          out.println(" \n" +

                   "\n" + ""</span> <span class="token operator">+</span> title <span class="token operator">+</span> 
<span class="token string">"\n" +
                   "\n" +
                 "

" + "您的信息已提交!" + "

\n"
+ "
    \n" + "
  • 姓名::" + name + "\n" + "
  • 手机号码::" + request.getParameter("phoneNumber") + "\n" + "
\n"
+ ""); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }

点击之后的过程分为以下几步:
1.浏览器提交表单数据,为了方便观察,抓包看一下浏览器发送的数据:
在这里插入图片描述
可以发现浏览器发送了一个POST请求,URL是/TomcatTest/HelloForm, 查看具体发送的内容如下
servlet+ajax+json实现前后端分离_第3张图片

  1. HelloForm接收到表单信息后,构造一个html页面返回给浏览器
    servlet+ajax+json实现前后端分离_第4张图片

3.浏览器跳转到该页面并显示

以上过程就是所谓的后端渲染

1.2 前后端分离

还是上面这个例子,后端不仅负责产生数据,还负责渲染页面,后端要做的事也太多了八!
所谓前后端分离也就是后端只负责产生数据,前端拿到数据后自己去渲染。
由于我掌握的知识不够多,以后端产生json数据+前端用ajax获取,并用jquery渲染来说明。

1.2.1 Servlet产生json数据

定义一个实体类:

public class Student {

     private final int id;                           //学号

     private final String name;                      //姓名

     private final String sex;                       //性别

     private final int  age;                    //年龄

     private final int score;                   //排名

     

     

     public Student(StudentBuilder sb) {

          this.id = sb.getId();

          this.name = sb.getName();

          this.sex = sb.getSex();

          this.age = sb.getAge();

          this.score = sb.getScore();

     }

     public int getId() {

          return id;

     }

     

     public String getName() {

          return name;

     }

     

     public String getSex() {

          return sex;

     }

     

     public int getAge() {

          return age;

     }

     

     public int getScore() {

          return score;

     }

     public String toString() {

          return "Student Info: id:" + this.getId() 

              + " name:" + this.getName() //

              + " age:" + this.getAge() //

              + " sex:" + this.getSex() //

              + " score:" + this.getScore();

     }

Servlet查询数据库获取相应数据,生成一个Student对象,然后将对象序列化为json字符串的格式:
servlet+ajax+json实现前后端分离_第5张图片

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		int id = Integer.parseInt(request.getParameter("id"));
		dao = new StudentDAOImpl();
		Student stu = null;
		try {
		    stu = dao.findById(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String res = null;
		if(stu == null) {
			out.write("error");
			return ;
		}
		String json = JSON.toJSONString(stu);
		out.write(json);
	}
1.2.2 前端通过ajax获取json数据,并渲染到前端界面

html代码:


<form id="form2" method="post" action="##" onsubmit="return false">

       学号:<input type="text"  name="id" /> <input    type="button" value="查询"  onclick="searchById()" />
 form>   



<div id="display" >widthu>=80% >

                   <table id="table" >

                   <tr>

                        <th>姓名th>

                        <th>学号th>

                        <th>年龄th>

                        <th>性别th>

                        <th>分数th>

                   tr>

                   table>

                   <div id="error">div>

          div>


相应的js代码:

function searchById(){

          $.ajax({

              type:"post",

              dataType:"json",

              url:"/my-webapp/QueryById",

              data:$("#form2").serialize(),

              

              success:function(data){

                   $("#table tr:not(:first)").remove();

                   $("#table").append(

                             "" + data.name + 
"" +

                             "" + data.id + "" +

                             "" + data.age + "" 
+

                             "" + data.sex + "" 
+

                             "" + data.score + 
"" 

                   );

                   $('#error > div ').remove();

              },

              error:function(data){

                   $("#table tr:not(:first)").remove();

                   $("#error").append(

                             

                                  "<div 
class='empty_text'>"+

                                      "查询不到相关学生信息"+

                                  "
" ); } }); }

效果:
servlet+ajax+json实现前后端分离_第6张图片
根据id查询:
servlet+ajax+json实现前后端分离_第7张图片

你可能感兴趣的:(java,ee)