Day21-SSM项目整合

SSM整合项目

  1. 新建数据库

    CREATE DATABASE ssmbuild;

    USE `ssmbuild`

    DROP TABLE IF EXISTS `books`;

    CREATE TABLE `books`(
    `bookID` INT (10) NOT NULL AUTO_INCREMENT COMMENT '书id',
    `bookName` VARCHAR (100) NOT NULL COMMENT '书名',
    `bookCounts` INT (11) NOT NULL COMMENT '数量',
    `detail` VARCHAR (200) NOT NULL COMMENT '描述',
    KEY `bookID` (`bookID`)
    )ENGINE=INNODB DEFAULT CHARSET=utf8

    INSERT INTO `books`(`bookID`, `bookName`, `bookCounts`,`detail`) VALUES
    (1,'Java',1,'从入门到放弃'),
    (2, 'MySQL',10,'MySQL从删库到跑路'),
    (3,'Linux',5,'从进门到进牢');
  2. 新建maven项目

  3. 导包(junit、数据库驱动、连接池【c3p0】、servlet、jsp、mybatis、mybatis-spring、spring、json)

     <dependencies>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    </dependency>
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
    </dependency>
    <dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.5</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.1-b03</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.13</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.7</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.15.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.20</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
    </dependency>
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.32</version>
    </dependency>
    </dependencies>

    <build>
    <resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    </resources>
    </build>
    1. 连接数据库

    2. 把各层包和xml文件建好

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "https://mybatis.org/dtd/mybatis-3-config.dtd">
      <configuration>

      <settings>
      <setting name="logImpl" value="STDOUT_LOGGING"/>
      </settings>

      <typeAliases>
      <package name="com.lsq.pojo"/>
      </typeAliases>

      <mappers>
      <mapper class="com.lsq.dao.BookMapper"/>
      </mappers>
      </configuration>
    3. 创建数据库配置文件(注意:数据库是8.0以后的版本,配置url时需要加一个时区配置)

      driver=com.mysql.cj.jdbc.Driver
      url=jdbc:mysql://localhost:3306/ssmbulid?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
      username=root
      password=12345678
    4. 创建spring-dao.xml,整合dao层

      <?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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      https://www.springframework.org/schema/context/spring-context.xsd">

      <!--1.关连数据库配置文件-->
      <context:property-placeholder location="classpath:db.properties"/>
      <!--2.连接池-->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
      <property name="driverClass" value="${jdbc.driver}"/>
      <property name="jdbcUrl" value="${jdbc.url}"/>
      <property name="user" value="${jdbc.username}"/>
      <property name="password" value="${jdbc.password}"/>

      <property name="maxPoolSize" value="30"/>
      <property name="minPoolSize" value="10"/>
      <property name="autoCommitOnClose" value="false"/>
      <property name="checkoutTimeout" value="10000"/>
      <property name="acquireRetryAttempts" value="2"/>
      </bean>
      <!--3.sqlSessionFactory-->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="configLocation" value="classpath:mybatis-config.xml"/>
      </bean>

      <!--4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
      <property name="basePackage" value="com.lsq.dao"/>
      </bean>
      </beans>
    5. 创建spring-service.xml,整合service层

      <?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:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://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/aop
      https://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/cache/spring-tx.xsd">

      <!--1.扫描service下的包-->
      <context:component-scan base-package="com.lsq.service"/>

      <!--2.将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
      <bean id="bookServiceImpl" class="com.lsq.service.BookServiceImpl">
      <property name="bookMapper" ref="bookMapper"/>
      </bean>
      <!--3.声明式事务配置-->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
      </bean>

      <tx:advice id="txAdvice" transaction-manager="transactionManager">
      <tx:attributes>
      <tx:method name="add" propagation="REQUIRED"/>
      <tx:method name="delete" propagation="REQUIRED"/>
      <tx:method name="update" propagation="REQUIRED"/>
      <tx:method name="select" read-only="true"/>
      <tx:method name="*" propagation="REQUIRED"/>
      </tx:attributes>
      </tx:advice>

      <aop:config>
      <aop:pointcut id="pointcut" expression="execution(* com.lsq.dao.*(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
      </aop:config>
      </beans>
    6. 配置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">
      <!--DispatchServlet-->
      <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.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>encodingFilter</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>encodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
      </filter-mapping>

      <session-config>
      <session-timeout>15</session-timeout>
      </session-config>
      </web-app>
    7. 创建spring-mvc.xml,整合controller层

      <?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:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc
      https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

      <!--1.注解驱动-->
      <mvc:annotation-driven/>
      <!--2.静态资源过滤-->
      <mvc:default-servlet-handler/>
      <!--3.扫描包:controller-->
      <context:component-scan base-package="com.lsq.controller"/>
      <!--4.视图解析器-->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"/>
      <property name="suffix" value=".jsp"/>
      </bean>
      </beans>
    8. 配置applicationContext.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"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc
      https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

      <import resource="spring-dao.xml"/>
      <import resource="spring-serivce.xml"/>
      <import resource="spring-mvc.xml"/>

      </beans>
    9. dao-service-controller层开发

    AJax

    1. 编写一个cotroller

      package com.lsq.controller;

      import com.lsq.service.UserService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;

      import javax.jws.WebParam;

      @RestController
      @RequestMapping("/user")
      public class UserController {

      @Autowired
      private UserService userService;

      @RequestMapping("/login")
      public String loginController(String name, String pwd) {
      String msg = "";
      if (name != null) {
      if ("admin".equals(name)) {
      msg = "ok";
      } else {
      msg = "用户名错误";
      }
      }

      if (pwd != null) {
      if ("12345678".equals(pwd)) {
      msg = "ok";
      } else {
      msg = "密码错误";
      }
      }
      return msg;
      }
      }
    2. 编写前端页面

      <%--
      Created by IntelliJ IDEA.
      User: liushaoqin
      Date: 2023/8/6
      Time: 19:06
      To change this template use File | Settings | File Templates.
      --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
      <title>$Title$</title>
      <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
      <script>
      function a1(){
      $.post({
      url:"${pageContext.request.contextPath}/user/login",
      data:{'name':$("#username").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}/user/login",
      data:{'pwd':$("#password").val()},
      success:function (data){
      if (data.toString()=='ok'){
      $("#pwdInfo").css("color","green");
      }else {
      $("#pwdInfo").css("color","red");
      }
      $("#pwdInfo").html(data);
      }
      });
      }
      </script>
      </head>
      <body>
      <p>
      用户名:<input type="text" id="username" onblur="a1()"/>
      <span id="userInfo"></span>
      </p>
      <p>
      密码:<input type="password" id="password" onblur="a2()"/>
      <span id="pwdInfo"></span>
      </p>
      </body>
      </html>
    3. 编写ajax函数

       function a1(){
      $.post({
      url:"${pageContext.request.contextPath}/user/login",
      data:{'name':$("#username").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}/user/login",
      data:{'pwd':$("#password").val()},
      success:function (data){
      if (data.toString()=='ok'){
      $("#pwdInfo").css("color","green");
      }else {
      $("#pwdInfo").css("color","red");
      }
      $("#pwdInfo").html(data);
      }
      });
      }
    4. 导入jquery , 可以使用在线的CDN , 也可以下载导入

      <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>

    拦截器

    • SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。

    • 拦截器是AOP思想的具体应用

    1. 拦截器配置

      <!--拦截器配置-->
      <!--关于拦截器的配置-->
      <mvc:interceptors>
      <mvc:interceptor>
      <!--/** 包括路径及其子路径-->
      <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
      <!--/admin/** 拦截的是/admin/下的所有-->
      <mvc:mapping path="/**"/>
      <!--bean配置的就是拦截器-->
      <bean class="com.lsq.config.MyInterceptor"/>
      </mvc:interceptor>
      </mvc:interceptors>
    2. 继承拦截器,编写MyInterceptor类

      package com.lsq.config;

      import org.springframework.web.servlet.HandlerInterceptor;
      import org.springframework.web.servlet.ModelAndView;

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

      public class MyInterceptor implements HandlerInterceptor{
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      System.out.println("============执行前==========");
      return HandlerInterceptor.super.preHandle(request, response, handler);
      }

      @Override
      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      System.out.println("============执行后==========");
      HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
      }

      @Override
      public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      System.out.println("============清理==========");
      HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
      }
      }
    3. 编写controller类

      package com.lsq.controller;

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

      @RestController
      public class InterceptorController {
      @RequestMapping("/t1")
      public String test(){
      System.out.println("InterceptorController-->执行了");
      return "OK";
      }
      }
    4. 执行结果

    用户判断验证

    1. 拦截器

      package com.lsq.config;

      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 {
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      HttpSession session = request.getSession();
      if (request.getRequestURI().contains("Login")){
      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 HandlerInterceptor.super.preHandle(request, response, handler);
      }
      }
    2. cotroller

      package com.lsq.controller;

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

      import javax.servlet.http.HttpSession;

      @Controller
      public class InterceptorController {

      @RequestMapping("/main")
      public String main(){
      return "main";
      }

      @RequestMapping("/goLogin")
      public String goLogin(){
      return "login";
      }

      @RequestMapping("/login")
      public String login(HttpSession session,String username, String password,Model model){
      session.setAttribute("userInfo",username);
      model.addAttribute("username",username);
      return "main";
      }

      @RequestMapping("/loginOut")
      public String loginOut(HttpSession session){
      session.removeAttribute("userInfo");
      return "redirect:index.jsp";
      }
      }
    3. 首页

      <%--
      Created by IntelliJ IDEA.
      User: liushaoqin
      Date: 2023/8/7
      Time: 00:20
      To change this template use File | Settings | File Templates.
      --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
      <title>未登陆用户拦截</title>
      </head>
      <body>
      <h1>
      <a href="${pageContext.request.contextPath}/main">首页</a>
      </h1>
      <h1>
      <a href="${pageContext.request.contextPath}/goLogin">登陆</a>
      </h1>
      </body>
      </html>
    4. 登陆页

      <%--
      Created by IntelliJ IDEA.
      User: liushaoqin
      Date: 2023/8/6
      Time: 21:23
      To change this template use File | Settings | File Templates.
      --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
      <title>登陆页面</title>
      </head>
      <body>
      <form action="${pageContext.request.contextPath}/login" method="post">
      用户名:<input type="text" name="username"/>
      密码:<input type="password" name="password"/>
      <input type="submit" value="提交">
      </form>
      </body>
      </html>
    5. 主页

      <%--
      Created by IntelliJ IDEA.
      User: liushaoqin
      Date: 2023/8/6
      Time: 21:23
      To change this template use File | Settings | File Templates.
      --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
      <title>首页</title>
      </head>
      <body>
      <p>
      <h1>首页</h1>
      <span>${sessionScope.userInfo}</span>
      </p>
      <p>
      <a href="${pageContext.request.contextPath}/loginOut" >注销</a>
      </p>
      </body>
      </html>

    文件上传和下载

    • 文件上传

    1. 前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;

      <form action="" enctype="multipart/form-data" method="post">
      <input type="file" name="file"/>
      <input type="submit">
      </form>
    2. 导入依赖包

      <!--文件上传-->
      <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
      </dependency>
      <!--servlet-api导入高版本的-->
      <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      </dependency>
    3. 配置bean:multipartResolver,bena的id必须为:multipartResolver , 否则上传文件会报400的错误

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

      <form action="/upload" enctype="multipart/form-data" method="post">
      <input type="file" name="file"/>
      <input type="submit" value="upload">
      </form>
    5. 编写cotroller文件

      package com.lsq.controller;

      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.multipart.commons.CommonsMultipartFile;

      import javax.servlet.http.HttpServletRequest;
      import java.io.*;

      @Controller
      public class FileController {
      //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
      //批量上传CommonsMultipartFile则为数组即可
      @RequestMapping("/upload")
      public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

      //获取文件名 : file.getOriginalFilename();
      String uploadFileName = file.getOriginalFilename();

      //如果文件名为空,直接回到首页!
      if ("".equals(uploadFileName)){
      return "redirect:/index.jsp";
      }
      System.out.println("上传文件名 : "+uploadFileName);

      //上传路径保存设置
      String path = request.getServletContext().getRealPath("/upload");
      //如果路径不存在,创建一个
      File realPath = new File(path);
      if (!realPath.exists()){
      realPath.mkdir();
      }
      System.out.println("上传文件保存地址:"+realPath);

      InputStream is = file.getInputStream(); //文件输入流
      OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

      //读取写出
      int len=0;
      byte[] buffer = new byte[1024];
      while ((len=is.read(buffer))!=-1){
      os.write(buffer,0,len);
      os.flush();
      }
      os.close();
      is.close();
      return "redirect:/index.jsp";
      }
      }

      采用file.Transto 来保存上传的文件

      /*
      * 采用file.Transto 来保存上传的文件
      */
      @RequestMapping("/upload2")
      public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

      //上传路径保存设置
      String path = request.getServletContext().getRealPath("/upload");
      File realPath = new File(path);
      if (!realPath.exists()){
      realPath.mkdir();
      }
      //上传文件地址
      System.out.println("上传文件保存地址:"+realPath);

      //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
      file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

      return "redirect:/index.jsp";
      }
    • 文件下载

    1. 设置 response 响应头

    2. 读取文件 -- InputStream

    3. 写出文件 -- OutputStream

    4. 执行操作

    5. 关闭流 (先开后关)

    @RequestMapping(value="/download")
    public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
    //要下载的图片地址
    String path = request.getServletContext().getRealPath("/upload");
    String fileName = "基础语法.jpg";

    //1、设置response 响应头
    response.reset(); //设置页面不缓存,清空buffer
    response.setCharacterEncoding("UTF-8"); //字符编码
    response.setContentType("multipart/form-data"); //二进制传输数据
    //设置响应头
    response.setHeader("Content-Disposition",
    "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

    File file = new File(path,fileName);
    //2、 读取文件--输入流
    InputStream input=new FileInputStream(file);
    //3、 写出文件--输出流
    OutputStream out = response.getOutputStream();

    byte[] buff =new byte[1024];
    int index=0;
    //4、执行 写出操作
    while((index= input.read(buff))!= -1){
    out.write(buff, 0, index);
    out.flush();
    }
    out.close();
    input.close();
    return null;
    }
    1. 前端jsp页面

    <a href="/download">点击下载</a>
posted @ 2023-08-07 01:33  仓鼠的气垫床  阅读(12)  评论(0编辑  收藏  举报