Spring MVC回顾(1)--上传案例

Spring MVC回顾–上传案例

配置SringMVC组件
  1. 创建spring mvc需要导入的依赖
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.0.2.RELEASE</version>
</dependency>
  1. 配置web.xml时,需要优先配置DispatcherServlet
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!--初始化时,一并加载springMVC的配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC-config.xml</param-value>
    </init-param>
    <!--加载优先级 设置成1-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!--从这里接收用户请求,请求路径为“/”,意思就是可以拦截任何请求,然后映射到上面dispatcherServlet,创建
      dispatcherServlet对象
  -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  1. jsp页面的头信息
<!--处理乱码-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  1. SpringMVC的配置文件中需要导入的约束空间
<?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
      http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</bean>
  1. 在SpringMVC配置文件中配置如下这个信息时,它会自动加载处理器映射器(RequestMappingHandlerMapping),处理器适配器(RequestMappingHandlerAdapter)
  <mvc:annotation-driven>
  1. Spring MVC的各个组件中,处理器映射器、处理器适配器、视图解析器并称三大组件

    • 核心是前端控制器DispatcherServlet
  2. 处理请求编码乱码

    //配置解决中文乱码的过滤器,任何请求都可以拦截
    <filter>
      <filter-name>characterEncodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      //找到这个MVC提供的设置编码类,初始化参数
      <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
      </init-param>
    </filter>
      //拦截请求 拦截到请求后根据名字找到上面的filter
    <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/星号</url-pattern>
    </filter-mapping>
相关注解
  1. @RequestMapping:建立请求URL和处理请求方法之间的对应关系
  2. 如何获取请求,传入参数即可
    • HttpServletRequest request,HttpServletResponse response
    • request.getSession()
加载响应
  1. archetypeCatalog internal

  2. ModelAndView实际上跟String一样

  3. web.xml配置的前端控制器会拦截所有的请求,在spring配置中解决这个问题

    • 问题:所有请求都给拦截,因此静态资源也给拦截,不能访问
    • springmvc配置文件中配置
//js不拦截拦截
<mvc:resources mapping="/js/**" location="/js/**"/>
//样式不拦截
<mvc:resources mapping="/css/**" location="/css/**"/>
//图片资源不拦截
<mvc:resources mapping="/images/**" location="/images/**"/>
Spring mvc的文件上传
文件上传前提
  1. form表单的enctype取值必须是:multipart/form-data

    • 默认是:application/x-www-form-urlencoded
    • enctype:是表单请求正文的类型
  2. method属性取值必须是post

  3. 提供一个文件选择域

借助第三方组件实现文件上传
  1. 使用commons-fileupload组件实现文件上传
  2. 还需要导入commons-io,这个包不属于上传组件开发包,但是他是上传包的依赖包
传统方法上传文件
  1. 页面写form表单
<h3>文件上传</h3>
<form action="/fileupload1" method="post" enctype="multipart/form-data">
    <input type="file" name="upload"><br>
    <input type="submit" value="上传">
</form>
  1. Controller
/**
 * 文件上传
 表单提交文件,所有的数据都会被封装到request对象中。
 解析request,然后拿到文件。直接加参数HttpServletRequest request
 request.getSession()拿到最大的session对象
 request.getSession().getServletContext()拿到最大的域对象
 request.getRealPath() 这个表示的是web内容里的路径,参数具体到路径
 * @return
 */
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception{
    //1. 从request中获取信息
    String path = request.getSession().getServletContext().getRealPath("/uploads/");

    //2. 判断文件夹是否存在,如果不存在,创建文件夹
    File file = new File(path);
    if(!file.exists()){
        file.mkdir();
    }

    //3. 解析request对象,获取上传的文件,组件中的类
    /**
      创建一个磁盘临时空间,暂时存放从request中取到的数据
      创建文件上传对象,用于存储文件的操作
    */
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    //4. 解析request

    List<FileItem> fileItems = upload.parseRequest(request);

    //遍历
    for (FileItem fileItem : fileItems) {
        //判断当前文件是否是上传文件
        if(fileItem.isFormField()){
            System.out.println("不是上传文件");
        }else{
            //是上传文件
            //1. 获取文件名
            String fileName = fileItem.getName();
            //2. 使用UUID替换成乱码
            String uuid = UUID.randomUUID().toString().replace("-","");
            String fileName2 = uuid + "_" + fileName;
            //写入
            fileItem.write(new File(path,fileName2));
            //删除临时文件
            fileItem.delete();
        }
    }
    return "success";
}
Spring MVC的提供的上传方式
  1. commons-fileupload和commons-io

  2. spring配置文件中配置文件解析器对象

//配置文件解析器对象
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"/>
</bean>
  1. controller中写方法,参数两个一个request,一个MultipartFile upload
@RequestMapping("/fileupload2")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
    //1. 配置好了文件解析对象,不需要对request取出的文件进行解析
    String path = request.getSession().getServletContext().getRealPath("/uploads/");
    //2. 判断目录是否存在
    File file = new File(path);
    if(!file.exists()){
        file.mkdir();
    }

    //3. 设置好名字
    String originalFilename = upload.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replace("-","");
    originalFilename = uuid + "-" + originalFilename;

    //4. 使用upload完成上传
    upload.transferTo(new File(path,originalFilename));
    return "success";
}
Spring MVC跨服务器上传
  1. 上传资源一般是上传到另一个专门存放数据的服务器上,因此需要再导入两个jar包
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-core</artifactId>
  <version>1.18.1</version>
</dependency>

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-client</artifactId>
  <version>1.18.1</version>
</dependency>
  1. 配置文件解析器对象
  2. 前端不可少的form表单
  3. controller方法
@RequestMapping("/fileupload3")
public String fileuoload3(MultipartFile upload) throws Exception {
    System.out.println("跨服务器文件上传...");

    // 定义上传文件服务器路径
    String path = "http://localhost:9090/uploads/";

    // 说明上传文件项
    // 获取上传文件的名称
    String filename = upload.getOriginalFilename();
    // 把文件的名称设置唯一值,uuid
    String uuid = UUID.randomUUID().toString().replace("-", "");
    filename = uuid+"_"+filename;

    // 创建客户端的对象
    Client client = Client.create();

    // 和图片服务器进行连接
    WebResource webResource = client.resource(path + filename);

    // 上传文件
    webResource.put(upload.getBytes());

    return "success";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值