SpringMVC的底层原理  
  
在前面我们学习了SpringMVC的使用(67章博客开始),现在开始说明他的原理(实际上更多的细节只存在67章博客中,这篇博客只是讲一点深度,重复的东西尽量少说明点)   
 
 
 
 
< packaging> </ packaging> <?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > </ web-app>   < dependencies> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> </ dependencies>  < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> 
 
< servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> < load-on-startup> </ load-on-startup> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> < load-on-startup> </ load-on-startup> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> < url-pattern> </ url-pattern> </ servlet-mapping> package  com. controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. ui.  Model ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. servlet.  ModelAndView ; 
import  java. util.  Date ; 
@Controller 
@RequestMapping ( "/demo" ) 
public  class  DisController  { 
    @RequestMapping ( "handle01" ) 
    public  ModelAndView  handle01 ( )  { 
        Date  date =  new  Date ( ) ;  
        
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView; 
    } 
} 
    public  ModelAndView  handle01 ( ModelAndView  modelAndView)  { 
        Date  date =  new  Date ( ) ;  
        
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView;  
    } 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Title</title>
  </head>
  <body>
      <%-- ${ date },隔开也行(单纯不在单纯之间的空格是不算的) --%>
  跳转成功!服务器时间是:${date}    
  </body>
</html>
< beansxmlns = " http://www.springframework.org/schema/beans" xmlns: mvc= " http://www.springframework.org/schema/mvc" xmlns: context= " http://www.springframework.org/schema/context" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd" > < context: component-scanbase-package = " com.controller" /> < beanid = " viewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" > < propertyname = " prefix" value = " /WEB-INF/jsp/" > </ property> < propertyname = " suffix" value = " .jsp" > </ property> </ bean> < mvc: annotation-driven> </ mvc: annotation-driven> < mvc: default-servlet-handler/> < mvc: resourcesmapping = " /resources/**" location = " classpath:/" /> </ beans>  < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> </ servlet> 
 
String  ageStr =  request. getParameter ( "age" ) ; 
Integer  age =  Integer . parseInt ( ageStr) ; 
@RequestMapping ( "xxx" ) 
public  String  handle ( Integer  age)  {  
System . out. println ( age) ; 
} 
@RequestMapping ( "handle11" ) 
    public  String  handle11 ( ModelAndView  modelAndView)  { 
        Date  date =  new  Date ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        return  "success" ;  
    } 
    @RequestMapping ( "handle21" ) 
    public  String  handle21 ( )  { 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        return  "success" ;  
    } 
    @RequestMapping ( "handle31" ) 
    public  String  handle31 ( ModelMap  modelMap)  { 
        Date  date =  new  Date ( ) ; 
        modelMap. addAttribute ( "date" ,  date) ; 
        return  "success" ; 
    } 
@RequestMapping ( "handle41" ) 
    public  String  handle41 ( Model  model)  { 
        Date  date =  new  Date ( ) ; 
        model. addAttribute ( "date" ,  date) ; 
        return  "success" ; 
    } 
 @RequestMapping ( "handle51" ) 
    public  String  handle51 ( Map < String , Object > )  { 
        Date  date =  new  Date ( ) ; 
        map. put ( "date" ,  date) ; 
        return  "success" ; 
    } 
   
    < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> < scope> </ scope> </ dependency> package  com. controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. servlet.  ModelAndView ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  javax. servlet. http.  HttpSession ; 
import  java. util.  Date ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  TestController  { 
    @RequestMapping ( "a1" ) 
    public  ModelAndView  a1 ( HttpServletRequest  request,  HttpServletResponse  response,  HttpSession  session)  { 
        String  id =  request. getParameter ( "id" ) ; 
        System . out. println ( id) ; 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        System . out. println ( request) ; 
        System . out. println ( response) ; 
        System . out. println ( session) ; 
        return  modelAndView; 
    } 
} 
@RequestMapping ( "a2" ) 
    public  ModelAndView  a2 ( boolean  id)  { 
        System . out. println ( id) ; 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView; 
    } 
String  id =  "true" ; 
System . out. println ( id) ; 
id =  "\"true\"" ; 
System . out. println ( id) ; 
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--查询指定id为15的数据--%>
<a href="demo/handle/15">rest_get测试</a>
<%--进行添加,添加不需要指定什么--%>
<form method="post" action="demo/handle">
    <input type="text" name="username"/>
    <input type="submit" value="提交rest_post请求"/>
</form>
<%--更新,那么自然需要一个数据,也就是list(可以认为是姓名,如改成这个姓名,当然,后面还可以继续的补充),当然,有时候并不操作put,所以需要加上list才可,来防止后面请求的冲突,如后面的删除--%>
<form method="post" action="demo/handle/15/lisi">
    <input type="hidden" name="_method" value="put"/>
    <input type="submit" value="提交rest_put请求"/>
</form>
<%--删除指定的id的数据--%>
<form method="post" action="demo/handle/15">
    <input type="hidden" name="_method" value="delete"/>
    <input type="submit" value="提交rest_delete请求"/>
</form>
   
</body>
</html>
package  com. controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  PathVariable ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. bind. annotation.  RequestMethod ; 
import  org. springframework. web. servlet.  ModelAndView ; 
import  java. util.  Date ; 
@Controller 
@RequestMapping ( "/demo" ) 
public  class  DemoController  { 
    
    @RequestMapping ( value =  "/handle/{id}" ,  method =  { RequestMethod . GET } )  
    public  ModelAndView  handleGet ( @PathVariable ( "id" )  Integer  id)  { 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView; 
    } 
    
    @RequestMapping ( value =  "/handle" ,  method =  { RequestMethod . POST } ) 
    public  ModelAndView  handlePost ( String  username)  { 
        System . out. println ( username) ; 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView; 
    } 
    
    @RequestMapping ( value =  "/handle/{id}/{name}" ,  method =  { RequestMethod . PUT } )  
    public  ModelAndView  handlePut ( @PathVariable ( "id" )  Integer  id,  @PathVariable ( "name" )  String  username)  { 
        System . out. println ( id) ; 
        System . out. println ( username) ; 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView; 
    } 
    
    @RequestMapping ( value =  "/handle/{id}" ,  method =  { RequestMethod . DELETE } )  
    public  ModelAndView  handleDelete ( @PathVariable ( "id" )  Integer  id)  { 
        System . out. println ( id) ; 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        return  modelAndView; 
    } 
} 
 
    < filter> < filter-name> </ filter-name> < filter-class> </ filter-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> </ filter> < filter-mapping> < filter-name> </ filter-name> < url-pattern> </ url-pattern> </ filter-mapping> 
    < filter> < filter-name> </ filter-name> < filter-class> </ filter-class> </ filter> < filter-mapping> < filter-name> </ filter-name> < url-pattern> </ url-pattern> </ filter-mapping>  
    @ResponseBody 
    @RequestMapping ( value =  "/handle/{id}" ,  method =  { RequestMethod . DELETE } ) 
    public  String  handleDelete ( @PathVariable ( "id" )  Integer  id)  { 
        System . out. println ( id) ; 
        Date  date =  new  Date ( ) ; 
        ModelAndView  modelAndView =  new  ModelAndView ( ) ; 
        modelAndView. addObject ( "date" ,  date) ; 
        modelAndView. setViewName ( "success" ) ; 
        System . out. println ( 1 ) ; 
        return  "11" ; 
    } 
 
< packaging> </ packaging> < dependencies> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> </ dependencies> <?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> < load-on-startup> </ load-on-startup> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> </ web-app> < beansxmlns = " http://www.springframework.org/schema/beans" xmlns: mvc= " http://www.springframework.org/schema/mvc" xmlns: context= " http://www.springframework.org/schema/context" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd" > < context: component-scanbase-package = " com.test" /> < mvc: annotation-driven> </ mvc: annotation-driven> </ beans> package  com. test ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. bind. annotation.  ResponseBody ; 
@Controller 
public  class  JsonController  { 
    @ResponseBody 
    @RequestMapping ( "json" ) 
    public  String  json ( )  { 
        return  "1" ; 
    } 
} 
    < mvc: resourcesmapping = " /js/**" location = " /WEB-INF/js/" /> package  com. entity ; 
public  class  User  { 
    String  id; 
    String  username; 
    public  String  getId ( )  { 
        return  id; 
    } 
    public  void  setId ( String  id)  { 
        this . id =  id; 
    } 
    public  String  getUsername ( )  { 
        return  username; 
    } 
    public  void  setUsername ( String  username)  { 
        this . username =  username; 
    } 
    
    @Override 
    public  String  toString ( )  { 
        return  "User{"  + 
                "id='"  +  id +  '\''  + 
                ", username='"  +  username +  '\''  + 
                '}' ; 
    } 
} 
 @ResponseBody 
    @RequestMapping ( "ajax" ) 
    public  List < User > ajax ( @RequestBody  List < User > ) { 
        System . out. println ( list) ; 
        return  list; 
    } 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <!--这个路径可以选择远程的路径,百度上查一查就行了
比如:<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
-->
<script src="js/jquery-3.4.1.min.js"></script>
<button id="btn">ajax提交</button>
<script>
    $("#btn").click(function(){
        let url = 'ajax';
        let data = '[{"id":1,"username":"张三"},{"id":2,"username":"李四"}]'
        $.ajax({
            type:'POST',//大小写可以忽略
            url:url,
            data:data,
            contentType:'application/json;charset=utf-8', //如这里
            success:function (data) {
                console.log(data);
            }
        })
    })
</script>
</body>
</html>
< packaging> </ packaging> < dependencies> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> </ dependencies> 
 
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  java. io.  IOException ; 
import  java. io.  PrintWriter ; 
public  class  GetRequest  implements  Servlet  { 
    
    
    
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    
    
    
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        System . out. println ( 1 ) ; 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
    
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
<?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> </ web-app> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
1
</body>
</html>
<input type="button" οnclick="run1()" value="原生js实现Ajax的get请求"><br>
<script>
    function run1(){
        let x;
        //判断浏览器类型,并创建核心对象
        if(window.XMLHttpRequest){
            x =new XMLHttpRequest();
        }else{
            x = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //建立连接get方式,资源路径,是否异步
        //GET大小写忽略
        x.open("GET","get",false); //关于请求路径是否加上/,可以选择参照67章博客中对/的说明(可以全局搜索"如action或者超链接(或者类似的)等等,不使用时,一般就是相",action与这里是一样的,或者说类似的),这里是不加上/的
        //提交请求,这里可以选择修改上面open的值,再来访问
        x.send();
        //等待响应,获取上面指定地址的响应结果
        x.onreadystatechange=function ()
        {
            //判断提交状态和响应状态码是否都ok
            //请求已完成,且响应已就绪,200响应状态完成
            if(x.readyState == 4 && x.status == 200){
                console.log("第一个")
                //将响应的信息进行赋值
                let text =x.responseText;
                console.log(text)
            }
        }
        console.log("下一个")
        x.open("geT","get?username=tom",false);
        x.send();
        x.onreadystatechange=function ()
        {
            if(x.readyState == 4 && x.status == 200){
                console.log("第二个")
                let text =x.responseText;
                console.log(text)
            }
        }
    }
</script>
function  run1 ( ) { 
        let  x; 
        
        if ( window. XMLHttpRequest) { 
            x = new  XMLHttpRequest ( ) ; 
        } else { 
            x =  new  ActiveXObject ( "Microsoft.XMLHTTP" ) ; 
        } 
        
        
        x. open ( "GET" , "get" , false ) ; 
        
        x. send ( ) ; 
        let  text = x. responseText; 
        console. log ( text) 
    } 
1 :x. open ( "GET" , "get?" , false ) ; 
2 :x. open ( "GET" , "get??" , false ) ; 
3 :x. open ( "GET" , "get?&" , false ) ; 
4 :x. open ( "GET" , "get?&=" , false ) ; 
5 :x. open ( "GET" , "get?=" , false ) ; 
6 :x. open ( "GET" , "get? =1" , false ) ; 
7 :x. open ( "GET" , "get?= " , false ) ; 
8 :x. open ( "GET" , "get?=&" , false ) ; 
9 :x. open ( "GET" , "get?name" , false ) ; 
10 :x. open ( "GET" , "get?name=" , false ) ; 
11 :x. open ( "GET" , "get?name= " , false ) ; 
12 :x. open ( "GET" , "get?name&" , false ) ; 
13 :x. open ( "GET" , "get?name&&" , false ) ; 
14 :x. open ( "GET" , "get?name=1" , false ) ; 
15 :x. open ( "GET" , "get?name=1?" , false ) ; 
16 :x. open ( "GET" , "get?name=1&" , false ) ; 
17 :x. open ( "GET" , "get?name=1&pass" , false ) ; 
18 :x. open ( "GET" , "get?name=1&&pass" , false ) ; 
19 :x. open ( "GET" , "get?nae=1&&pass" , false ) ; 
20 :x. open ( "GET" , "get&" , false ) ; 
21 :x. open ( "GET" , "get&name&" , false ) ; 
22 :x. open ( "GET" , "get?name=1&name=2" , false ) ; 
 @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        String  name =  servletRequest. getParameter ( "name" ) ; 
        String  pass =  servletRequest. getParameter ( "pass" ) ; 
        String  p =  servletRequest. getParameter ( "?" ) ; 
        String  a =  servletRequest. getParameter ( "&" ) ; 
        String  b =  servletRequest. getParameter ( "" ) ; 
        String  c =  servletRequest. getParameter ( " " ) ; 
        System . out. println ( name +  ","  +  pass +  ","  +  p +  ","  +  a +  ","  +  b +  ","  +  c) ; 
        System . out. println ( 1 ) ; 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
<form action="get" method="get">
    <input type="text" name="name">
    <input type="text" name="pass">
    <input type="submit" value="提交">
</form>
<!--
输入:1,2:get?name=1&pass=12
输入:1,不输入:get?name=1&pass=
输入:不输入,不输入:get?name=&pass=
很明显去掉自然也就不存在了
都去掉:get?,即get?是基础
-->
x. setRequestHeader ( "Content-Type" ,  "application/json" ) ;  
<input type="file" id="fileInput" />
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files[0]; // 获取文件选择框中的文件
        sendFileUsingGET(file); // 调用发送文件的函数
    }
    function sendFileUsingGET(file) {
        let xhr = new XMLHttpRequest();
        //原生中需要这个对象,或者说他也是相对原生的(因为你也会看XMLHttpRequest对象里面的源码的,这些源码相当于操作系统的接口一样,是提供的)
        //所以说,一般情况下,原生的意思代表是整个语言操作编写时自带的一些API或者固定语法意思,否则就应该说成是底层原理(考虑操作系统接口的处理,这不是单纯程序员所要理解和操作的东西了),原生也会称为底层源码
        let formData = new FormData();
        // 将文件添加到FormData,相当于表单操作的name和对应的值了
        formData.append('file', file);
        // 构建GET请求URL,将FormData中的数据作为查询参数
        let url = 'get?' + new URLSearchParams(formData).toString();
        console.log(new URLSearchParams(formData).toString()) //一般是这样的形式:file=%5Bobject+File%5D
        // 打开并发送GET请求
        xhr.open('GET', url, false);
        xhr.send();
        //后面的就不操作打印了,因为只是打印返回值而已,没有必要
    }
</script>
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  java. io.  IOException ; 
import  java. io.  PrintWriter ; 
public  class  GetRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        System . out. println ( 1 ) ; 
        System . out. println ( servletRequest) ;  
        
        
        
        
        
        
        
        
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        System . out. println ( h. getMethod ( ) ) ;  
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
function  sendFileUsingGET ( file )  { 
        let  xhr =  new  XMLHttpRequest ( ) ; 
        let  formData =  new  FormData ( ) ; 
        
        formData. append ( 'file' ,  file) ; 
        xhr. open ( 'GET' ,  "get" ,  false ) ; 
        xhr. send ( formData) ;  
    } 
@Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
        } 
        try  { 
            
            
            Part  filePart =  h. getPart ( "file" ) ;  
            String  fileName =  filePart. getSubmittedFileName ( ) ;  
            System . out. println ( "文件名:"  +  fileName) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
            System . out. println ( 2 ) ; 
        } 
        System . out. println ( 1 ) ; 
    } 
<input type="file" id="fileInput"/>
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        //前面没有说明这些,是因为他们是不会成功的,其实这个代表得到文件对应的信息,由于存在文件和多文件,所以下面才会存在数组的形式的
        let fileInput = document.getElementById('fileInput');
        console.log(fileInput)
        let file = fileInput.files[0]; // 获取文件选择框中的文件,由于只是单文件,所以只需要拿取下标为0的值即可,因为也只会是下标为0开始,因为只有一个
        console.log(file)
        //读取文件内容并进行 Base64 编码(注意是文件,也就是包括图片或者视频都可以),即将文件信息从二进制进行该编码处理,该编码对文件的操作使用的比较多,所以这里使用这个编码,也就是说,虽然我们不能使用get的multipart/form-data编码方式,但是我们可以直接来解决这个特殊字符的问题,如&,因为后端之所以默认判断报错,无非就是防止这种问题,即不能让你单纯的操作文件,但是他的判断一直存在,所以我们需要进行跳过,即按照其他方式的数据进行传递,也就只能将文件信息放在url中了,所以通过上面的说,也就是为什么get也只能将数据放在url的原因,根本原因还是get只能操作url,是否感觉上面的测试是多余的,但是也不要忘记了,前面也说了"以及如果不这样做会出现什么"这种情况,所以我也应该进行测试出来
        //一般使用该编码的他的好处可以降低数据大小的存在,那么变量就不会占用很多内存了,否则可能使用默认的变量给变量会造成比较大的内存占用(文件中的处理是操作系统的处理,而编码只是一种表现形式的指向而已)
        //创建了一个新的 FileReader 对象,用于读取文件内容,FileReader 是一个可以异步读取文件的 API(即你可以执行其他的任务,并且他是原生中js读取文件的操作,即也是原生的,我可没有引入一些js,要知道原生js的api可是有很多的,他们一般也是使用这些原生js组成的而已,比如vue)
        let reader = new FileReader();
        //设置了 FileReader 的 onload 事件处理函数,当文件读取完成时,该函数将会被触发
        reader.onload = function (e) {
            /*你可以将该e的数据复制下来(操作打印即可,即console.log(e);),然后记得两边没有分号",然后在url中粘贴,若出现你上传的图片,代表是真的获取了,他就是编码后的数据*/
            let fileData = e.target.result.split(',')[1]; // 获取Base64编码后的内容,因为这个时候他才算是真正的编码后面的数据,而前面的前缀只是一个标识而已,而非数据,所以通常并不影响后端的解码处理
            sendFileUsingGET(fileData); // 调用发送文件的函数
        };
        //开始读取指定的文件内容,并以 Base64 编码的形式返回结果,首先判断是否传递了文件
        if (file != undefined) {
            reader.readAsDataURL(file); //对应的异步出现一般体现于这里,并且他内部操作了编码,然后变成上面的e参数,同样的reader.onload 也是异步的处理,可以说reader基本都是异步的处理这是保证再处理多个文件时不会浪费很多时间,这也是没有办法的事情
        }
    }
    function sendFileUsingGET(fileData) {
        let xhr = new XMLHttpRequest();
        // 添加文件信息到 URL 中,这里之所以需要encodeURIComponent方法,是因为与默认的后端需要对应的编码一样,防止对应一些字符的处理,如&等等,由于get必然会在url中进行操作,那么如果不这样处理的话,可能会造成数据丢失
        let url = "get?file=" + encodeURIComponent(fileData);
        console.log(encodeURIComponent(fileData))
        // 打开并发送 GET 请求
        xhr.open('GET', url, false);
        xhr.send();
    }
