快捷搜索: 长连接 前端 源码 pan

SpringMVC(idea)整理

SpringMVC(idea)整理

文章目录:

1.创建web项目

maven依赖

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

2.回顾servlet

1.编写servlet

2.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="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>Hello</servlet-name>
        <servlet-class>com.wash.servlet.Servlet1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
   <!-- <session-config>
        <session-timeout>15</session-timeout>
    </session-config>-->
   <!-- <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>-->
</web-app>

3.编写跳转页面的jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${
          
   msg}
</body>
</html>

4.运行tomcat,在页面配置参数

3.springMVC初识

4.第一个springMVC程序

1.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="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>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联一个springmvc的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
            
        </init-param>
        <!--启动级别-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--添加处理映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--添加处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <!--添加视图解析器
		1.获取ModelAndView的数据
		2.解析ModelAndView的视图名字
		3.拼接视图名字,找到对应的视图/WBE-INF/jsp/hello.jsp
		4.将数据渲染到视图上
    -->
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean id="/hello" class="com.wash.controller.HelloController"/>
</beans>

3.controller.java

package com.wash.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloController implements Controller {
          
   
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
          
   
       //ModerAndView 模型和视图
        ModelAndView mv= new ModelAndView();
        //封装对象,放在ModelAndView中
        mv.addObject("msg", "HelloSpringMvc");
        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello");
        return mv;
    }
}

4.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${
          
   msg}
</body>
</html>

5.运行tomcat,将项目部署在tomcat下运行

5.springMVC的执行原理(执行流程)

6.使用注解开发springMVC

web.xml和jsp页面不变,且都需要配置

1.controller.java

package com.wash.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class HelloController  {
          
   
   //真实地址
    @RequestMapping("/he")
        public String hello(Model model){
          
   
            //封装数据
            model.addAttribute("msg", "hello springmvc");
            return "hello";//会被视图解析器处理
        }
}

2.配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
    <context:component-scan base-package="com.wash.controller"/>
    <!--让spring不处理静态资源,css,js,html-->
    <mvc:default-servlet-handler/>
    <!--使用注解注册映射器和适配器两个实例-->
    <mvc:annotation-driven/>
    <!--添加视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

7.RequestMapping

明确真实地址的级别

8.Restful风格

1.原来的风格

2.Restful

在springmvc中添加@PathVariable注解

10.接收请求参数及数据回显

11.解决乱码问题

/*可以的。

这里把url-pattern里的/改成/*,/处理部分请求,/ *处理所有请求包括jsp界面。

11.JSON

12.controller返回JSON数据

    jackson Fastjson

步骤:

    1.导入maven包(上面的 jackson) 2.在web.xml内配置dispatcherservlet 和过滤器 3.配置spring-servlet.xml(需要自动扫描还有视图解析器) 4.在controller类中创建Objectmapper类 5.可将JSON封装成工具类

将JSON封装成工具类

工具类 controller类 注意:通过后端返回给前端字符串的两种方式

    第一种@controller +@ResponseBody 第二种@RestController

FastJson

1.maven导包

13.ssm整合

注意:因为ssm整合这块代码比较多,所以之后会单更新ssm整合篇

错误排查

14.Ajax

1.用iframe仿照ajax实现不刷新页面加载数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>iframe测试体验无刷新</title>
    <script>
        function go() {
           
    
           var url= document.getElementById("url").value;
            document.getElementById("iframe").src=url;

        }
    </script>
</head>
<body>
    <div>
        <p>请输入地址</p>
        <p>
            <input type="text" id="url" value="https://www.baidu.com"/>
            <input type="button" value="提交" onclick="go()"/>
        </p>
    </div>
    <div>
        <iframe id="iframe" style="width: 100%;height: 500px"></iframe>
    </div>
</body>
</html>

2.通过jquery库的ajax实现异步刷新

//controller

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class ajaxComtroller {
          
   
@RequestMapping("/t1")
    public String ajax(){
          
   

        return "hello";
    }
@RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
          
   
    System.out.println("name"+name);
    if("shuaishuai".equals(name)){
          
   
        response.getWriter().print("true");
    }else{
          
   
        response.getWriter().print("false");
    }
}
}
//通过ajax实现后台controller层的数据传送
//ajax通过url和callback找到对应controller,
//并把controller层的数据(字符串)返回到前端。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
      <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
      <script>
        function go(){
           
    
            $.post({
           
    
                url:"${pageContext.request.contextPath}/a1",
                data:{
           
    "name":$("#username").val()},
                success:function (data) {
           
    
                        alert(data);
                }

            })
        }

      </script>
  </head>
  <body>
      <%--失去焦点的时候发起一个请求到后台--%>
      用户名<input type="text" id="username" onblur="go()"/>
  </body>
</html>

3.ajax异步加载数据

//1.实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
          
   
    private String name;
    private int age;
    private String sex;
}

注意:导lombok包和Jackson包

<dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.8</version>
    </dependency>

</dependencies>
//2.controller层

@RestController
public class ajaxComtroller {
          
   
@RequestMapping("/t1")
    public String ajax(){
          
   

        return "hello";
    }
@RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
          
   
    System.out.println("name"+name);
    if("shuaishuai".equals(name)){
          
   
        response.getWriter().print("true");
    }else{
          
   
        response.getWriter().print("false");
    }
}

@RequestMapping("/a2")
    public List<User> a2(){
          
   
    List<User> userList= new ArrayList<User>();
    //添加数据
    userList.add(new User("shuaishuai",2,"男"));
    userList.add(new User("wenwen",2,"女"));
    userList.add(new User("小小猪",2,"女"));
    return userList;
}
}
//3.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>a2</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>
        $(function () {
           
    
            $("#btn").click(function () {
           
    
               /*
               * $.post(url,参数【可以省略】,success)*/
                $.post("${pageContext.request.contextPath}/a2",function (data) {
           
    
                    var html="";
                    for (let i=0;i<data.length;i++){
           
    
                        html+="<tr>"+
                            "<td>"+ data[i].name+"</td>"+
                            "<td>"+ data[i].age+"</td>"+
                            "<td>"+ data[i].sex+"</td>"+
                            "</tr>"
                    }
                    $("#content").html(html);
                });
            })

        });


    </script>
