JAVAEE look at the framework 07-SpringMVC file upload and exception handling mechanism

1. SpringMVC file upload

1.1 Three elements of file upload

  1. Must contain form item type = "file"

  2. The form submission method is post

  3. The enctype attribute of the form is a multi-part form, and enctype = "multipart / form-data"

<h3>用户注册-文件上传</h3>
<form action="fu" method="post" enctype="multipart/form-data">
    姓名: <input type="text" name="name" /> <br/>
    年龄: <input type="text" name="age" /> <br/>
    头像: <input type="file" name="headImg" /> <br/>
    <input type="submit" value="注册">
</form>

1.2 File upload

1.2.1 Add dependency

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

1.2.2 Configuration file parser

note:

  1. Configure file parser in SpringMVC.xml

  2. The ID of the file parser must be " multipartResolver "

<!--配置文件上传解析器-->
<bean id="multipartResolver"
    		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--上传文件的编码类型-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--文件上传的总大小(10M)-->
    <property name="maxUploadSize" value="10485600"/>
    <!--单个文件的大小(5M)-->
    <property name="maxUploadSizePerFile" value="5242800"/>
</bean>

1.2.3 Use

note:

1. In the method parameter of Controller, write the parameter of MultipartFile type.

2. The parameter name must be consistent with the name attribute of the "file upload item" in the form

@RequestMapping("/upload")
@ResponseBody
public void fileUpload(String name, int age, MultipartFile headImg) throws IOException {

}

1.2.4 Save file

@RequestMapping("/upload")
@ResponseBody
public void fileUpload(String name, int age, MultipartFile headImg) throws IOException {
    //获取普通项    
    System.out.println(name);
    System.out.println(age);
    
	//处理文件上传项
    //0.判断文件是否为空
    if (!headImg.isEmpty()) {
        //1.获取上传文件的文件名称
        String filename = headImg.getOriginalFilename();  //6b.jpeg
        //2.处理文件名
        filename = new Date().getTime() + "_" + filename; //1573701830347_6b.jpeg
        //3.保存该文件
        headImg.transferTo(new File("d:\\" + filename));
    }
}

1.2 Multi-file upload

1.2.1 Form code

<form action="/upload" method="post" enctype="multipart/form-data">
    姓名: <input type="text" name="name" /> <br/>
    图片1: <input type="file" name="uploadFile"><br/>
    图片2: <input type="file" name="uploadFile"><br/>
    <input type="submit" value="提交">
</form>

1.2.2 Background code

note:

When uploading multiple files, just change the MultipartFile type to an array.

However, the name of the array must be the same as the name attribute of the "file upload item" in the form

@RequestMapping("/upload")
@ResponseBody
public void fileUpload(String name, MultipartFile[] uploadFile) throws IOException {
    
}

2. SpringMVC interceptor

2.1 Interceptor overview

The interceptor class of Spring MVC, similar to the Filter in the development of Servlet, is used to pre-process and post-process the processor.

2.2 Use of interceptors

2.2.1 Create a custom interceptor

Define a class, implement the HandlerInterceptor interface, and override the preHandle method

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 		Object handler) {
        System.out.println("MyInterceptor拦截器执行了...");
        //返回true表示放行,返回false表示不放行
        return true;
    }
}

2.2.2 Configure custom interceptor

In the springmvc configuration file. Configure the interceptor

<!--配置拦截器-->
<mvc:interceptors>
    <mvc:interceptor>
        <!--拦截所有请求-->
        <mvc:mapping path="/**"/>   
        <!--放行"/user/login"-->
        <mvc:exclude-mapping path="/user/login"/>	
        <!--配置拦截器类-->
        <bean class="com.itheima.interceptor.LoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

2.2.3 Matters needing attention

1. The interceptor's interception rules, for those requests that enter the springmvc process.

2. There are three methods in the HandlerInterceptor interface:

PreHandler is executed before the target method is executed

PostHandle is executed after the target method is executed and before the view object returns

AfterCompletion is executed after the process is completed

3. There can be multiple interceptors, forming an interceptor chain

3. SpringMVC exception handling mechanism

3.1 The idea of ​​exception handling

When an exception occurs in Dao, Service and Controller of the system, throws Exception is thrown upward, and finally the SpringMVC front-end controller is handed over to the exception handler for exception handling, as shown below:

[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-vDB8rRTY-1585558986178) (img / 7.png)]

3.2 Two methods of exception handling

① Simple exception handler SimpleMappingExceptionResolver

② Customize your own exception handler and implement the HandlerExceptionResolver interface

A. Simple exception handler

Simple exception processor is a processor interface made by springmvc in advance, and can be used directly by configuring

<!--配置简单映射异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <!--默认错误视图-->
    <property name="defaultErrorView" value="forward:/error/errorMsg.jsp"/>       
    <property name="exceptionMappings">
        <map>
            <!--除零异常视图-->
            <entry key="ArithmeticException" value="forward:/error/arithmetic.jsp"/>  
            <!--类型转换异常视图-->
            <entry key="ClassCastException" value="forward:/error/classCast.jsp"/>       
        </map>
    </property>
</bean>

B. Custom exception handler

Define a class, implement the HandlerExceptionResolver interface, and rewrite the method

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        //判断出现的异常是什么异常
        if (ex instanceof ArithmeticException){
            //如果是除零异常
            //跳转到"forward:/error/arithmetic.jsp"
            modelAndView.setViewName("forward:/error/arithmetic.jsp");
        }else if (ex instanceof ClassCastException){
            //如果类型转换异常
            //跳转到"forward:/error/classCast.jspp"
            modelAndView.setViewName("forward:/error/classCast.jsp");
        }else{
            //其他异常
            //就跳转到exceptionPage页面
            modelAndView.setViewName("forward:/error/exceptionPage.jsp");
        }

        return modelAndView;
    }
}

Configure exception handler

<bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>
Published 78 original articles · praised 30 · visits 3636

Guess you like

Origin blog.csdn.net/ZMW_IOS/article/details/105203349