</script>
@Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
        } 
        String  file =  servletRequest. getParameter ( "file" ) ; 
        if  ( file !=  null )  { 
            
            
            
            
            byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file) ;  
            
            
            
            FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/in.jpg" ) ; 
            fileWriter. write ( decodedBytes) ; 
        }  else  { 
        } 
    } 
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  java. io.  * ; 
import  java. util.  Base64 ; 
public  class  GetRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
            getFile ( h,  servletRequest,  servletResponse) ; 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
        } 
    } 
    private  static  void  getFile ( HttpServletRequest  h,  ServletRequest  servletRequest,  ServletResponse  servletResponse)  { 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        try  { 
            PrintWriter  writer =  servletResponse. getWriter ( ) ; 
            String  file =  servletRequest. getParameter ( "file" ) ; 
            String  filename =  servletRequest. getParameter ( "filename" ) ; 
            if  ( file !=  null )  { 
                String [ ]  split =  filename. split ( "\\." ) ; 
                byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file) ; 
                FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/in."  +  split[ 1 ] ) ; 
                fileWriter. write ( decodedBytes) ; 
                writer. write ( "<h1>"  +  "上传文件成功"  +  "</h1>" ) ; 
                return ;  
            } 
            writer. write ( "<h1>"  +  "上传的文件为空"  +  "</h1>" ) ; 
            return ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput"/>
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files[0];
        let reader = new FileReader();
        reader.onload = function (e) {
            console.log(e);
            let fileData = e.target.result.split(',')[1];
            sendFileUsingGET(fileData, file.name);
        };
        if (file != undefined) {
            reader.readAsDataURL(file);
        }
    }
    function sendFileUsingGET(fileData, name) {
        let xhr = new XMLHttpRequest();
        let url = "file?file=" + encodeURIComponent(fileData) + "&filename=" + name;
        xhr.open('GET', url, false);
        xhr.send();
        console.log(xhr.responseText);
    }
