Javaweb-Spring mvc 文件上传

文件上传

三要素

  1. 表单
  2. 提交方式为post
  3. 表单enctype时多部分表单形式

范例

项目结构

Javaweb-Spring mvc 文件上传_第1张图片

单文件步骤

  1. 创建测试表单upload.jsp
<%--
  Created by IntelliJ IDEA.
  User: Zsy
  Date: 2020/8/9
  Time: 14:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/user/upload" method="post" enctype="multipart/form-data">

    <input type="text" name="username"> <br>
    <input type="file" name="file"><br>
    <input type="submit" value="submit">
</form>

</body>
</html>

  1. 在spring mvc xml配置文件上传解析器
<!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="500000"/>
    </bean>
  1. 编写控制层代码
 @RequestMapping(value="/upload")
    @ResponseBody
    public void testFileUpload(String username, MultipartFile file) throws IOException {
        System.out.println(username);
        file.transferTo(new File("F:\\test\\"+file.getOriginalFilename()));
    }
  1. 测试

Javaweb-Spring mvc 文件上传_第2张图片
Javaweb-Spring mvc 文件上传_第3张图片

多文件上传

步骤

  1. 在原先的jsp文件添加一个表单

<form action="${pageContext.request.contextPath}/user/upload2" method="post" enctype="multipart/form-data">

    <input type="text" name="username"> <br>
    <input type="file" name="uploadFile"><br>
    <input type="file" name="uploadFile"><br>
    <input type="submit" value="submit">
</form>
  1. 添加多文件上传控制器
  @RequestMapping(value="/upload2")
    @ResponseBody
    public void testMultiFileUpload(String username, MultipartFile[] uploadFile) throws IOException {
        System.out.println(username);
        for (MultipartFile file : uploadFile) {
            System.out.println(file.getOriginalFilename());
            file.transferTo(new File("F:\\test\\"+file.getOriginalFilename()));
        }
    }

spring mvc拦截器

作用

用于预处理和后处理,即将拦截器按一定顺序结成一条链,这条链称为拦截器链。在访问拦截器方法或字段时,拦截器中的拦截器就会按照顺序被调用,拦截器也是AOP思想的具体实现

与传统过滤器的区别

Javaweb-Spring mvc 文件上传_第4张图片

拦截器入门案例

步骤

  1. 编写测试网页
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>hello ${username}</h1>
</body>
  1. 编写拦截器
    代码如下所示,这里控制器做了个判断,若请求的user为root则返回true,即这个请求可以通过,若为false则跳转到error页面
    postHandle在目标方法执行之后 视图对象返回之前执行,所以笔者在这里修改了username的值,最后响应的usernmae是rose而不是jack
package com.study.interceptor;


/**
 * Created by Zsy on 2020/8/9.
 */
public class myInterceptor implements HandlerInterceptor {


    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle。。。。。");
        String param = request.getParameter("user");
        if ("root".equals(param))
            return true;


        request.getRequestDispatcher("/error.jsp").forward(request, response);
        return false;
    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        modelAndView.addObject("username", "rose");
        System.out.println("postHandle........");
    }


    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("afterCompletion....");
    }
}

  1. 配置拦截器

    <!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--对哪些资源执行拦截操作-->
            <mvc:mapping path="/**"/>
            <bean class="com.study.interceptor.myInterceptor"/>
        </mvc:interceptor>

    </mvc:interceptors>

  1. 编写测试控制器
  @RequestMapping(value = "/login")
    @ResponseBody
    public ModelAndView testInterceptor() {

        System.out.println("目标资源执行......");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username","jack");
        modelAndView.setViewName("success");
        return modelAndView;
    }
  1. 测试
    Javaweb-Spring mvc 文件上传_第5张图片

spring mvc异常处理机制

过程图解

如下图所示,系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理

Javaweb-Spring mvc 文件上传_第6张图片

演示范例

非自定义异常处理器配置范例

步骤

  1. 业务层编写错误代码
package com.study.service.impl;

import com.study.exception.MyException;
import com.study.service.UserService;
import com.study.dao.UserDao;

/**
 * Created by Zsy on 2020/8/5.
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void save() {
        userDao.save();
    }


    public void ex1() {
        System.out.println("抛出类型转换异常....");
        Object str = "zhangsan";
        Integer num = (Integer)str;
    }



    public void ex2() throws MyException {
        System.out.println("自定义异常....");
        throw new MyException();
    }
}

  1. 控制层调用这些作死的代码
 @RequestMapping(value = "/ex1")
    @ResponseBody
    public void testException(){
        service.ex1();
    }
  1. spring-mvc.xml配置异常处理器
 <!--配置异常处理器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!--<property name="defaultErrorView" value="error"/>-->
        <property name="exceptionMappings">
            <map>
                <entry key="java.lang.ClassCastException" value="error"/>
                <entry key="com.itheima.exception.MyException" value="error"/>
            </map>
        </property>
    </bean>
  1. 编写错误网页
<%--
  Created by IntelliJ IDEA.
  User: Zsy
  Date: 2020/8/9
  Time: 14:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
error
</body>
</html>

  1. 测试
    Javaweb-Spring mvc 文件上传_第7张图片

自定义异常处理器配置范例

步骤

  1. 编写自定义异常处理器
package com.study.resolver;





public class MyExceptionResolver implements HandlerExceptionResolver {

    /*
       参数Exception:异常对象
       返回值ModelAndView:跳转到错误视图信息
    */
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
        ModelAndView modelAndView=new ModelAndView();
        System.out.println("error catch");
        if (e instanceof MyException)
            modelAndView.addObject("type","myException");
        else
            modelAndView.addObject("type","otherException");
        modelAndView.setViewName("error");

        return modelAndView;
    }



}

  1. 编写错误测试jsp
<%--
  Created by IntelliJ IDEA.
  User: Zsy
  Date: 2020/8/9
  Time: 14:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<html>
<head>
    <title>Title</title>
</head>
<body>


<h1> error type ${type}</h1>
error
</body>
</html>

  1. 配置自定义拦截器,注意将之前配置好的spring异常处理器去掉
    Javaweb-Spring mvc 文件上传_第8张图片
  2. 测试结果
    Javaweb-Spring mvc 文件上传_第9张图片

你可能感兴趣的:(Javaweb,过滤器,java,spring,tomcat,struts2)