web前后台数据交互

xiaoxiao2021-02-28  58

1.利用cookie对象 

Cookie是服务器保存在客户端中的一小段数据信息。使用Cookie有一个前提,就是客户端浏览器允许使用Cookie并对此做出相应的设置。一般不赞成使用Cookie。

(1)后台代码

1 2 Cookie cookie= new Cookie( "name" , "hello" );  response.addCookie(cookie);

 

(2)前台代码

 

1 2 3 4 5 6 Cookie[] cookies=request.getCookies();  for ( int i= 0 ;i<cookies.length;i++){           if (cookies[i].getName().toString().equals( "name" )){               out.print(cookies[i].getValue());           }  }

2.利用session对象

session对象表示特定会话session的用户数据。客户第一次访问支持session的JSP网页,服务器会创建一个session对象记录客户的信息。当客户访问同一网站的不同网页时,仍处于同一个session中。

 

(1)后台代码

 

1 2 3 request.getSession().setAttribute( "name" , name);  request.getSession().setMaxInactiveInterval( 2 );  response.sendRedirect( "welcome.jsp" ); 

  

(2)前台代码(jsp页面)

1 Object user=request.getSession().getAttribute( "name" );

  

3.利用request重定向,设置setAttribute

 

(1)后台代码

 

1 2 request.setAttribute( "name" , "cute" );  request.getRequestDispatcher( "welcome.jsp" ).forward(request, response);  //网址不会改变

 

PS:如果后台使用的转发代码为 response.sendRedirect("welcome.jsp");  //网址变为welcome.jsp

则request设置的参数无效,因为已经切换到另一个请求了,request参数的有效期为本次请求。

(2)前台代码

 

1 String name=request.getAttribute( "name" ).toString(); 

 

4.利用Ajax进行异步数据请求(得到的数据可以以json或xml格式返回,便于处理)

(1)后台代码案例(运用servlet传输数据)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class TestServlet extends HttpServlet {           /**       * Constructor of the object.       */       public TestServlet() {           super ();       }           public void doGet(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {           doPost(request, response);       }           public void doPost(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {               response.setContentType( "text/html" );           PrintWriter out = response.getWriter();           String data= "[{\"name\":\"apple\",\"price\":23},{\"name\":\"banana\",\"price\":12},{\"name\":\"orange\",\"price\":8}]" ;           out.write(data);           out.flush();           out.close();       }           /**       * Initialization of the servlet. <br>       *       * @throws ServletException if an error occurs       */       public void init() throws ServletException {           // Put your code here       }      } 

  

2.前台js请求处理数据代码

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 function createXMLHttpRequest(){       var xmlrequest;       if (window.XMLHttpRequest){           xmlrequest= new XMLHttpRequest();       } else if (window.ActiveXObject){           try {               xmlrequest= new ActiveXObject( "Msxm12.XMLHTTP" );           } catch (e){               try {                   xmlrequest= new ActiveXObject( "Microsoft.XMLHTTP" );               } catch (e){                   xmlrequest= "" ;               }           }       }       return xmlrequest;  }  //获取数据的函数  function change(){       var xmlrequest=createXMLHttpRequest();       xmlrequest.open( "POST" , "TestServlet" , true );       xmlrequest.onreadystatechange=function(){           if (xmlrequest.readyState== 4 &&xmlrequest.status== 200 ){               var data=JSON.parse(xmlrequest.responseText);               var content= "<table border=1>" ;               for (var i= 0 ;i<data.length;i++){                   content+= "<tr>" ;                   for (o in data[i]){                       content+= "<td>" +data[i][o]+ "</td>" ;                   }                   content+= "</tr>" ;               }               content+= "</table>" ;               document.getElementById( "test" ).innerHTML=content;           }       };       xmlrequest.send();  } 

  

 

总结:在用户访问网站整个生命周期中都会用到的数据用session来存储,例如用户名,登录状态,购物车信息

           显示在网页上的信息数据大多通过 request或Ajax方式获取

====================================================================================================================================

ssm框架下,js页面通过json将数据发送到后台,后台处理之后,再将数据发送到前台。

在前台,要将用户名和邮箱发送到后台,先将用户名和和邮箱转成json形式的数据,在通过ajax发送到后台,其中url为后台要处理数据的地址。前台主要代码如下,其中User是一个实体类,有id,name,email,password等属性。

[html] view plain copy var user_json = {                        "user_name": user_name,                  "user_mail":user_mail              }         //js对象转换成JSON字符串              var jason_str = JSON.stringify(user_json);                    //Ajax发送数据给后台                  $.ajax({                      url :"/MyApplication/user/checkUserLogin",                       cache : true,                      type : "post",                      datatype : "json",                      contentType : "application/json; charset=utf-8",                      data : jason_str,                      success : function (data){                          //返回空值                          if(data==null){                              alert("不存在该用户!");                              window.location.href = "sighIn.html";                          } else{  //存在该用户                              if(password == data.user_password){  //密码正确                                  window.location.href = "index.html?user_name=" + data.user_name;                              }else{  //密码不正确                                  alert("密码错误!");                                  window.location.href = "sighIn.html";                              }                                                        }                      }                                        });  

后台只要代码如下(在controller层编写)

[html] view plain copy @RequestMapping(value = "/checkUserLogin")      public @ResponseBody User checkUserLogin(@RequestBody User user){          if (user.getUser_name() != null) {              user = userService.findByName(user.getUser_name());          } else if (user.getUser_mail() != null) {              user = userService.findByMail(user.getUser_mail());          }          return user;      }   @RequestBody是将json形式的数据转化成User类型的数据,@ResponseBody是将User类型的数据转成json发送到前端。

====================================================================================================================================

去年开始接触java web项目开发,在项目开发过程中难免会遇到前台jsp页面获得的数据传到后台controller层去处理,对于常用的三种方式进行了以下总结:

1.Form表单提交

jsp页面中可以嵌入form表单,主要有两个属性,action和method。action的内容是表单要提交到后台controller的某个请求。method是表单提交方式:主要有get和post两种提交方式,一般的表单提交数据会用到post方式,考虑到数据安全性问题。下面是我做的一个小例子,有用户名和密码两个字段

jsp页面form表单

后台处理请求代码:

后台请求方法

2.Ajax = Asynchronous JavaScript and XML

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行刷新。很常见的例子在某些网站注册过程中要求用户名不能重复,所以在避免数据已经提交到后台去数据库校验该用户是否存的的情况下,ajax可以实现异步刷新,在文本框失去焦点后就去访问后台数据库判断该用户是否已经存在。

jquery中的ajax

下面简单介绍下ajax请求里面的主要几个参数:

url:一般为String类型的参数,发送请求的地址。type:一般String类型的参数,请求方式主要用(post或get)默认为get。data:一般为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式dataType:预期服务器返回的数据类型success:要求为Function类型的参数,请求成功后调用的回调函数,一般有两个参数。

(1)由服务器返回,并根据dataType参数进行处理后的数据。

(2)描述状态的字符串。

function(data, textStatus){

//data可能是xmlDoc、jsonObj、html、text等等

}

error:请求失败时被调用的函数

3. a标签中src属性

常用的a便签中的src属性也可以发送请求到后台,后台有相应的处理方法即可。

a便签

后台处理方法

以上三种方式是我总结的工作中比较常用的几种方法,尤其是form表单提交数据。初次发稿还有许多不足的地方,欢迎大家继续补充和提出意见哈。

====================================================================================================================================

转载请注明原文地址: https://www.6miu.com/read-47463.html

最新回复(0)