</script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> </ web-app> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<button id="openFileButton">打开文件选择器</button>
<script>
    let openFileButton = document.getElementById('openFileButton');
    openFileButton.addEventListener('click', () => {
        let fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.click();
        fileInput.addEventListener('change', (event) => {
            let file = event.target.files[0];
            let reader = new FileReader();
            reader.onload = function (e) {
                console.log(e);
                let fileData = e.target.result.split(',')[1];
                sendFileUsingGET(fileData, file.name);
            };
            if (file != undefined) {
                reader.readAsDataURL(file);
            }
        });
    });
    function sendFileUsingGET(fileData, name) {
        let xhr = new XMLHttpRequest();
        let url = "file?file=" + encodeURIComponent(fileData) + "&filename=" + name;
        xhr.open('GET', url, false);
        xhr.send();
        console.log(xhr.responseText);
    }
</script>
</body>
</html>
   function  fetchUserData ( )  { 
      console. log ( 9 ) 
      return  new  Promise ( ( resolve,  reject )  =>  { 
        setTimeout ( ( )  =>  { 
          console. log ( 1 ) 
          resolve ( 5 ) ; 
        } ,  1000 ) ; 
      } ) ; 
    } 
    async  function  getUserInfo ( )  { 
      console. log ( 4 ) 
      let  userData =  await  fetchUserData ( ) ; 
      console. log ( userData) 
    } 
    console. log ( 2 ) 
    getUserInfo ( ) ; 
    console. log ( 3 ) 
    
function  fetchUserData ( )  { 
      let  currentTimeStamp =  Date. now ( ) ; 
      console. log ( 9 ) 
      return  new  Promise ( ( resolve,  reject )  =>  { 
        console. log ( 1 ) 
        resolve ( 5 ) ; 
      } ) ; 
    } 
    async  function  getUserInfo ( )  { 
      console. log ( 4 ) 
      let  userData =  await  fetchUserData ( ) ; 
      console. log ( userData) 
    } 
    console. log ( 2 ) 
    getUserInfo ( ) ; 
    console. log ( 3 ) 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput" multiple/> 
    <!--multiple可以选择多个文件,而也有webkitdirectory,可以选择文件夹,都写上,那么可以选择文件夹和文件(并且可以多选,因为multiple),他们都是一个补充,当然补充之间也存在覆盖关系,多文件包含单文件,即覆盖掉,文件夹也是如此,也就是说,加上了webkitdirectory,那么只能操作文件夹了-->
<button οnclick="uploadFile()">上传</button>
<script>
    async function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let fileData = [];
        let fileDatename = [];
        if (fileInput.files.length === 0) {
            return;
        }
        let readFilePromises = [];
        for (let y = 0; y < fileInput.files.length; y++) {
            if (fileInput.files[y] != undefined) {
                let reader = new FileReader();
                let readFilePromise = new Promise((resolve, reject) => {
                    reader.onload = function (e) {
                        console.log(e);
                        fileData.push(e.target.result.split(',')[1]);
                        fileDatename.push(fileInput.files[y].name);
                        resolve(); // 标记异步操作完成
                    };
                    reader.readAsDataURL(fileInput.files[y]);
                });
                //保存Promise,准备一起处理
                readFilePromises.push(readFilePromise);
            }
        }
        // 等待所有异步操作完成,all方法必须先执行完毕才会考虑异步,所以后面的并不会进行处理,在前面我们也说明了哦,必须等方法执行完毕去了
        //而all就是处理所有的Promise的结果后,才会进行完毕,并且是按照添加顺序的,这样就使得我们可以得到正常数据的结果
        //且由于Promise的特性,必须是resolve()才会进行结束,且保证了顺序,所以无论你是否异步,最终的结果都会正确,因为只需要给最后的处理进行resolve()即可
        await Promise.all(readFilePromises);
        //完成后进行处理
        sendFileUsingGET(fileData, fileDatename);
        /*
        上面的操作是否看起来进行了同步呢,实际上从上往下看的确是,但是从内部看只是一个被等待造成的同步而已
         */
    }
    function sendFileUsingGET(fileData, name) {
        console.log(fileData)
        console.log(name)
        //拿取了总共的数据现在我们来处理一下url
        let xhr = new XMLHttpRequest();
        let url = "file?";
        for (let h = 0; h < fileData.length; h++) {
            if (h == fileData.length - 1) {
                url += "file=" + encodeURIComponent(fileData[h]) + "&filename=" + name[h];
                continue;
            }
            url += "file=" + encodeURIComponent(fileData[h]) + "&filename=" + name[h] + "&";
        }
        console.log(url)
        xhr.open('GET', url, false);
        xhr.send();
        console.log(xhr.responseText);
    }
</script>
</body>
</html>
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  java. io.  * ; 
import  java. util.  Base64 ; 
public  class  GetRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
            getFile ( h,  servletRequest,  servletResponse) ; 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
        } 
    } 
    private  static  void  getFile ( HttpServletRequest  h,  ServletRequest  servletRequest,  ServletResponse  servletResponse)  { 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        try  { 
            PrintWriter  writer =  servletResponse. getWriter ( ) ; 
            String [ ]  file =  servletRequest. getParameterValues ( "file" ) ; 
            String [ ]  filename =  servletRequest. getParameterValues ( "filename" ) ; 
            if  ( file !=  null )  { 
                for  ( int  i =  0 ;  i <  file. length;  i++ )  { 
                    String [ ]  split =  filename[ i] . split ( "\\." ) ; 
                    byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file[ i] ) ; 
                    FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/"  +  split[ 0 ]  +  "."  +  split[ 1 ] ) ; 
                    fileWriter. write ( decodedBytes) ; 
                    writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
                } 
                return ; 
            } 
            writer. write ( "<h1>"  +  "上传的文件为空"  +  "</h1>" ) ; 
            return ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
 function sendFileUsingGET ( fileData,  name)  { 
        console. log ( fileData) 
        console. log ( name) 
        
        let xhr =  new  XMLHttpRequest ( ) ; 
        let url; 
        for  ( let h =  0 ;  h <  fileData. length;  h++ )  { 
            url =  "file?file="  +  encodeURIComponent ( fileData[ h] )  +  "&filename="  +  name[ h] ; 
            console. log ( url) 
            xhr. open ( 'GET' ,  url,  false ) ; 
            xhr. send ( ) ; 
            console. log ( xhr. responseText) ; 
        } 
    } 
<input type="file" id="fileInput" multiple webkitdirectory/>
<!--虽然是补充,但是补充之间也有覆盖,所以如果选择了文件夹的处理,那么你就只能选择文件夹了-->
<button οnclick="uploadFile()">上传</button>
< inputtype = " file" id = " fileInput" multiple  webkitdirectory /> <input type="button" οnclick="run1()" value="原生js实现Ajax的post请求"><br>
<script>
    function run1() {
        let x;
        if (window.XMLHttpRequest) {
            x = new XMLHttpRequest();
        } else {
            x = new ActiveXObject("Microsoft.XMLHTTP");
        }
        x.open("POST", "post?name=1&pass", false);
        x.send();
        let text = x.responseText;
        console.log(text)
    }
</script>
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  java. io.  IOException ; 
import  java. io.  PrintWriter ; 
public  class  PostRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        String  name =  servletRequest. getParameter ( "name" ) ; 
        String  pass =  servletRequest. getParameter ( "pass" ) ; 
        String  p =  servletRequest. getParameter ( "?" ) ; 
        String  a =  servletRequest. getParameter ( "&" ) ; 
        String  b =  servletRequest. getParameter ( "" ) ; 
        String  c =  servletRequest. getParameter ( " " ) ; 
        System . out. println ( name +  ","  +  pass +  ","  +  p +  ","  +  a +  ","  +  b +  ","  +  c) ; 
        System . out. println ( 1 ) ; 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
  < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> <input type="button" οnclick="run1()" value="原生js实现Ajax的post请求"><br>
<script>
    function run1() {
        let x;
        if (window.XMLHttpRequest) {
            x = new XMLHttpRequest();
        } else {
            x = new ActiveXObject("Microsoft.XMLHTTP");
        }
        x.open("POST", "post?ff=3", false);
        let body = {
            "name": 1,
            "pass": "",
        }
        console.log(body)
        console.log(JSON.stringify(body))
        x.send(JSON.stringify(body));
        let text = x.responseText;
        console.log(text)
    }
</script>
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  java. io.  IOException ; 
import  java. io.  PrintWriter ; 
public  class  PostRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        String  name =  servletRequest. getParameter ( "name" ) ; 
        String  pass =  servletRequest. getParameter ( "pass" ) ; 
        String  p =  servletRequest. getParameter ( "ff" ) ; 
        System . out. println ( name +  ","  +  pass +  ","  +  p) ;  
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
   x. open ( "POST" ,  "post?ff=3" ,  false ) ; 
        let  body =  { 
            "name" :  1 , 
            "pass" :  "" , 
        } 
        console. log ( body) 
        console. log ( JSON . stringify ( body) ) 
        x. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
        x. send ( JSON . stringify ( body) ) ; 
        let  text =  x. responseText; 
        console. log ( text) 
 x. open ( "POST" ,  "post?ff=3" ,  false ) ; 
        let  body =  { 
            "name" :  1 , 
            "pass" :  "" , 
        } 
        console. log ( body) 
        console. log ( JSON . stringify ( body) ) 
        x. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
        x. send ( body) ; 
        let  text =  x. responseText; 
        console. log ( text) 
x. open ( "POST" ,  "post?ff=3" ,  false ) ; 
        let  body =  { 
            "name" :  1 , 
            "pass" :  "" , 
        } 
        console. log ( body) 
        console. log ( JSON . stringify ( body) ) 
        x. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
        x. send ( "name=1&pass=" ) ; 
        let  text =  x. responseText; 
        console. log ( text) 
 x. open ( "POST" ,  "post" ,  false ) ;  
        let  body =  { 
            "ff" : "3" , 
            "name" :  1 , 
            "pass" :  "" , 
        } 
        console. log ( body) 
        console. log ( JSON . stringify ( body) ) 
        x. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
        x. send ( "name=1&pass=" ) ; 
        let  text =  x. responseText; 
        console. log ( text) 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput" multiple/>
<button οnclick="uploadFile()">上传</button>
<script>
    async function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let fileData = [];
        let fileDatename = [];
        if (fileInput.files.length === 0) {
            return;
        }
        let readFilePromises = [];
        for (let y = 0; y < fileInput.files.length; y++) {
            if (fileInput.files[y] != undefined) {
                let reader = new FileReader();
                let readFilePromise = new Promise((resolve, reject) => {
                    reader.onload = function (e) {
                        console.log(e);
                        fileData.push(e.target.result.split(',')[1]);
                        fileDatename.push(fileInput.files[y].name);
                        resolve();
                    };
                    reader.readAsDataURL(fileInput.files[y]);
                });
                readFilePromises.push(readFilePromise);
            }
        }
        await Promise.all(readFilePromises);
        sendFileUsingGET(fileData, fileDatename);
    }
    function sendFileUsingGET(fileData, name) {
        let xhr = new XMLHttpRequest();
        let url;
        for (let h = 0; h < fileData.length; h++) {
            url = "file?file=" + encodeURIComponent(fileData[h]) + "&filename=" + name[h];
            xhr.open('POST', url, false);
            xhr.send();
        }
    }
