XMLHTTPRequest的理解 及 SpringMvc请求和响应xml数据

HTTP请求报文三个部分组成
  POST /search HTTP/1.1        //→请求行(request line)、
  Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint,
  application/msword, application/x-silverlight, application/x-shockwave-flash, */*
  Referer: <a href="http://www.google.cn/">http://www.google.cn/</a>
  Accept-Language: zh-cn
  Accept-Encoding: gzip, deflate     //↑↓请求头部(header)
  User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; TheWorld)
  Host: <a href="http://www.google.cn">www.google.cn</a>
  Connection: Keep-Alive
  Cookie: PREF=ID=80a06da87be9ae3c:U=f7167333e2c3b714:NW=1:TM=1261551909:LM=1261551917:S=ybYcq2wpfefs4V9g;
  NID=31=ojj8d-IygaEtSxLgaJmqSjVhCspkviJrB6omjamNrSm8lZhKy_yMfO2M4QMRKcH1g0iQv9u-2hfBW7bUFwVh7pGaRUb0RnHcJU37y-
  FxlRugatx63JLv7CWMD6UB_O_r

  hl=zh-CN&source=hp&q=domety      //→请求数据(参数)(request-body)
  //可以看到,POST方式请求行中不包含数据字符串,这些数据保存在”请求内容”部分

HTTP响应报文也由三个部分组成,分别是:状态行、消息报头、响应正文。
  下面给出一个HTTP响应报文例子
  HTTP/1.1 200 OK              //→status-line状态行
  Date: Sat, 31 Dec 2005 23:59:59 GMT
  Content-Type: text/html;charset=ISO-8859-1 //↑↓headers消息响应报头
  Content-Length: 122

  <html>                  //→response-body响应正文
    <head>
    <title>Wrox Homepage</title>
    </head>
    <body>
    <!-- body goes here -->
    </body>
  </html>
  常见状态代码、状态描述的说明如下。
  200 OK:客户端请求成功。
  400 Bad Request:客户端请求有语法错误,不能被服务器所理解。
  401 Unauthorized:请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用。
  403 Forbidden:服务器收到请求,但是拒绝提供服务。
  404 Not Found:请求资源不存在,举个例子:输入了错误的URL。
  500 Internal Server Error:服务器发生不可预期的错误。
  503 Server Unavailable:服务器当前不能处理客户端的请求,一段时间后可能恢复正常,举个例子:HTTP/1.1 200 OK(CRLF)。

ajax技术的核心是XMLHttpRequest对象

ajax通过原生的XMLHttpRequest对象发出HTTP请求,得到服务器返回的数据后,再进行处理
创建同步请求
  //message.xml格式数据
  <p>hello world</p>

  <button ></div>
  <script>
  btn.onclick = function(){
    //显示加载图片
    img.style.display = 'inline-block';
    //按钮属性禁用
    btn.setAttribute('disabled','');
    //创建xhr对象
    var xhr;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //异步接受响应
    xhr.onreadystatechange = function(){
      if(xhr.readyState == 4){
        if(xhr.status == 200){
        //隐藏加载图片
        img.style.display = 'none';
        //按钮属性禁用移除
        btn.removeAttribute('disabled');
        //实际操作
        result.innerHTML += xhr.responseText;
        }
      }
    }  
    //发送请求
    xhr.open('get','message.xml',true);
    // 设置期望的返回数据类型 'json' 'text' 'document' ...
    xhr.responseType = '';
    // 设置请求头 'Content-Type': 'application/json; charset=UTF-8'/'multipart/form-data'
    xhr.setRequestHeader('', '');
    //请求超时后触发
    xhr.ontimeout = function(){
      console.log('The request timed out.');
     }
    xhr.timeout = 1000;
    xhr.send();//请求参数
  }
</script>

springmvc controller中接收和返回XML数据
  @RequestMapping 位于org.springframework.web.bind.annotation(绑定注解)
  value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
  method: 指定请求的method类型, GET、POST、PUT、DELETE等;
  consumes(消费): 指定请求提交的内容类型(Content-Type),例如application/json,application/xml,text/html=String;
  produces(生产): 指定返回的内容类型,仅当request请求头headers中的(Accept类型)中包含该指定类型才返回;如:例如application/json,application/xml,text/html=String;
  params(参数): 指定request中必须包含某些参数值是,才让该方法处理。
  headers(请求头): 指定request中必须包含某些指定的header值,才能让该方法处理请求。

@Controller
public class XmlController {
  //请求的数据格式
  @PostMapping(value = "/sendxml",headers = {"content-type=application/xml"})
  public void sendxml(@RequestBody User user){
  logger.info(JSONObject.toJSONString(user));
  logger.info("接收xml数据成功");
  }


  //响应的数据格式
  @RequestMapping(value = "/xml", produces={"application/xml; charset=UTF-8"}, method = { RequestMethod.GET,
  RequestMethod.POST })
  @ResponseBody
  public String xml(HttpServletRequest request, HttpServletResponse response)throws Exception {
    String xmlData = "<person>"
            + "<name>tom</name>"
            + "<age>17</age>"
           + "</person>";
    return xmlData;
  }


  //设置 请求及响应的数据格式
  @RequestMapping(value = "/地址",consumes = "application/xml",produces ="application/xml",method = RequestMethod.POST)
  @ResponseBody
  public String initAuthentication(@RequestBody StudentPojo studentPojo ) {
    System.out.println(studentPojo.getId());
  }
}

HTTP请求报文三个部分组成
  POST /search HTTP/1.1        //→请求行(request line)、
  Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint,
  application/msword, application/x-silverlight, application/x-shockwave-flash, */*
  Referer: <a href="http://www.google.cn/">http://www.google.cn/</a>
  Accept-Language: zh-cn
  Accept-Encoding: gzip, deflate     //↑↓请求头部(header)
  User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; TheWorld)
  Host: <a href="http://www.google.cn">www.google.cn</a>
  Connection: Keep-Alive
  Cookie: PREF=ID=80a06da87be9ae3c:U=f7167333e2c3b714:NW=1:TM=1261551909:LM=1261551917:S=ybYcq2wpfefs4V9g;
  NID=31=ojj8d-IygaEtSxLgaJmqSjVhCspkviJrB6omjamNrSm8lZhKy_yMfO2M4QMRKcH1g0iQv9u-2hfBW7bUFwVh7pGaRUb0RnHcJU37y-
  FxlRugatx63JLv7CWMD6UB_O_r

  hl=zh-CN&source=hp&q=domety      //→请求数据(参数)(request-body)
  //可以看到,POST方式请求行中不包含数据字符串,这些数据保存在”请求内容”部分