</head>
<body>
    <input type="button" value="加载数据" id="btn"/>
    <table>
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>

        <tbody id="content">
            <%--后台数据--%>

        </tbody>
    </table>
</body>
</html>

4.ajax验证用户名体验

注意:json乱码的解决

//1.login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>
        function a1() {
           
    
           $.post({
           
    
               url:"${pageContext.request.contextPath}/a3",
               data:{
           
    "name":$("#name").val()},
               success:function (data) {
           
    
                    if(data.toString()==="ok"){
           
    
                        $("#userinfo").css("color","green");
                    }else{
           
    
                        $("#userinfo").css("color","red");
                    }
                    $("#userinfo").html(data);
               }
           })
        }
        function a2() {
           
    
            $.post({
           
    
                url:"${pageContext.request.contextPath}/a3",
                data:{
           
    "pwd":$("#pwd").val()},
                success:function (data) {
           
    
                    if(data.toString()==="ok"){
           
    
                        $("#pwdinfo").css("color","green");
                    }else{
           
    
                        $("#pwdinfo").css("color","red");
                    }
                    $("#pwdinfo").html(data);
                }
            })
        }

    </script>
</head>
<body>

    用户名:<input type="text" id="name" placeholder="请输入用户名" onblur="a1()"/>
           <span id="userinfo"></span>
    密码:  <input type="text" id="pwd" placeholder="请输入密码" onblur="a2()"/>
           <span id="pwdinfo"></span>

</body>
</html>
//2.controller

import com.wash.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ajaxComtroller {
          
   
@RequestMapping("/t1")
    public String ajax(){
          
   

        return "hello";
    }
@RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
          
   
    System.out.println("name"+name);
    if("shuaishuai".equals(name)){
          
   
        response.getWriter().print("true");
    }else{
          
   
        response.getWriter().print("false");
    }
}

@RequestMapping("/a2")
    public List<User> a2(){
          
   
    List<User> userList= new ArrayList<User>();
    //添加数据
    userList.add(new User("shuaishuai",2,"男"));
    userList.add(new User("wenwen",2,"女"));
    userList.add(new User("小小猪",2,"女"));
    return userList;
}

@RequestMapping("/a3")
    public String a3(String name,String pwd){
          
   
        String msg="";
        if(name!=null){
          
   
            if("admin".equals(name)){
          
   
                msg="ok";
            }else{
          
   
                msg="用户名有误";
            }
        }
        if(pwd!=null){
          
   
            if("1234567".equals(pwd)){
          
   
                msg="ok";
            }else{
          
   
                msg="密码错误";
            }
        }
        return msg;
}
}