</script>
</body>
</html>
 < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> package  com. test. controller ; 
import  javax. servlet.  * ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  java. io.  FileOutputStream ; 
import  java. io.  IOException ; 
import  java. io.  PrintWriter ; 
import  java. util.  Base64 ; 
public  class  PostRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
            getFile ( h,  servletRequest,  servletResponse) ; 
        } 
    } 
    private  static  void  getFile ( HttpServletRequest  h,  ServletRequest  servletRequest,  ServletResponse  servletResponse)  { 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        try  { 
            PrintWriter  writer =  servletResponse. getWriter ( ) ; 
            String [ ]  file =  servletRequest. getParameterValues ( "file" ) ; 
            String [ ]  filename =  servletRequest. getParameterValues ( "filename" ) ; 
            if  ( file !=  null )  { 
                for  ( int  i =  0 ;  i <  file. length;  i++ )  { 
                    String [ ]  split =  filename[ i] . split ( "\\." ) ; 
                    byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file[ i] ) ; 
                    FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/"  +  split[ 0 ]  +  "."  +  split[ 1 ] ) ; 
                    fileWriter. write ( decodedBytes) ; 
                    writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
                } 
                return ; 
            } 
            writer. write ( "<h1>"  +  "上传的文件为空"  +  "</h1>" ) ; 
            return ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
< inputtype = " file" id = " fileInput" /> < buttononclick = " uploadFile ( ) " > </ button> < inputtype = " file" id = " fileInput" multiple /> < buttononclick = " uploadFile ( ) " > </ button> < inputtype = " file" id = " fileInput" webkitdirectory /> < buttononclick = " uploadFile ( ) " > </ button> if  ( file !=  null )  { 
                for  ( int  i =  0 ;  i <  file. length;  i++ )  { 
                    String [ ]  split =  filename[ i] . split ( "\\." ) ; 
                    byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file[ i] ) ; 
                    FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/"  +  split[ 0 ]  +  "."  +  split[ 1 ] ) ; 
                    fileWriter. write ( decodedBytes) ; 
                    writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
                    fileWriter. close ( ) ;  
                } 
                writer. close ( ) ;  
                return ; 
            } 
function  sendFileUsingGET ( fileData,  name )  { 
        let  xhr =  new  XMLHttpRequest ( ) ; 
        let  url; 
        for  ( let  h =  0 ;  h <  fileData. length;  h++ )  { 
            url =  "file?file="  +  encodeURIComponent ( fileData[ h] )  +  "&filename="  +  name[ h] ; 
            xhr. open ( 'GET' ,  url,  false ) ; 
            xhr. send ( ) ; 
        } 
    } 
< inputtype = " file" id = " fileInput" /> < buttononclick = " uploadFile ( ) " > </ button> java. lang.  IllegalArgumentException:  Request  header is too large
java. lang.  IllegalArgumentException:  Request  header is too large
function  sendFileUsingGET ( fileData,  name )  { 
        let  xhr =  new  XMLHttpRequest ( ) ; 
        let  url; 
        for  ( let  h =  0 ;  h <  fileData. length;  h++ )  { 
            url =  "file" ; 
            xhr. open ( 'POST' ,  url,  false ) ; 
            xhr. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
            xhr. send ( "file="  +  encodeURIComponent ( fileData[ h] )  +  "&filename="  +  name[ h] ) ; 
        } 
    } 
private  static  void  getFile ( HttpServletRequest  h,  ServletRequest  servletRequest,  ServletResponse  servletResponse)  { 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        try  { 
            
            h. setCharacterEncoding ( "utf-8" ) ; 
            PrintWriter  writer =  servletResponse. getWriter ( ) ; 
            String [ ]  file =  servletRequest. getParameterValues ( "file" ) ; 
            String [ ]  filename =  servletRequest. getParameterValues ( "filename" ) ; 
            if  ( file !=  null )  { 
                for  ( int  i =  0 ;  i <  file. length;  i++ )  { 
                    String [ ]  split =  filename[ i] . split ( "\\." ) ; 
                    byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file[ i] ) ; 
                    FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/"  +  split[ 0 ]  +  "."  +  split[ 1 ] ) ; 
                    fileWriter. write ( decodedBytes) ; 
                    writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
                    fileWriter. close ( ) ; 
                } 
                writer. close ( ) ; 
                return ; 
            } 
            writer. write ( "<h1>"  +  "上传的文件为空"  +  "</h1>" ) ; 
            return ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
< formaction = " file" method = " post" enctype = " multipart/form-data" > < inputtype = " file" name = " file" > < inputtype = " text" name = " filename" > < inputtype = " submit" value = " 文件上传" > </ form> <input type="file" id="fileInput"/>
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files[0];
        sendFileUsingGET(file);
    }
    function sendFileUsingGET(file) {
        let xhr = new XMLHttpRequest();
        let formData = new FormData();
        formData.append('file', file);
        xhr.open('POST', "get", false);
        xhr.send(formData);
    }
</script>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        let xhr = new XMLHttpRequest();
        xhr.open('get', "get?name=1", false);
        xhr.send();
    }
</script>
</body>
</html>
    < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping>  @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        String  name =  servletRequest. getParameter ( "name" ) ; 
        System . out. println ( name) ; 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
@Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  throws  ServletException ,  IOException  { 
        String  name =  servletRequest. getParameter ( "name" ) ; 
        System . out. println ( name) ; 
        
       
        BufferedReader  br =  servletRequest. getReader ( ) ; 
        BufferedWriter  bw =  new  BufferedWriter ( new  FileWriter ( "F:/in.txt" ) ) ; 
        String  str =  null ; 
        while  ( ( str =  br. readLine ( ) )  !=  null )  { 
            System . out. println ( str) ; 
            bw. write ( str) ; 
            bw. newLine ( ) ; 
        } 
        bw. close ( ) ; 
        br. close ( ) ; 
        servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
        PrintWriter  writer =  servletResponse. getWriter ( ) ; 
        writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
    } 
 function  uploadFile ( )  { 
        let  xhr =  new  XMLHttpRequest ( ) ; 
        let  formData =  new  FormData ( ) ; 
        formData. append ( 'name' ,  1 ) ; 
        xhr. open ( 'POST' ,  "get?name=1" ,  false ) ;  
        xhr. send ( formData) ; 
    } 
 
< % @ page contentType= "text/html;charset=UTF-8"  language= "java"  % > 
< html> < head> < title> Title < / title> 
< / head> 
< body> < input type= "file"  id= "fileInput" / > 
< button onclick= "uploadFile()" > 上传< / button> 
< script> uploadFile ( )  { 
        let fileInput =  document. getElementById ( 'fileInput') ; 
        let file =  fileInput. files[ 0 ] ; 
        sendFileUsingGET ( file) ; 
    } 
    function sendFileUsingGET ( file)  { 
        let xhr =  new  XMLHttpRequest ( ) ; 
        let formData =  new  FormData ( ) ; 
        formData. append ( 'file' ,  file) ; 
        formData. append ( 'name' ,  "22" ) ; 
        xhr. open ( 'POST' ,  "get" ,  false ) ; 
        xhr. send ( formData) ; 
    } 
