前后端分离实现
前后端分离的好处就不用多说了,前后端那么Java Web项目前后端分离是怎么实现的呢?
1.浏览器发送请求
2.直接到达html页面(前端控制路由与渲染页面,整个项目开发的权重前移)
3.html页面负责调用服务端接口产生数据(通过ajax等等,后台返回json格式数据,json数据格式因为简洁高效而取代xml)
4.填充html,展现动态效果,在页面上进行解析并操作DOM。
它的核心思想是前端html页面通过ajax调用后端的restuful api接口并使用json数据进行交互。如果后端采用了Spring MVC框架的话,那么只需要·加一个@ResponseBody注解就可以返回json对象,一个@RequestBody就可以接收前台json数据,这就是框架的好处吧,可以省很多工夫,但是现在先不用,用最基本的Servlet来接收和返回json数据。
JQuery对ajax的支持
JQuery也有对AJAX的支持,使得其对AJAX的操作简化了很多,这样就不用用原生js了。
关键字 | 简介 |
$.ajax | 提交AJAX请求 |
$.get | 使用get方式提交ajax |
$.post | 使用post方式提交ajax |
load | 最简单的调用ajax的方式 |
serialize | 格式化form下的输入数据 |
前后端交互
建一个实体类
package edu.hpu.Pojo; public class Role { private String name; private String film; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFilm() { return film; } public void setFilm(String film) { this.film = film; } @Override public String toString() { return "Role [name=" + name + ", film=" + film + "]"; } }
我们的前后端数据就主要围绕这个实体类展开了。
导入相应的包和jquery.min.js
解析json数据好像用Jackson的比较多(可以参考【3】),但这个用的不是,具体用的包直接参考【2】。
提交数据
submit.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>提交数据</title> <script type="text/javascript" src="jquery.min.js"></script> </head> <body> <form> <p>影视角色</p> 姓名:<input type="text" id="name"><br> 电影:<input type="text" id="film"><br> <input type="button" value="提交" id="sender"> </form> <div id="message"></div> <script type="text/javascript"> $('#sender').click(function () { //点击按钮触发 var name=document.getElementById("name").value; var film=document.getElementById("film").value; var role={"name":name,"film":film}; //新建一个json对象 var url="submitServlet"; $.post( url, {"data":JSON.stringify(role)}, function(data) { alert("提交成功,请在Tomcat控制台查看服务端接收到的数据"); }); }); </script> </body> </html>
SubmitServlet:
package edu.hpu.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.hpu.Pojo.Role; import net.sf.json.JSONObject; /** * Servlet implementation class SubmitServlet */ public class SubmitServlet extends HttpServlet { private static final long serialVersionUID = 1L; public SubmitServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data=request.getParameter("data"); //获取前端传递数据 System.out.println("服务端接收到的数据是:" +data); JSONObject json=JSONObject.fromObject(data); System.out.println("转换为JSON对象之后是:"+ json); Role role = (Role)JSONObject.toBean(json,Role.class); System.out.println("转换为Hero对象之后是:"+role); } }
web.xml配置:
<servlet> <servlet-name>SubmitServlet</servlet-name> <servlet-class>edu.hpu.servlet.SubmitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SubmitServlet</servlet-name> <url-pattern>/submitServlet</url-pattern> </servlet-mapping>
跑一下,结果:
前端获取一个对象
GetOneServlet:
package edu.hpu.servlet; import edu.hpu.pojo.Role; import net.sf.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class GetOneServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Role role=new Role(); role.setName("柳飘飘"); role.setFilm("喜剧之王"); JSONObject json= new JSONObject(); json.put("role", JSONObject.fromObject(role)); response.setContentType("text/html;charset=utf-8"); response.getWriter().print(json); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
web.xml配置:
<servlet> <servlet-name>GetOneServlet</servlet-name> <servlet-class>edu.hpu.servlet.GetOneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetOneServlet</servlet-name> <url-pattern>/getOneServlet</url-pattern> </servlet-mapping>
getOne.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>获取一个对象</title> <script type="text/javascript" src="jquery.min.js"></script> </head> <body> 影视角色:<br> <input type="submit" value="通过AJAX获取一个Role对象" id="sender"> <div id="message"></div> <script type="text/javascript"> $('#sender').click(function(){ var url="getOneServlet"; $.post( url, function(data) { var json=JSON.parse(data); var name =json.role.name; var film = json.role.film; $("#message").html("角色名字:"+name + "<br>电影:" +film ); }); }); </script> </body> </html>
跑一下,结果:
F12可以进入调试模式,查看前端发出的异步请求以及后端的响应:
前端获取多个对象
GetManyServlet:
package edu.hpu.servlet; import edu.hpu.pojo.Role; import net.sf.json.JSONSerializer; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet(name = "GetManyServlet") public class GetManyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Role> roles=new ArrayList<>(); for (int i=0;i<10;i++){ Role role=new Role(); role.setName("燕双鹰"+i); role.setFilm("宇宙第一豪杰、灭霸杀手"+i); roles.add(role); } String result= JSONSerializer.toJSON(roles).toString(); //通过通过JSONSerializer.toJSON(heros)把集合转换为JSON字符串 response.setContentType("text/html;charset=utf-8"); //设置编码 response.getWriter().print(result); //以流的形式传递给前端 } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
配置:
<servlet> <servlet-name>GetManyServlet</servlet-name> <servlet-class>edu.hpu.servlet.GetManyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetManyServlet</servlet-name> <url-pattern>/getManyServlet</url-pattern> </servlet-mapping>
getMany.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>获取多个对象</title> <script type="text/javascript" src="jquery.min.js"></script> </head> <body> <input type="button" value="通过AJAX获取多个Hero对象" id="sender"> <div id="messageDiv"></div> <script> $('#sender').click(function () { var url="getManyServlet"; $.post( url, function (data) { var roles=$.parseJSON(data); //把返回的数据转换为json数组 for(i in roles){ //循环json数组 var old = $("#messageDiv").html(); var role = roles[i]; $("#messageDiv").html(old + "<br>"+role.name+" ----- "+role.film); } } ); }); </script> </body> </html>
跑一下结果:
参考:
【1】、https://blog.csdn.net/piantoutongyang/article/details/65446892?tdsourcetag=s_pctim_aiomsg###
【2】、http://how2j.cn/k/jquery/jquery-ajax/474.html#step1002
【3】、https://blog.csdn.net/qq1940879801/article/details/77854906
【4】、http://how2j.cn/k/servlet/servlet-submit-json/1323.html#nowhere
【5】、http://how2j.cn/k/servlet/servlet-get-one-json/1324.html#nowhere
【6】、http://how2j.cn/k/servlet/servlet-get-many-json/1325.html