15.拦截器

    首先新建module,添加web支持 然后编写web.xml和application.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="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">
    <!--dispatchservlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--绑定spring的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application.xml</param-value>
        </init-param>
        <!--启动时加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
        <!--不能写/*-->
    </servlet-mapping>
    <!--过滤字符集-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
        <!--/*过滤所有的请求-->
    </filter-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>
    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 4.扫描web相关的bean,下面所有的注解类交给ioc容器处理 -->
    <context:component-scan base-package="com.wash.controller" />
    <!--拦截器配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--包括这个请求下面的所有请求-->
            <mvc:mapping path="/**"/>
            <bean class="com.wash.config.Interceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</bean>

注意拦截器的配置

    之后写拦截器还有controller
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Interceptor implements HandlerInterceptor {
          
   
//return true;表示拦截器放行
//return false;表示拦截器拦截请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          
   
        //处理前
        System.out.println("处理前");
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
          
   
        //处理后
        System.out.println("处理后");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
          
   
            //清理
    }
}
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class controller {
          
   

    @RequestMapping("/a1")
        public String test(){
          
   
        System.out.println("ok");
            return "ok";
        }
}

16.通过拦截器实现登录判断验证(只有登录才能进去页面)

1.配置web.xml和application.xml 2.controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class Logincontroller {
          
   
   @RequestMapping("/main")
   public String main(){
          
   
       return "main";
   }
    @RequestMapping("/gologin")
    public String logingo(){
          
   
        return "login";
    }
    @RequestMapping("/login")
    public String login(HttpSession session, String username, String password, Model model){
          
   
        //把用户信息存入session
        session.setAttribute("userinfo", username);
        model.addAttribute("username", username);
        return "main";

    }
    @RequestMapping("/remove")
    public String remove(HttpSession session){
          
   
        session.removeAttribute("userinfo");
        return "main";

    }
}

3.jsp界面

①登录

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
    <%--WEB-INF下的所有页面或者资源只能通过controller和servlet进行访问--%>
</head>
<body>
        <h1>登录界面</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
            用户名:<input type="text" name="username"/>
            <br/>
            密码:  <input type="password" name="password"/>
            <br/>
            <input type="submit" value="提交"/>
        </form>
</body>
</html>

②首页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
        <h1>我是首页</h1>
        <span>${username}</span>
        <p>
            <a href="${pageContext.request.contextPath}/user/remove">注销</a>
        </p>
</body>
</html>

③索引页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1><a href="${pageContext.request.contextPath}/user/gologin">登录页面</a></h1>
  <h1><a href="${pageContext.request.contextPath}/user/main">首页</a></h1>
  </body>
</html>

一定要在application,xml内配置对于的拦截器信息 ④拦截器

import org.springframework.web.servlet.HandlerInterceptor;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.servlet.http.HttpSession;

public class logininterceptor implements HandlerInterceptor {
          
   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          
   
        HttpSession session= request.getSession();
        //放行,判断什么时候登录
        //登录页面放行
        if(request.getRequestURI().contains("gologin"))
        {
          
   
            return true;
        }
        if(request.getRequestURI().contains("login"))
        {
          
   
            return true;
        }
        if(session.getAttribute("userinfo")!=null){
          
   
            return true;
        }
        //判断什么时候没有登录
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }
}

17.文件上传与下载

1.文件上传 1.导入包

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.1</version>
</dependency>
<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>servlet-api</artifactId>
 <version>2.2</version>
</dependency>

2.springmvc.xml的文件上传配置

<!--文件上传配置-->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <!--请求的编码格式,必须和pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1-->
     <property name="defaultEncoding" value="utf-8"/>
     <!--上传文件大小上限,单位是字节-->
     <property name="maxUploadSize" value="10485760"/>
     <property name="maxInMemorySize" value="40960"/>
 </bean>

3.controller

①通过流的方式上传文件

@Controller
public class FileController {
          
   
    //采用流的方式上传文件
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
          
   
        //获得文件名
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
          
   
            return "文件不存在";
        }
        //上传文件保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
          
   
            realPath.mkdir();
        }
        //文件上传
        InputStream inputStream = file.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(new File(realPath, filename));
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len=inputStream.read(bytes))!=-1){
          
   
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        //关闭流
        outputStream.close();
        inputStream.close();
        return "上传完毕";
    }
}

②.使用file.Transto上传文件

@Controller
public class FileController {
          
   
    //采用file.Transto上传文件
    @RequestMapping("/upload2")
    @ResponseBody
    public String upload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
          
   
        //上传文件保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
          
   
            realPath.mkdir();
        }
        //transferTo将文件写入磁盘,参数传入一个文件
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
        return "上传完毕";
    }
}

2.文件下载

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.*;
@Controller
public class DownloadController {
          
   
    @RequestMapping("/download2")
    public String download(HttpServletRequest request, HttpServletResponse response) {
          
   
        String fileName = "1.png";
        System.out.println(fileName);
        response.setContentType("text/html;charset=utf-8");
        try {
          
   
            request.setCharacterEncoding("UTF-8");//设定请求字符编码
        } catch (UnsupportedEncodingException e1) {
          
   
            e1.printStackTrace();
        }
        BufferedInputStream bis = null;//创建输入输出流
        BufferedOutputStream bos = null;
        String realPath = request.getSession().getServletContext().getRealPath("/") + "upload/";//获取文件真实路径
        System.out.println(realPath);
        String downLoadPath = realPath + fileName;
        System.out.println(downLoadPath);
        try {
          
   
            long fileLength = new File(downLoadPath).length();//获取文件长度
            //设置响应头信息;【固定的不用记,保存即可】
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));//创建输入输出流实例
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];//创建字节缓冲大小
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
          
   
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
          
   
            e.printStackTrace();
        } finally {
          
   
            if (bis != null)
                try {
          
   
                    bis.close();//关闭输入流
                } catch (IOException e) {
          
   
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            if (bos != null)
                try {
          
   
                    bos.close();//关闭输出流
                } catch (IOException e) {
          
   
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return null;
    }
}

之后会更新springboot和vue。

经验分享 程序员 微信小程序 职场和发展