< / script> 
< / body> 
< / html> 
 
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  java. io.  * ; 
import  java. nio. charset.  StandardCharsets ; 
import  java. util.  * ; 
public  class  GetRequest  implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  { 
        try  { 
            HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
            String  contentType =  h. getHeader ( "Content-Type" ) ; 
            String  boundary =  null ; 
            
            if  ( contentType !=  null  &&  contentType. startsWith ( "multipart/form-data" ) )  { 
                
                int  boundaryIndex =  contentType. indexOf ( "boundary=" ) ; 
                if  ( boundaryIndex !=  - 1 )  { 
                    
                    boundary =  contentType. substring ( boundaryIndex +  "boundary=" . length ( ) ) ; 
                } 
            } 
            
            if  ( boundary !=  null )  { 
                Map < Integer ,  Map < String ,  String > > =  new  HashMap < > ( ) ; 
                Map < String ,  String > =  null ; 
                
                
                
                ServletInputStream  inputStream =  servletRequest. getInputStream ( ) ; 
                FileOutputStream  fileWriter =  null ; 
                int  hh =  0 ; 
                int  re =  0 ; 
                byte [ ]  fd =  new  byte [ 1024 ] ; 
                int  hkl =  0 ; 
                int  u =  0 ; 
                int  bh =  0 ; 
                
                String  name =  "333.png" ; 
                int  ghk =  0 ; 
                int  count =  0 ; 
                int  jj =  4 ; 
                int  uh =  0 ; 
                
                while  ( ( re =  inputStream. read ( ) )  !=  - 1 )  { 
                    if  ( hkl >=  fd. length)  { 
                        byte [ ]  ll =  fd; 
                        fd =  new  byte [ fd. length *  2 ] ; 
                        for  ( int  g =  0 ;  g <  ll. length;  g++ )  { 
                            fd[ g]  =  ll[ g] ; 
                        } 
                    } 
                    fd[ hkl]  =  ( byte )  re; 
                    hkl++ ; 
                    
                    
                    if  ( ( char )  re ==  '\r'  ||  ( char )  re ==  '\n' )  { 
                        ghk++ ; 
                        if  ( count ==  1 )  { 
                            if  ( ghk >=  4 )  { 
                                if  ( ghk %  2  ==  0 )  { 
                                    uh++ ; 
                                } 
                                fd =  new  byte [ 1024 ] ; 
                                hkl =  0 ; 
                            } 
                        } 
                        if  ( count ==  0 )  { 
                            if  ( ghk ==  jj)  { 
                                count =  1 ; 
                                fd =  new  byte [ 1024 ] ; 
                                hkl =  0 ; 
                            } 
                        } 
                        if  ( ( char )  re ==  '\n'  &&  ghk ==  2 )  { 
                            if  ( u ==  0 )  { 
                                u++ ; 
                                byte [ ]  ii =  new  byte [ hkl] ; 
                                for  ( int  yun =  0 ;  yun <  hkl;  yun++ )  { 
                                    ii[ yun]  =  fd[ yun] ; 
                                } 
                                byte [ ]  iii =  new  byte [ ii. length -  2 ] ; 
                                for  ( int  b =  0 ;  b <  iii. length;  b++ )  { 
                                    iii[ b]  =  ii[ b] ; 
                                } 
                                
                                
                                String  str =  new  String ( iii,  "UTF-8" ) ; 
                                
                                str =  str. replace ( " " ,  "" ) ; 
                                byte [ ]  iij =  new  byte [ ii. length +  uh *  2 ] ; 
                                for  ( int  hkk =  uh *  2 ,  kl =  0 ;  hkk <  iij. length;  hkk++ )  { 
                                    iij[ hkk]  =  ii[ kl] ; 
                                    kl++ ; 
                                } 
                                int  q =  0 ; 
                                int  w =  1 ; 
                                for  ( int  gh =  0 ;  gh <  uh *  2 ;  gh++ )  { 
                                    if  ( q ==  0  &&  w ==  1 )  { 
                                        iij[ gh]  =  '\r' ; 
                                        w =  0 ; 
                                        q =  1 ; 
                                        continue ; 
                                    } 
                                    if  ( q ==  1  &&  w ==  0 )  { 
                                        iij[ gh]  =  '\n' ; 
                                        w =  1 ; 
                                        q =  0 ; 
                                    } 
                                } 
                                
                                if  ( str. equals ( "--"  +  boundary) )  { 
                                    if  ( uh >  0 )  { 
                                        byte [ ]  hj =  new  byte [ uh *  2 ] ; 
                                        int  ujg =  0 ; 
                                        for  ( int  i =  0 ;  i <  hj. length;  i++ )  { 
                                            if  ( ujg ==  0 )  { 
                                                hj[ i]  =  '\r' ; 
                                                ujg =  1 ; 
                                                continue ; 
                                            } 
                                            if  ( ujg ==  1 )  { 
                                                hj[ i]  =  '\n' ; 
                                                ujg =  0 ; 
                                            } 
                                        } 
                                        uh =  0 ; 
                                        fileWriter. write ( hj) ; 
                                    } 
                                    bh =  0 ; 
                                    if  ( fileWriter !=  null )  { 
                                        count =  0 ; 
                                        fileWriter. close ( ) ; 
                                        
                                        dern ( name) ; 
                                    } 
                                    map =  new  HashMap < > ( ) ; 
                                    mapMap. put ( hh,  map) ; 
                                    hh++ ; 
                                } 
                                if  ( str. equals ( "--"  +  boundary +  "--" ) )  { 
                                    if  ( uh >  0 )  { 
                                        byte [ ]  hj =  new  byte [ uh *  2 ] ; 
                                        int  ujg =  0 ; 
                                        for  ( int  i =  0 ;  i <  hj. length;  i++ )  { 
                                            if  ( ujg ==  0 )  { 
                                                hj[ i]  =  '\r' ; 
                                                ujg =  1 ; 
                                                continue ; 
                                            } 
                                            if  ( ujg ==  1 )  { 
                                                hj[ i]  =  '\n' ; 
                                                ujg =  0 ; 
                                            } 
                                        } 
                                        uh =  0 ; 
                                        fileWriter. write ( hj) ; 
                                        fileWriter. close ( ) ; 
                                    } 
                                    break ; 
                                } 
                                uh =  0 ; 
                                if  ( str. indexOf ( "Content-Disposition" )  >=  0 )  { 
                                    int  i =  str. indexOf ( ";" ) ; 
                                    String  substring =  str. substring ( i +  1 ,  str. length ( ) ) ; 
                                    String  s =  "" ; 
                                    char [ ]  chars =  substring. toCharArray ( ) ; 
                                    for  ( int  o =  0 ;  o <  chars. length;  o++ )  { 
                                        if  ( chars[ o]  ==  ' ' )  { 
                                            continue ; 
                                        } 
                                        s +=  chars[ o] ; 
                                    } 
                                    String [ ]  split =  s. split ( ";" ) ; 
                                    for  ( int  k =  0 ;  k <  split. length;  k++ )  { 
                                        String [ ]  split1 =  split[ k] . split ( "=" ) ; 
                                        String  replace =  split1[ 1 ] . replace ( "\"" ,  "" ) ; 
                                        map. put ( split1[ 0 ] ,  replace) ; 
                                    } 
                                } 
                                
                                if  ( str. indexOf ( "Content-Type" )  >=  0 )  { 
                                    if  ( str. indexOf ( "image/png" )  >=  0 || str. indexOf ( "text/plain" ) >= 0 ) { 
                                        name =  map. get ( "filename" ) ; 
                                        if  ( name !=  null )  { 
                                            fileWriter =  new  FileOutputStream ( "F:/"  +  name) ; 
                                        } 
                                        bh =  1 ; 
                                    } 
                                    fd =  new  byte [ 1024 ] ; 
                                    hkl =  0 ; 
                                    continue ; 
                                } 
                                
                                
                                
                                if  ( bh ==  1 )  { 
                                    
                                    fileWriter. write ( iij) ; 
                                } 
                                fd =  new  byte [ 1024 ] ; 
                                hkl =  0 ; 
                            } 
                        } 
                        continue ; 
                    } 
                    ghk =  0 ; 
                    u =  0 ; 
                } 
                inputStream. close ( ) ; 
                for  ( int  hhh =  0 ;  hhh <  mapMap. size ( ) ;  hhh++ )  { 
                    Map < String ,  String > =  mapMap. get ( hhh) ; 
                    Set < Map. Entry < String ,  String > > =  mapp. entrySet ( ) ; 
                    System . out. println ( hhh +  ":" ) ; 
                    for  ( Map. Entry  e :  entries)  { 
                        System . out. println ( "{"  +  e. getKey ( )  +  ":"  +  e. getValue ( )  +  "}" ) ; 
                    } 
                } 
                servletResponse. setContentType ( "text/html;charset=UTF-8" ) ; 
                PrintWriter  writer =  servletResponse. getWriter ( ) ; 
                writer. write ( "<h1>"  +  11  +  "</h1>" ) ; 
                System . out. println ( "操作完毕" ) ; 
            } 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
    private  void  dern ( String  name)  { 
        try  { 
            FileInputStream  fileInputStream =  new  FileInputStream ( "F:/"  +  name) ; 
            int  re =  0 ; 
            byte [ ]  fd =  new  byte [ 1024 ] ; 
            int  hkl =  0 ; 
            while  ( ( re =  fileInputStream. read ( ) )  !=  - 1 )  { 
                if  ( hkl >=  fd. length)  { 
                    byte [ ]  ll =  fd; 
                    fd =  new  byte [ fd. length *  2 ] ; 
                    for  ( int  g =  0 ;  g <  ll. length;  g++ )  { 
                        fd[ g]  =  ll[ g] ; 
                    } 
                } 
                fd[ hkl]  =  ( byte )  re; 
                hkl++ ; 
            } 
            FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/"  +  name) ; 
            byte [ ]  fdd =  new  byte [ hkl -  2 ] ; 
            for  ( int  u =  0 ;  u <  fdd. length;  u++ )  { 
                fdd[ u]  =  fd[ u] ; 
            } 
            fileWriter. write ( fdd) ; 
            fileWriter. close ( ) ; 
            fileInputStream. close ( ) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
111111111
  4444444
5555
22
    
  1
分割符
111111111
  4444444
5555
22
    
  1
分割符
dern ( name) ; 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput" multiple/>
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files;
        sendFileUsingGET(file);
    }
    function sendFileUsingGET(file) {
        let xhr = new XMLHttpRequest();
        let formData = new FormData();
        for (let y = 0; y < file.length; y++) {
            formData.append('file', file[y]);
        }
        formData.append('name', "22");
        xhr.open('POST', "get", false);
        xhr.send(formData);
    }
</script>
</body>
</html>
<!--上面的情况,可以解决多个文件的处理,以后建议操作文件的时候,最好这样,因为他无论是选择多个还是一个都可以完成,而最好不用操作默认为0的处理,即let file = fileInput.files[0];,当然,前面我们只是测试测试而已,所以这样也没事,因为我们只是一个测试操作,而非正式的写代码-->
 
 
 let  fileInput =  document. getElementById ( 'fileInput' ) ; 
        let  file =  fileInput. files; 
        console. log ( file) 
if  ( str. indexOf ( "Content-Type" )  >=  0 )  { 
                                    if  ( str. indexOf ( "image/png" )  >=  0 || str. indexOf ( "text/plain" ) >= 0 ) { 
                                        name =  map. get ( "filename" ) ; 
                                        if  ( name !=  null )  { 
                                            String  pa =  "F:/" ; 
                                            File  file =  new  File ( pa +  name) ; 
                                            if  ( file. exists ( ) )  { 
                                                fileWriter =  new  FileOutputStream ( pa +  name) ; 
                                            }  else  { 
                                                
                                                
                                                String  name1 =  file. getPath ( ) ; 
                                                int  i =  name1. lastIndexOf ( "\\" ) ; 
                                                String  substring =  name1. substring ( 0 ,  i) ; 
                                                new  File ( substring) . mkdirs ( ) ; 
                                                fileWriter =  new  FileOutputStream ( pa +  name) ; 
                                            } 
                                        } 
                                        bh =  1 ; 
                                    } 
                                    fd =  new  byte [ 1024 ] ; 
                                    hkl =  0 ; 
                                    continue ; 
                                } 
HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
        } 
package  com. test. controller ; 
import  javax. servlet.  * ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
public  class  re implements  Servlet  { 
    @Override 
    public  void  init ( ServletConfig  servletConfig)  throws  ServletException  { 
        System . out. println ( "初始化" ) ; 
    } 
    @Override 
    public  ServletConfig  getServletConfig ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  service ( ServletRequest  servletRequest,  ServletResponse  servletResponse)  { 
        HttpServletRequest  h =  ( HttpServletRequest )  servletRequest; 
        if  ( h. getMethod ( ) . equals ( "GET" ) )  { 
            System . out. println ( "GET" ) ; 
            try  { 
                doGet ( ( HttpServletRequest )  servletRequest,  ( HttpServletResponse )  servletResponse) ; 
            }  catch  ( Exception  e)  { 
                e. printStackTrace ( ) ; 
            } 
        } 
        if  ( h. getMethod ( ) . equals ( "POST" ) )  { 
            System . out. println ( "POST" ) ; 
            try  { 
                doPost ( ( HttpServletRequest )  servletRequest,  ( HttpServletResponse )  servletResponse) ; 
            }  catch  ( Exception  e)  { 
                e. printStackTrace ( ) ; 
            } 
        } 
    } 
    protected  void  doPost ( HttpServletRequest  servletRequest,  HttpServletResponse  servletResponse)  { 
    } 
    protected  void  doGet ( HttpServletRequest  servletRequest,  HttpServletResponse  servletResponse)  { 
    } 
    @Override 
    public  String  getServletInfo ( )  { 
        return  null ; 
    } 
    @Override 
    public  void  destroy ( )  { 
        System . out. println ( "正在销毁中" ) ; 
    } 
} 
package  com. test. controller ; 
import  javax. servlet.  ServletException ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  java. io.  IOException ; 
public  class  reen extends  re { 
    @Override 
    protected  void  doGet ( HttpServletRequest  req,  HttpServletResponse  resp)  { 
        System . out. println ( 1 ) ; 
    } 
    @Override 
    protected  void  doPost ( HttpServletRequest  req,  HttpServletResponse  resp)  { 
        System . out. println ( 2 ) ; 
    } 
} 
< servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<button οnclick="uploadFile()">访问</button>
<script>
    function uploadFile() {
        sendFileUsingGET();
    }
    function sendFileUsingGET(file) {
        let xhr = new XMLHttpRequest();
       
        xhr.open('POST', "reen", false);
        xhr.send();
        xhr.open('GET', "reen", false);
        xhr.send();
    }
</script>
</body>
</html>
初始化
POST 
2 
GET 
1 
package  com. test. controller ; 
import  javax. servlet. annotation.  MultipartConfig ; 
import  javax. servlet. annotation.  WebServlet ; 
import  javax. servlet. http.  HttpServlet ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  javax. servlet. http.  Part ; 
import  java. io.  InputStream ; 
import  java. nio. file.  Files ; 
import  java. nio. file.  Path ; 
import  java. nio. file.  Paths ; 
import  java. nio. file.  StandardCopyOption ; 
@WebServlet ( "/upload" )  
@MultipartConfig (  
        
        fileSizeThreshold =  1024  *  1024  *  2 ,   
        maxFileSize =  1024  *  1024  *  10 ,        
        maxRequestSize =  1024  *  1024  *  50      
) 
public  class  FileUploadServlet  extends  HttpServlet  {  
    
    protected  void  doPost ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        try  { 
            
            Part  filePart =  request. getPart ( "file" ) ; 
            
            String  fileName =  filePart. getSubmittedFileName ( ) ; 
            
            InputStream  fileContent =  filePart. getInputStream ( ) ; 
            
            Path  targetPath =  Paths . get ( "F:/"  +  fileName) ; 
            
            
            
            
            Files . copy ( fileContent,  targetPath,  StandardCopyOption . REPLACE_EXISTING ) ; 
            
            response. getWriter ( ) . write ( "文件上传成功:"  +  fileName) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput"/>
<button οnclick="uploadFile()">上传</button>
<script>
    function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files;
        console.log(file)
        sendFileUsingGET(file);
    }
    function sendFileUsingGET(file) {
        let xhr = new XMLHttpRequest();
        let formData = new FormData();
        for (let y = 0; y < file.length; y++) {
            formData.append('file', file[y]);
        }
        formData.append('name', "22");
        xhr.open('POST', "upload", false);
        xhr.send(formData);
    }
</script>
</body>
</html>
package  com. test. controller ; 
import  javax. servlet. annotation.  MultipartConfig ; 
import  javax. servlet. annotation.  WebServlet ; 
import  javax. servlet. http.  HttpServlet ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  javax. servlet. http.  Part ; 
import  java. io.  InputStream ; 
import  java. nio. file.  Files ; 
import  java. nio. file.  Path ; 
import  java. nio. file.  Paths ; 
import  java. nio. file.  StandardCopyOption ; 
import  java. util.  Collection ; 
@WebServlet ( "/upload" ) 
@MultipartConfig ( 
        fileSizeThreshold =  1024  *  1024  *  2 , 
        maxFileSize =  1024  *  1024  *  10 , 
        maxRequestSize =  1024  *  1024  *  50 ) 
public  class  FileUploadServlet  extends  HttpServlet  { 
    protected  void  doPost ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        try  { 
            Collection < Part > =  request. getParts ( ) ; 
            for  ( Part  part :  request. getParts ( ) )  { 
                
                
                if  ( "file" . equals ( part. getName ( ) ) )  { 
                    String  fileName =  part. getSubmittedFileName ( ) ; 
                    InputStream  fileContent =  part. getInputStream ( ) ; 
                    Path  targetPath =  Paths . get ( "F:/"  +  fileName) ; 
                    Files . copy ( fileContent,  targetPath,  StandardCopyOption . REPLACE_EXISTING ) ; 
                    response. getWriter ( ) . write ( "文件上传成功:"  +  fileName) ; 
                } 
            } 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
String  fileName =  part. getSubmittedFileName ( ) ; 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="file" name="file">
    <input type="file" name="file">
    <input type="text" name="filename">
    <input type="submit" value="文件上传">
</form>
</body>
</html>
 
< input type= "file"  id= "fileInput" / > 
< button onclick= "uploadFile()" > 上传< / button> 
< script src= "https://code.jquery.com/jquery-3.6.0.min.js" > < / script> 
< script> uploadFile ( )  { 
        let fileInput =  document. getElementById ( 'fileInput') ; 
        let file =  fileInput. files; 
        console. log ( file) 
        sendFileUsingGET ( file) ; 
    } 
    function sendFileUsingGET ( file)  { 
        let formData =  new  FormData ( ) ; 
        for  ( let y =  0 ;  y <  file. length;  y++ )  { 
            formData. append ( 'file' ,  file[ y] ) ; 
        } 
        formData. append ( 'name' ,  "22" ) ; 
        $. ajax ( { 
            url:  'upload' ,  
            type:  'POST' , 
            data:  formData, 
            processData:  false ,  
            contentType:  false ,  
            success:  function ( data)  { 
                
                console. log ( data) 
            } , 
            error:  function ( error)  { 
                console. log ( data) 
            } 
        } ) ; 
    } 
< / script> 
package  com. test. controller ; 
import  javax. servlet. annotation.  MultipartConfig ; 
import  javax. servlet. annotation.  WebServlet ; 
import  javax. servlet. http.  HttpServlet ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  javax. servlet. http.  Part ; 
import  java. io.  InputStream ; 
import  java. nio. file.  Files ; 
import  java. nio. file.  Path ; 
import  java. nio. file.  Paths ; 
import  java. nio. file.  StandardCopyOption ; 
import  java. util.  Collection ; 
@WebServlet ( "/upload" ) 
@MultipartConfig ( 
        fileSizeThreshold =  1024  *  1024  *  2 , 
        maxFileSize =  1024  *  1024  *  10 , 
        maxRequestSize =  1024  *  1024  *  50 ) 
public  class  FileUploadServlet  extends  HttpServlet  { 
    protected  void  doPost ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        try  { 
            Collection < Part > =  request. getParts ( ) ; 
            for  ( Part  part :  request. getParts ( ) )  { 
                if  ( "file" . equals ( part. getName ( ) ) )  { 
                    String  name =  part. getName ( ) ;  
                    String  fileName =  part. getSubmittedFileName ( ) ; 
                    InputStream  fileContent =  part. getInputStream ( ) ; 
                    Path  targetPath =  Paths . get ( "F:/"  +  fileName) ; 
                    Files . copy ( fileContent,  targetPath,  StandardCopyOption . REPLACE_EXISTING ) ; 
                    response. getWriter ( ) . write ( "文件上传成功:"  +  fileName) ; 
                } 
            } 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
request. setCharacterEncoding ( "utf-8" ) ;  
Collection < Part > =  request. getParts ( ) ; 
url:  'upload' ,  
type:  'POST' , 
data:  formData, 
processData:  false ,  
contentType:  false ,  
function sendFileUsingGET ( fileData,  name)  { 
        let xhr =  new  XMLHttpRequest ( ) ; 
        let url; 
        for  ( let h =  0 ;  h <  fileData. length;  h++ )  { 
            url =  "file" ; 
            xhr. open ( 'POST' ,  url,  false ) ; 
            xhr. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
            xhr. send ( "file="  +  encodeURIComponent ( fileData[ h] )  +  "&filename="  +  name[ h] ) ; 
        } 
    } 
type :  'GET' ,  
    headers :  { 
        'Header-Name1' :  'Header-Value1' ,  
        'Header-Name2' :  'Header-Value2' , 
        
    } , 
let  xhr =  new  XMLHttpRequest ( ) ; 
        xhr. open ( 'POST' ,  "upload?k=4" ,  false ) ; 
        xhr. setRequestHeader ( "Content-Type" ,  "application/json" ) ; 
        xhr. send ( "nn=3" ) ; 
 
processData :  false ,  
contentType :  false ,  
response. setContentType ( "text/html;charset=UTF-8" ) ;  
response. getWriter ( ) . write ( "文件上传成功:"  +  fileName) ; 
 < packaging> </ packaging> < dependencies> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> </ dependencies> <?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> </ web-app> package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  upload { 
    @RequestMapping ( "a" ) 
    public  void  handle01 ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        try  { 
            response. setContentType ( "text/html;charset=UTF-8" ) ; 
            response. getWriter ( ) . write ( "操作" ) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
< beansxmlns = " http://www.springframework.org/schema/beans" xmlns: context= " http://www.springframework.org/schema/context" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd" > < context: component-scanbase-package = " controller" /> </ beans> <?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> </ web-app> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput" multiple/>
<button οnclick="uploadFile()">上传</button>
<script>
    async function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let fileData = [];
        let fileDatename = [];
        if (fileInput.files.length === 0) {
            return;
        }
        let readFilePromises = [];
        for (let y = 0; y < fileInput.files.length; y++) {
            if (fileInput.files[y] != undefined) {
                let reader = new FileReader();
                let readFilePromise = new Promise((resolve, reject) => {
                    reader.onload = function (e) {
                        console.log(e);
                        fileData.push(e.target.result.split(',')[1]);
                        fileDatename.push(fileInput.files[y].name);
                        resolve();
                    };
                    reader.readAsDataURL(fileInput.files[y]);
                });
                readFilePromises.push(readFilePromise);
            }
        }
        await Promise.all(readFilePromises);
        sendFileUsingGET(fileData, fileDatename);
    }
    function sendFileUsingGET(fileData, name) {
        console.log(fileData)
        console.log(name)
        let xhr = new XMLHttpRequest();
        let url = "test/a?";
        for (let h = 0; h < fileData.length; h++) {
            if (h == fileData.length - 1) {
                url += "file=" + encodeURIComponent(fileData[h]) + "&filename=" + name[h];
                continue;
            }
            url += "file=" + encodeURIComponent(fileData[h]) + "&filename=" + name[h] + "&";
        }
        console.log(url)
        xhr.open('GET', url, false);
        xhr.send();
        console.log(xhr.responseText);
    }
</script>
</body>
</html>
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  java. io.  FileOutputStream ; 
import  java. io.  PrintWriter ; 
import  java. util.  Base64 ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  upload { 
    @RequestMapping ( "a" ) 
    public  void  handle01 ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        response. setContentType ( "text/html;charset=UTF-8" ) ; 
        try  { 
            PrintWriter  writer =  response. getWriter ( ) ; 
            String [ ]  file =  request. getParameterValues ( "file" ) ; 
            String [ ]  filename =  request. getParameterValues ( "filename" ) ; 
            if  ( file !=  null )  { 
                for  ( int  i =  0 ;  i <  file. length;  i++ )  { 
                    String [ ]  split =  filename[ i] . split ( "\\." ) ; 
                    byte [ ]  decodedBytes =  Base64 . getDecoder ( ) . decode ( file[ i] ) ; 
                    FileOutputStream  fileWriter =  new  FileOutputStream ( "F:/"  +  split[ 0 ]  +  "."  +  split[ 1 ] ) ; 
                    fileWriter. write ( decodedBytes) ; 
                    writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
                } 
                return ; 
            } 
            writer. write ( "<h1>"  +  "上传的文件为空"  +  "</h1>" ) ; 
            return ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
xhr. open ( 'GET' ,  url,  false ) ; 
到
xhr. open ( 'POST' ,  url,  false ) ; 
@MultipartConfig ( 
        fileSizeThreshold =  1024  *  1024  *  2 , 
        maxFileSize =  1024  *  1024  *  10 , 
        maxRequestSize =  1024  *  1024  *  50 ) 
<form action="test/a" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="text" name="filename">
    <input type="submit" value="提交">
</form>
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. ui.  Model ; 
import  org. springframework. web. bind. annotation.  PostMapping ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. bind. annotation.  RequestParam ; 
import  org. springframework. web. multipart.  MultipartFile ; 
import  org. springframework. web. servlet.  ModelAndView ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  java. io.  FileOutputStream ; 
import  java. io.  PrintWriter ; 
import  java. util.  Date ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  upload { 
    @PostMapping ( "a" ) 
    public  void  handleFormUpload ( @RequestParam ( "file" )  MultipartFile  file,  @RequestParam ( "filename" )  String  filename,  HttpServletRequest  request,  HttpServletResponse  response)  { 
        if  ( ! file. isEmpty ( ) )  { 
            try  { 
                
                request. setCharacterEncoding ( "utf-8" ) ; 
                
                System . out. println ( "文件名称: "  +  filename) ; 
                String  name =  file. getOriginalFilename ( ) ;  
                
                name =  new  String ( name. getBytes ( "iso-8859-1" ) ,  "utf-8" ) ; 
                byte [ ]  bytes =  file. getBytes ( ) ; 
                FileOutputStream  fileOutputStream =  new  FileOutputStream ( "F:/"  +  name) ; 
                fileOutputStream. write ( bytes) ; 
                response. setContentType ( "text/html;charset=UTF-8" ) ; 
                PrintWriter  writer =  response. getWriter ( ) ; 
                writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
            }  catch  ( Exception  e)  { 
                e. printStackTrace ( ) ; 
            } 
        } 
    } 
} 
   
    < beanid = " multipartResolver" class = " org.springframework.web.multipart.commons.CommonsMultipartResolver" > < propertyname = " maxUploadSize" value = " 5242880" > </ property> < propertyname = " maxInMemorySize" value = " 40960" > </ property> </ bean> 
 
< dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < inputtype = " file" name = " file" multiple > package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. ui.  Model ; 
import  org. springframework. web. bind. annotation.  PostMapping ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. bind. annotation.  RequestParam ; 
import  org. springframework. web. multipart.  MultipartFile ; 
import  org. springframework. web. servlet.  ModelAndView ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  java. io.  FileOutputStream ; 
import  java. io.  PrintWriter ; 
import  java. util.  Date ; 
import  java. util.  List ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  upload { 
    @PostMapping ( "a" ) 
    public  void  handleFormUpload ( @RequestParam ( "file" )  List < MultipartFile > ,  @RequestParam ( "filename" )  String  filename,  HttpServletRequest  request,  HttpServletResponse  response)  { 
        if  ( fileList. size ( )  >  0 )  { 
            try  { 
                for  ( MultipartFile  file :  fileList)  { 
                    request. setCharacterEncoding ( "utf-8" ) ; 
                    System . out. println ( "文件名称: "  +  filename) ; 
                    String  name =  file. getOriginalFilename ( ) ; 
                    name =  new  String ( name. getBytes ( "iso-8859-1" ) ,  "utf-8" ) ; 
                    byte [ ]  bytes =  file. getBytes ( ) ; 
                    FileOutputStream  fileOutputStream =  new  FileOutputStream ( "F:/"  +  name) ; 
                    fileOutputStream. write ( bytes) ; 
                    response. setContentType ( "text/html;charset=UTF-8" ) ; 
                    PrintWriter  writer =  response. getWriter ( ) ; 
                    writer. write ( "<h1>"  +  "上传一个文件成功"  +  "</h1>" ) ; 
                } 
            }  catch  ( Exception  e)  { 
                e. printStackTrace ( ) ; 
            } 
        } 
    } 
} 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="file" id="fileInput"/>
<button οnclick="uploadFile()">上传</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    function uploadFile() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files;
        console.log(file)
        sendFileUsingGET(file);
    }
    function sendFileUsingGET(file) {
        let formData = new FormData();
        for (let y = 0; y < file.length; y++) {
            formData.append('file', file[y]);
        }
        formData.append('filename', "22");
        $.ajax({
            url: 'test/a', // 提交到的URL
            type: 'POST',
            data: formData,
            processData: false, // 不处理数据
            contentType: false, // 不设置内容类型
            success: function (data) {
                // 成功回调函数
                console.log(data)
            },
            error: function (error) {
                console.log(data)
            }
        });
    }
</script>
</body>
</html>
xhr. setRequestHeader ( "Content-Type" ,  "application/json" ) ; 
xhr. setRequestHeader ( "Content-Type" ,  "application/x-www-form-urlencoded" ) ; 
或者
multipart/ form- data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<button οnclick="uploadFile()">访问</button>
<script>
    function uploadFile() {
        sendFileUsingGET();
    }
    function sendFileUsingGET() {
        let xhr = new XMLHttpRequest();
        xhr.open('POST', "te/u", false);
        //可以选择加上看看结果(一般是一样的)
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send("22");
    }
</script>
</body>
</html>
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. ui.  Model ; 
import  org. springframework. web. bind. annotation.  PostMapping ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. bind. annotation.  RequestParam ; 
import  org. springframework. web. multipart.  MultipartFile ; 
import  org. springframework. web. servlet.  ModelAndView ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  java. io.  BufferedReader ; 
import  java. io.  FileOutputStream ; 
import  java. io.  PrintWriter ; 
import  java. util.  Date ; 
import  java. util.  List ; 
@Controller 
@RequestMapping ( "/te" ) 
public  class  json { 
    @PostMapping ( "u" ) 
    public  void  handleFormUpload ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        
        response. setContentType ( "application/json" ) ; 
        
        StringBuilder  requestBody =  new  StringBuilder ( ) ; 
        try  { 
            BufferedReader  reader =  request. getReader ( ) ; 
            String  line; 
            while  ( ( line =  reader. readLine ( ) )  !=  null )  { 
                requestBody. append ( line) ; 
            } 
            String  jsonPayload =  requestBody. toString ( ) ; 
            response. getWriter ( ) . write ( jsonPayload) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
response. setContentType ( "application/json" ) ; 
response. setContentType ( "text/html;charset=UTF-8" ) ; 
xhr. send ( "22" ) ; 
console. log ( xhr. responseText) ;  
  
        response. setContentType ( "application/json" ) ; 
        try  { 
            response. getWriter ( ) . write ( "{\"message\": \"Hello, world!\"}" ) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
     
        response. setContentType ( "application/json" ) ; 
        try  { 
            response. getWriter ( ) . write ( "[1,2,3]" ) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
package  controller ; 
public  class  test { 
    String  message; 
    @Override 
    public  String  toString ( )  { 
        return  "test{"  + 
                "message='"  +  message +  '\''  + 
                '}' ; 
    } 
} 
   
        response. setContentType ( "application/json" ) ; 
        try  { 
            test test =  new  test ( ) ; 
            test. message =  "Hello, world!" ; 
            response. getWriter ( ) . write ( test. toString ( ) ) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
{ "message" :  "Hello, world!" } 
[ 1 , 2 , 3 ] 
test{ message= 'Hello ,  world! '} 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script src="js/jquery-3.4.1.min.js"></script>
    <!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<button id="btn">ajax提交</button>
<script>
    $("#btn").click(function(){
        let url = 'ajax';
        let data = '[{"id":1,"username":"张三"},{"id":2,"username":"李四"}]'
        $.ajax({
            type:'POST',//大小写可以忽略
            url:url,
            data:data,
            contentType:'application/json;charset=utf-8', //如这里
            success:function (data) {
                console.log(data);
            }
        })
    })
</script>
</body>
</html>
processData:  false ,  
contentType:  false ,  
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
< html> < head> < title> </ title> </ head> < body> < inputtype = " file" id = " fileInput" /> < buttononclick = " uploadFile ( ) " > </ button> < scriptsrc = " https://code.jquery.com/jquery-3.6.0.min.js" > </ script> < script> 
    function  uploadFile ( )  { 
        let  fileInput =  document. getElementById ( 'fileInput' ) ; 
        let  file =  fileInput. files; 
        console. log ( file) 
        sendFileUsingGET ( file) ; 
    } 
    function  sendFileUsingGET ( file )  { 
        let  formData =  new  FormData ( ) ; 
        for  ( let  y =  0 ;  y <  file. length;  y++ )  { 
            formData. append ( 'file' ,  file[ y] ) ; 
        } 
        formData. append ( 'name' ,  "22" ) ; 
        $. ajax ( { 
            url :  'upload' ,  
            type :  'POST' , 
            data :  formData, 
            processData :  false ,  
            contentType :  false ,  
            success :  function  ( data )  { 
                
                console. log ( data) 
            } , 
            error :  function  ( error )  { 
                console. log ( data) 
            } 
        } ) ; 
    } 
 </ script> </ body> </ html> package  controller ; 
import  javax. servlet. annotation.  MultipartConfig ; 
import  javax. servlet. annotation.  WebServlet ; 
import  javax. servlet. http.  HttpServlet ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
import  javax. servlet. http.  Part ; 
import  java. io.  InputStream ; 
import  java. nio. file.  Files ; 
import  java. nio. file.  Path ; 
import  java. nio. file.  Paths ; 
import  java. nio. file.  StandardCopyOption ; 
import  java. util.  Collection ; 
@WebServlet ( "/upload" ) 
@MultipartConfig ( 
        fileSizeThreshold =  1024  *  1024  *  2 , 
        maxFileSize =  1024  *  1024  *  10 , 
        maxRequestSize =  1024  *  1024  *  50 ) 
public  class  FileUploadServlet  extends  HttpServlet  { 
    protected  void  doPost ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        try  { 
            System . out. println ( 1 ) ; 
            request. setCharacterEncoding ( "utf-8" ) ; 
            Collection < Part > =  request. getParts ( ) ; 
            for  ( Part  part :  request. getParts ( ) )  { 
                if  ( "file" . equals ( part. getName ( ) ) )  { 
                    String  name =  part. getName ( ) ; 
                    String  fileName =  part. getSubmittedFileName ( ) ; 
                    InputStream  fileContent =  part. getInputStream ( ) ; 
                    Path  targetPath =  Paths . get ( "F:/"  +  fileName) ; 
                    Files . copy ( fileContent,  targetPath,  StandardCopyOption . REPLACE_EXISTING ) ; 
                    response. setContentType ( "text/html;charset=UTF-8" ) ; 
                    response. getWriter ( ) . write ( "文件上传成功:"  +  fileName) ; 
                } 
            } 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  PostMapping ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  javax. servlet. http.  HttpServletRequest ; 
import  javax. servlet. http.  HttpServletResponse ; 
@Controller 
@RequestMapping ( "/upload" ) 
public  class  up { 
    @PostMapping ( "u" ) 
    public  void  handleFormUpload ( HttpServletRequest  request,  HttpServletResponse  response)  { 
        try  { 
            System . out. println ( 2 ) ; 
            response. getWriter ( ) . write ( "Hello, world!" ) ; 
        }  catch  ( Exception  e)  { 
            e. printStackTrace ( ) ; 
        } 
    } 
} 
 $. ajax ( { 
            url :  'upload' ,  
            type :  'POST' , 
            data :  formData, 
            contentType :  false ,  
            success :  function  ( data )  { 
                
                console. log ( data) 
            } , 
            error :  function  ( error )  { 
                console. log ( data) 
            } 
        } ) ; 
contentType : 'application/json;charset=utf-8' ,  
contentType: 'multipart/ form- data',  
contentType :  "multipart/form-data;boundary=----WebKitFormBoundary85LOXlPgPrx4eO" ,  
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<script src="js/jquery-3.4.1.min.js"></script>
    <!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<button id="btn">ajax提交</button>
<script>
    $("#btn").click(function(){
        let url = 'ajax';
        let data = '[{"id":1,"username":"张三"},{"id":2,"username":"李四"}]'
        $.ajax({
            type:'POST',//大小写可以忽略
            url:url,
            data:data,
            contentType:'application/json;charset=utf-8', //如这里
            success:function (data) {
                console.log(data);
            }
        })
    })
</script>
</body>
</html>
  String  id; 
    String  username; 
    public  String  getId ( )  { 
        return  id; 
    } 
    public  void  setId ( String  id)  { 
        this . id =  id; 
    } 
    public  String  getUsername ( )  { 
        return  username; 
    } 
    public  void  setUsername ( String  username)  { 
        this . username =  username; 
    } 
    
    @Override 
    public  String  toString ( )  { 
        return  "User{"  + 
                "id='"  +  id +  '\''  + 
                ", username='"  +  username +  '\''  + 
                '}' ; 
    } 
package  controller ; 
import  org. springframework. web. bind. annotation.  RequestBody ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  org. springframework. web. bind. annotation.  ResponseBody ; 
import  java. util.  List ; 
@Controller 
public  class  ajax { 
    @ResponseBody 
    @RequestMapping ( "ajax" ) 
    
    public  List < User > ajax ( @RequestBody  List < User > )  { 
        System . out. println ( list) ; 
        return  list; 
    } 
} 
Content - Type : application/ json; charset= UTF - 8 
 < packaging> </ packaging> < dependencies> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> < dependency> < groupId> </ groupId> < artifactId> </ artifactId> < version> </ version> </ dependency> </ dependencies> 
 
<?xml version="1.0" encoding="UTF-8"?> 
< web-appxmlns = " http://xmlns.jcp.org/xml/ns/javaee" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = " 4.0" > < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> </ servlet> < servlet-mapping> < servlet-name> </ servlet-name> < url-pattern> </ url-pattern> </ servlet-mapping> </ web-app> package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( )  { 
 System . out. println ( 1 ) ; 
    } 
} 
< beansxmlns = " http://www.springframework.org/schema/beans" xmlns: context= " http://www.springframework.org/schema/context" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd" > < context: component-scanbase-package = " controller" /> </ beans> < servlet> < servlet-name> </ servlet-name> < servlet-class> </ servlet-class> < init-param> < param-name> </ param-name> < param-value> </ param-value> </ init-param> </ servlet> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="test/a" method="post">
    <input type="text" name="text1">
    <input type="text" name="text2">
    <input type="text" name="text3">
    <input type="submit" value="提交">
</form>
</body>
</html>
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( String  text1)  { 
        System . out. println ( text1) ; 
        System . out. println ( 1 ) ; 
    } 
} 
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  java. util.  Arrays ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( String [ ]  text1)  { 
        System . out. println ( Arrays . toString ( text1) ) ; 
        System . out. println ( 1 ) ; 
    } 
} 
<form action="test/a" method="get">
    <input type="text" name="text1">
    <input type="text" name="text1">
    <input type="text" name="text1">
    <input type="submit" value="提交">
</form>
<form action="test/a" method="get">
    <input type="text" name="text1">
    <input type="text" name="text2">
    <input type="text" name="text3">
    <input type="submit" value="提交">
</form>
package  controller ; 
public  class  User  { 
    private  String  id; 
    private  String  name; 
    private  String  pass; 
    @Override 
    public  String  toString ( )  { 
        return  "User{"  + 
                "id='"  +  id +  '\''  + 
                ", name='"  +  name +  '\''  + 
                ", pass='"  +  pass +  '\''  + 
                '}' ; 
    } 
    public  String  getId ( )  { 
        return  id; 
    } 
    public  void  setId ( String  id)  { 
        this . id =  id; 
    } 
    public  String  getName ( )  { 
        return  name; 
    } 
    public  void  setName ( String  name)  { 
        this . name =  name; 
    } 
    public  String  getPass ( )  { 
        return  pass; 
    } 
    public  void  setPass ( String  pass)  { 
        this . pass =  pass; 
    } 
} 
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( User  text1)  { 
        System . out. println ( text1) ; 
        System . out. println ( 1 ) ; 
    } 
} 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="test/a" method="post">
    <!--name(属性,而不是属性值,name="id"中name是属性,说明的就是这个)中的大小写一般是忽略的-->
    <input type="text" name="id">
    <input type="text" name="name">
    <input type="text" name="pass">
    <input type="submit" value="提交">
</form>
</body>
</html>
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( User [ ]  text1)  { 
        System . out. println ( text1) ; 
        System . out. println ( 1 ) ; 
    } 
} 
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  java. util.  Arrays ; 
import  java. util.  List ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( List < String > )  { 
        System . out. println ( text1. toArray ( ) ) ; 
        System . out. println ( Arrays . toString ( text1. toArray ( ) ) ) ; 
        System . out. println ( 1 ) ; 
    } 
} 
package  controller ; 
import  org. springframework. stereotype.  Controller ; 
import  org. springframework. web. bind. annotation.  RequestMapping ; 
import  java. util.  Arrays ; 
import  java. util.  List ; 
import  java. util.  Map ; 
@Controller 
@RequestMapping ( "/test" ) 
public  class  test { 
    @RequestMapping ( "a" ) 
    public  void  a ( Map < String ,  String > )  { 
        System . out. println ( text1) ; 
        System . out. println ( 1 ) ; 
    } 
} 
package  controller ; 
import  java. util.  List ; 
import  java. util.  Map ; 
public  class  QueryVo  { 
    String  id; 
    User  user; 
    List < User > ; 
    Map < String ,  User > ; 
    @Override 
    public  String  toString ( )  { 
        return  "QueryVo{"  + 
                "id='"  +  id +  '\''  + 
                ", user="  +  user + 
                ", userList="  +  userList + 
                ", userMap="  +  userMap + 
                '}' ; 
    } 
    public  String  getId ( )  { 
        return  id; 
    } 
    public  void  setId ( String  id)  { 
        this . id =  id; 
    } 
    public  User  getUser ( )  { 
        return  user; 
    } 
    public  void  setUser ( User  user)  { 
        this . user =  user; 
    } 
    public  List < User > getUserList ( )  { 
        return  userList; 
    } 
    public  void  setUserList ( List < User > )  { 
        this . userList =  userList; 
    } 
    public  Map < String ,  User > getUserMap ( )  { 
        return  userMap; 
    } 
    public  void  setUserMap ( Map < String ,  User > )  { 
        this . userMap =  userMap; 
    } 
} 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="test/a" method="post">
    搜索关键字:
    <input type="text" name="keyword"> <br>
    user对象:
    <input type="text" name="user.id" placeholder="编号">
    <input type="text" name="user.username" placeholder="姓名"><br>
    list集合<br>
    第一个元素:
    <input type="text" name="userList[0].id" placeholder="编号"><!--可以写0或者不写,当然有些版本可能必须要写0了-->
    <input type="text" name="userList[0].username" placeholder="姓名"><br>
    第二个元素:
    <input type="text" name="userList[1].id" placeholder="编号">
    <input type="text" name="userList[1].username" placeholder="姓名"><br>
    map集合<br>
    第一个元素:
    <input type="text" name="userMap['u1'].id" placeholder="编号">
    <input type="text" name="userMap['u1'].username" placeholder="姓名"><br>
    第二个元素:
    <input type="text" name="userMap['u1'].id" placeholder="编号">
    <input type="text" name="userMap['u1'].username" placeholder="姓名"><br>
    <input type="submit" value="复杂类型">
</form>
</body>
</html>
 list集合<br>
    第一个元素:
    <input type="text" name="userList[0]" placeholder="编号"><!--可以写0或者不写,当然有些版本可能必须要写0了-->
    <input type="text" name="userList[0]" placeholder="姓名"><br>
    第二个元素:
    <input type="text" name="userList[1]" placeholder="编号">
    <input type="text" name="userList[1]" placeholder="姓名"><br>
    map集合<br>
    第一个元素:
    <input type="text" name="userMap['u1']" placeholder="编号">
    <input type="text" name="userMap['u1']" placeholder="姓名"><br>
    第二个元素:
    <input type="text" name="userMap['u1']" placeholder="编号">
    <input type="text" name="userMap['u1']" placeholder="姓名"><br>