HTTP响应报文也由三个部分组成,分别是:状态行、消息报头、响应正文。
  下面给出一个HTTP响应报文例子
  HTTP/1.1 200 OK              //→status-line状态行
  Date: Sat, 31 Dec 2005 23:59:59 GMT
  Content-Type: text/html;charset=ISO-8859-1 //↑↓headers消息响应报头
  Content-Length: 122

  <html>                  //→response-body响应正文
    <head>
    <title>Wrox Homepage</title>
    </head>
    <body>
    <!-- body goes here -->
    </body>
  </html>
  常见状态代码、状态描述的说明如下。
  200 OK:客户端请求成功。
  400 Bad Request:客户端请求有语法错误,不能被服务器所理解。
  401 Unauthorized:请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用。
  403 Forbidden:服务器收到请求,但是拒绝提供服务。
  404 Not Found:请求资源不存在,举个例子:输入了错误的URL。
  500 Internal Server Error:服务器发生不可预期的错误。
  503 Server Unavailable:服务器当前不能处理客户端的请求,一段时间后可能恢复正常,举个例子:HTTP/1.1 200 OK(CRLF)。

ajax技术的核心是XMLHttpRequest对象

ajax通过原生的XMLHttpRequest对象发出HTTP请求,得到服务器返回的数据后,再进行处理
创建同步请求
  //message.xml格式数据
  <p>hello world</p>

  <button >获取信息</button>
  <div ></div>
  <script>
  btn.onclick = function(){
    //创建xhr对象
    var xhr;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //发送请求
    xhr.open('get','/uploads/rs/26/ddzmgynp/message.xml',false);//默认true异步响应,
    xhr.send();//请求参数
    //同步接受响应
    if(xhr.readyState == 4){//4代表完成响应
      if(xhr.status == 200){
      //实际操作
      result.innerHTML += xhr.responseText;
      }
    }
  }
</script>
创建异步请求
  <button >获取信息</button>
  <div ></div>
  <script>
  btn.onclick = function(){
    //显示加载图片
    img.style.display = 'inline-block';
    //按钮属性禁用
    btn.setAttribute('disabled','');
    //创建xhr对象
    var xhr;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //异步接受响应
    xhr.onreadystatechange = function(){
      if(xhr.readyState == 4){
        if(xhr.status == 200){
        //隐藏加载图片
        img.style.display = 'none';
        //按钮属性禁用移除
        btn.removeAttribute('disabled');
        //实际操作
        result.innerHTML += xhr.responseText;
        }
      }
    }  
    //发送请求
    xhr.open('get','message.xml',true);
    // 设置期望的返回数据类型 'json' 'text' 'document' ...
    xhr.responseType = '';
    // 设置请求头 'Content-Type': 'application/json; charset=UTF-8'/'multipart/form-data'
    xhr.setRequestHeader('', '');
    //请求超时后触发
    xhr.ontimeout = function(){
      console.log('The request timed out.');
     }
    xhr.timeout = 1000;
    xhr.send();//请求参数
  }
</script>

springmvc controller中接收和返回XML数据
  @RequestMapping 位于org.springframework.web.bind.annotation(绑定注解)
  value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
  method: 指定请求的method类型, GET、POST、PUT、DELETE等;
  consumes(消费): 指定请求提交的内容类型(Content-Type),例如application/json,application/xml,text/html=String;
  produces(生产): 指定返回的内容类型,仅当request请求头headers中的(Accept类型)中包含该指定类型才返回;如:例如application/json,application/xml,text/html=String;
  params(参数): 指定request中必须包含某些参数值是,才让该方法处理。
  headers(请求头): 指定request中必须包含某些指定的header值,才能让该方法处理请求。

@Controller
public class XmlController {
  //请求的数据格式
  @PostMapping(value = "/sendxml",headers = {"content-type=application/xml"})
  public void sendxml(@RequestBody User user){
  logger.info(JSONObject.toJSONString(user));
  logger.info("接收xml数据成功");
  }


  //响应的数据格式
  @RequestMapping(value = "/xml", produces={"application/xml; charset=UTF-8"}, method = { RequestMethod.GET,
  RequestMethod.POST })
  @ResponseBody
  public String xml(HttpServletRequest request, HttpServletResponse response)throws Exception {
    String xmlData = "<person>"
            + "<name>tom</name>"
            + "<age>17</age>"
           + "</person>";
    return xmlData;
  }


  //设置 请求及响应的数据格式
  @RequestMapping(value = "/地址",consumes = "application/xml",produces ="application/xml",method = RequestMethod.POST)
  @ResponseBody
  public String initAuthentication(@RequestBody StudentPojo studentPojo ) {
    System.out.println(studentPojo.getId());
  }
}