赞
踩
目录
发送一个请求,回应请求,回应的内容会覆盖浏览器中的内容,这样会打断前端其他的正常操作。
不同步,可以使用js中提供的对象,向后发送请求,服务器响应的内容会被js对象接收,在js中接收到的内容,局部更新网页,就不会刷新页面。
Ajax:无刷新状态更新页面,并且实现异步提交,提升用户体验。利用浏览器提供的一个特殊的对象(XMLHttpRequest)异步地向服务器发送请求 。
前后端分离时存在的问题,跨域是指从一个域名的网页去请求另一个域名的资源,只要 协议,域名,端口有任何一个的不同,就被当作是跨域。
使用Ajax技术前后端交互,前端会默认进行阻止,不让前端接收其他后端的数据。
3.1解决方式:
后端解决:在响应头中设置说明,告知浏览器,此次的响应是可靠的。
创建一个过滤器解决跨域问题。
- package com.yyds.webback2.filter;
-
- import javax.servlet.*;
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
-
- @WebFilter(urlPatterns = "/*")
- public class CorsFilter implements Filter {
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
- throws IOException, ServletException {
- HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
- HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
- //允许携带Cookie时不能设置为* 否则前端报错
- httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("origin"));//允许所有请求跨域
- httpResponse.setHeader("Access-Control-Allow-Methods", "*");//允许跨域的请求方法GET, POST, HEAD 等
- httpResponse.setHeader("Access-Control-Allow-Headers", "*");//允许跨域的请求头
- httpResponse.setHeader("Access-Control-Allow-Credentials", "true");//是否携带cookie
-
- filterChain.doFilter(servletRequest, servletResponse);
- }
- }
配置解决跨域过滤器:
- <filter>
- <filter-name>csf</filter-name>
- <filter-class>com.yyds.webback2.filter.CorsFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>csf</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
前端基于Ajax异步交互(原生态):
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title></title>
- <script>
- function checkAccount(account){
- var httpobj = new XMLHttpRequest();
- httpobj.open("get","http://127.0.0.1:8080/webBack2/reg?account="+account,true);
- httpobj.send();
- httpobj.onreadystatechange=function(){
- //接收后端响应的数据
- // alert(httpobj.responseText);
- document.getElementById("aid").innerHTML = httpobj.responseText;
- }
- }
-
- </script>
- </head>
- <body>
- <form>
- 用户<input type="text" name="account" value="" onblur="checkAccount(this.value)"/><span id="aid"></span><br />
- 密码<input type="text" name="psd" value=""/><br />
- </form>
-
- </body>
- </html>
后端响应:
- package com.yyds.webback2.servlet;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.io.PrintWriter;
-
- public class RegServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- resp.setHeader("Content-Type","text/html;charset=utf-8");
- PrintWriter pt = resp.getWriter();
- String account = req.getParameter("account");
- if (account.equals("admin")){
- pt.write("账号已经存在");
- }else {
- pt.write("成功注册");
- }
- }
- }
效果:
官方下载axios.min.js,将包放入前端js文件夹中,然后在前端页面导入使用框架
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title></title>
- <script src="js/axios.min.js" type="text/javascript"></script>
- <script>
- function checkAccount(account){
- axios.get("http://127.0.0.1:8080/webBack2/reg?account="+account).then(function(resp){
- // console.log(resp.data);
- document.getElementById("aid").innerHTML = resp.data;
- })
- // axios.post("http://127.0.0.1:8080/webBack2/reg","account="+account+"&age=20").then(function(resp){
- // document.getElementById("aid").innerHTML = resp.data;
- // })
- }
-
- </script>
- </head>
- <body>
- <form method="post">
- 用户<input type="text" name="account" value="" onblur="checkAccount(this.value)"/><span id="aid"></span><br />
- 密码<input type="text" name="psd" value=""/><br />
- </form>
- </body>
- </html>
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
将数据封装到对象中响应到前端,首先向后端加载JSON包 :
json包中有ObjectMapper() 类:将封装的对象转为json形式,即转为字符串。
例如响应一个Student对象:
后端:使用doPost
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- resp.setHeader("Content-Type","text/html;charset=utf-8");
- PrintWriter pt = resp.getWriter();
- String num = req.getParameter("num");
- Student student = new Student(num,"张三","男","12345678910");
- ObjectMapper objectMapper = new ObjectMapper();
- String s = objectMapper.writeValueAsString(student);
- System.out.println(s);
- resp.getWriter().print(s);
- }
前端:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title></title>
- <script src="js/axios.min.js" type="text/javascript"></script>
- <script>
- function checkAccount(num){
- axios.post("http://127.0.0.1:8080/webBack2/reg","num="+num).then(function(resp){
- // document.getElementById("aid").innerHTML = resp.data;
- console.log(resp.data.num);
- console.log(resp.data.name);
- console.log(resp.data.gender);
- console.log(resp.data.phone);
-
- })
- }
- </script>
- </head>
- <body>
- <form method="post">
- 学号<input type="text" name="num" value="" onblur="checkAccount(this.value)"/><br />
- <!-- <span id="aid"></span><br /> -->
- </form>
- </body>
- </html>
前端接收到的数据:
ObjectMapper() 类将student对象转为了json形式,属于String 类,如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。