转发与重定向和文件上传

在这里插入图片描述

转发与重定向

重定向与Flash属性
在一个请求处理方法Action中如果返回结果为“index”字符则表示转发到视图index,有时候我们需要重定向,则可以在返回的结果前加上一个前缀“redirect:”,可以重定向到一个指定的页面,也可以是另一个action,示例代码如下:
在这里插入图片描述
}
在这里插入图片描述
当请求http://localhost:8080/MVCTest/foo/action3时运行结果如下:
在这里插入图片描述
在action3中返回的结果为redirect:action2,则表示重定向到action2这个请求处理方法,所有重定向都是以当前路径为起点的,请注意路径。在action3向model中添加了名称message的数据,因为重定向到action2中会发起2次请求,为了保持action3中的数据Spring MVC自动将数据重写到了url中。为了实现重定向时传递复杂数据,可以使用Flash属性,示例代码如下:
在这里插入图片描述
在这里插入图片描述
当访问action3时,首先创建了一个product产口对象,将该对象添加到了Flash属性中,在重定向后取出,个人猜测应该暂时将对象存入了Session中。当请求foo/action3时运行结果如下:
在这里插入图片描述
url地址已经发生了变化,product对象其实也已经被存入了model中,在action的视图中可以直接拿到。
1.4、转发
str=”forward : 路径”        请求转发到一个页面中
str=”forward : controller的映射”  请求转发到一个controller方法中
示例:
在这里插入图片描述
结果:
在这里插入图片描述
URL没有变化,数据存在可以直接使用。

文件上传

在Spring MVC中有两种实现上传文件的办法,第一种是Servlet3.0以下的版本通过commons-fileupload与commons-io完成的通用上传,第二种是Servlet3.0以上的版本的Spring内置标准上传,不需借助第3方组件。通用上传也兼容Servlet3.0以上的版本。
1.1、Servlet3.0以下的通过commons-fileupload上传
1.1.1、添加上传依赖包
因为需要借助第三方上传组件commons-fileupload与commons-io,所以要修改pom.xml文件添加依赖,依赖的内容如下:

下面展示一些 内联代码片


 		<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

1.1.2、新增上传页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>上传文件</title>
	</head>
<body>
	<h2>上传文件(支持多文件上传)</h2>
	<form action="fileSave" method="post"  enctype="multipart/form-data">
  <p>
        姓名:<input type="text" name="username"><br>
        文件:
        <input type="file" name="files"  multiple="multiple" />
        <%--<input type="file" name="files"  multiple="multiple" />--%>
        <%--<input type="file" name="files"  multiple="multiple" />--%>
   <p>
   	<button>提交</button>
   </p>
   <p>
     	${message}
   </p>
</form>
</body></html>

如果有成功上传,页面中有几个关键点要注意:method的值必为post;enctype必须为multipart/form-data,该类型的编码格式专门用于二进制数据类型;上传表单元素必须拥有name属性;
1.1.3、修改配置文件,增加上传配置
默认情总下Spring MVC对文件上传的视图内容是不能解析的,要配置一个特别的解析器解析上传的内容,修改springmvc-servlet.xml配置文件,增加如下配置内容:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize" value="10485760000" />
        <property name="maxInMemorySize" value="40960" />
    </bean>

增加了一个类型为CommonsMultipartResolver类型的解析器,各属性的意义:
defaultEncoding:默认编码格式
maxUploadSize:上传文件最大限制(字节byte)
maxInMemorySize:缓冲区大小
当Spring的前置中心控制器检查到客户端发送了一个多分部请求,定义在上下文中的解析器将被激活并接手处理。解析器将当前的HttpServletRequest包装成一个支持多部分文件上传的MultipartHttpServletRequest对象。在控制器中可以获得上传的文件信息。
在这里插入图片描述
CommonsMultipartResolver用于通用的文件上传,支持各种版本的Servlet。
StandardServletMultipartResolver用于Servlet3.0以上的版本上传文件。
4.1.4、增加控制器与Action

package com.zhangguo.springmvc51.controllers;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/up")
public class UpFileController {
    @RequestMapping(value="/fileSave",method=RequestMethod.POST)
    public String fileSave(Model model, @RequestParam MultipartFile[] files, HttpServletRequest request) throws Exception{
       String username=request.getParameter("username");
        System.out.println(username);
        //文件存放的位置
        String path=request.getServletContext().getRealPath("/files");
        String fileName=null;
        for (MultipartFile file : files) {
            fileName=file.getOriginalFilename();
            System.out.println(file.getOriginalFilename());
            File tempFile=new File(path, file.getOriginalFilename());
            if(!tempFile.exists()) {
                tempFile.mkdirs();
            }
            file.transferTo(tempFile);
        }
        System.out.println(path);
        model.addAttribute("path",path);
        model.addAttribute("fileName",fileName);
        return "upload";
    }
    /**
     * 跨服务器上传方式(了解)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload3")
    public String fileupload3(MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传...");

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

        //上传文件项
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
        //创建客户端对象
        Client client = Client.create();
        //和图片服务器进行连接
        WebResource webResource = client.resource(path + saveName);
        //上传文件
        webResource.put(upload.getBytes());
        return "success";
    }
}

注意这里定义的是一个数组,可以接受多个文件上传,如果单文件上传可以修改为MultipartFile类型。
4.1.5、测试运行
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值