SSM study notes eight (Spring-MVC file upload, interceptor, exception handling)

SpringMVC file upload

1-SpringMVC request-file upload-client form implementation (application)

The file upload client form needs to meet:

Form item type="file"

The form submission method is post

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

<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
        名称<input type="text" name="username"><br/>
        文件1<input type="file" name="uploadFile"><br/>
        <input type="submit" value="提交">
    </form>

2-SpringMVC request-file upload-the principle of file upload (understanding)

[External link image transfer failed, the source site may have an anti-hotlink mechanism, it is recommended to save the image and upload it directly (img-1XkjHByW-1611805784795)(./img/5.jpg)]

3-SpringMVC request-file upload-single file upload code implementation 1 (application)

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>

Configure multimedia parser

<!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UYF-8"/>
        <property name="maxUploadSize" value="500000"/>
    </bean>

background program

@RequestMapping(value="/quick22")
    @ResponseBody
    public void save22(String username, MultipartFile uploadFile) throws IOException {
    
    
        System.out.println(username);
       	System.out.println(uploadFile);
    }

4-SpringMVC request-file upload-single file upload code implementation 2 (application)

Complete file upload

@RequestMapping(value="/quick22")
    @ResponseBody
    public void save22(String username, MultipartFile uploadFile) throws IOException {
    
    
        System.out.println(username);
        //获得上传文件的名称
        String originalFilename = uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File("C:\\upload\\"+originalFilename));
    }

5-SpringMVC request-file upload-multiple file upload code implementation (application)

To upload multiple files, you only need to modify the page to multiple file upload items, and modify the method parameter MultipartFile type to MultipartFile[].

<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
        名称<input type="text" name="username"><br/>
        文件1<input type="file" name="uploadFile"><br/>
        文件2<input type="file" name="uploadFile"><br/>
        <input type="submit" value="提交">
    </form>
@RequestMapping(value="/quick23")
    @ResponseBody
    public void save23(String username, MultipartFile[] uploadFile) throws IOException {
    
    
        System.out.println(username);
        for (MultipartFile multipartFile : uploadFile) {
    
    
            String originalFilename = multipartFile.getOriginalFilename();
            multipartFile.transferTo(new File("C:\\upload\\"+originalFilename));
        }
    }

6-SpringMVC request-knowledge points (understanding, memory)

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-QorkJhYN-1611805784799)(.//img/6.jpg)]

SpringMVC interceptor

01-SpringMVC interceptor-the role of interceptor (understanding)

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

The interceptors are connected in a certain order into a chain, which is called the InterceptorChain (InterceptorChain). When accessing the intercepted method or field, the interceptors in the interceptor chain will be called in the order they were previously defined. The interceptor is also a concrete realization of the AOP idea.

02-SpringMVC interceptor-the difference between interceptor and filter (understanding, memory)

About the difference between interceptor and filter, as shown in the figure:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-d7jZDm80-1611805784801)(./img/1.png)]

03-SpringMVC Interceptor-Quick Start (Application)

The custom interceptor is very simple, only the following three steps:

①Create an interceptor class to implement the HandlerInterceptor interface

②Configure the interceptor

③Test the interception effect of the interceptor

Write an interceptor:

public class MyInterceptor1 implements HandlerInterceptor {
    
    
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
    
    
        System.out.println("preHandle.....");
}
    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    
    
System.out.println("postHandle...");
    }
    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    
    
        System.out.println("afterCompletion....");
    }
}

Configuration: Configure in the SpringMVC configuration file

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

Write a test program to test:

Write Controller, send request to controller, jump page

@Controller
public class TargetController {
    
    

    @RequestMapping("/target")
    public ModelAndView show(){
    
    
        System.out.println("目标资源执行......");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name","itcast");
        modelAndView.setViewName("index");
        return modelAndView;
    }

}

page

<html>
<body>
<h2>Hello World! ${name}</h2>
</body>
</html>

04-SpringMVC Interceptor-Quick Start Detailed Explanation (Application)

Under what circumstances will the interceptor execute the target resource after preprocessing, and under what circumstances will it not execute the target resource, and what is the execution order of the interceptor when there are multiple interceptors?

Write another interceptor 2,

public class MyInterceptor2 implements HandlerInterceptor {
    
    
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
    
    
        System.out.println("preHandle22222.....");
        return true;
    }

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

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

Configure Interceptor 2

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

in conclusion:

When the interceptor's preHandle method returns true, the target resource will be executed, if it returns false, the target resource will not be executed

In the case of multiple interceptors, the first configuration is executed first, and the second configuration is executed later

The method execution order in the interceptor is: preHandler-------target resource----postHandle---- afterCompletion

05-SpringMVC interceptor-knowledge summary (memory)

The method in the interceptor is explained as follows

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-V8ex6YfJ-1611805784807)(./img/2.png)]

06-SpringMVC Interceptor-User Login Authority Control Analysis (Understanding)

On the basis of the day06-Spring practice case: when the user is not logged in, the background menu cannot be accessed, click the menu to jump to the login page, and the background function can only be operated after the user logs in successfully

Demand map:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-dwmlNa4J-1611805784811)(./img/3.jpg)]

07-SpringMVC Interceptor-User Login Authority Control Code Implementation 1 (Application)

Judge whether the user is logged in essence: Judge whether there is a user in the session, if there is no login, log in first, and if it is already logged in, directly release the access to the target resource

First write the interceptor as follows:

public class PrivilegeInterceptor implements HandlerInterceptor {
    
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    
    
        //逻辑:判断用户是否登录  本质:判断session中有没有user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
    
    
            //没有登录
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return false;
        }
        //放行  访问目标资源
        return true;
    }
}

Then configure the interceptor: find the spring-mvc.xml of the project case and add the following configuration:

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

08-SpringMVC interceptor-user login permission control code implementation 2 (application)

Enter the user name and password on the login page, click login, and query through the user name and password. If the login is successful, the user information entity will be stored in the session, and then jump to the home page, if the login fails, continue back to the login page

Write login logic in UserController

@RequestMapping("/login")
    public String login(String username,String password,HttpSession session){
    
    
        User user = userService.login(username,password);
        if(user!=null){
    
    
            //登录成功  将user存储到session
            session.setAttribute("user",user);
            return "redirect:/index.jsp";
        }
        return "redirect:/login.jsp";
    }

The service layer code is as follows:

//service层
public User login(String username, String password) {
    
    
            User user = userDao.findByUsernameAndPassword(username,password);
            return user;
}

The dao layer code is as follows:

//dao层
 public User findByUsernameAndPassword(String username, String password) throws EmptyResultDataAccessException{
    
    
        User user = jdbcTemplate.queryForObject("select * from sys_user where username=? and password=?", new BeanPropertyRowMapper<User>(User.class), username, password);
        return user;
    }

At this time, I still can’t log in, because we need to let the interceptor release the login request url and add the configuration of resource exclusion

<!--配置权限拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--配置对哪些资源执行拦截操作-->
            <mvc:mapping path="/**"/>
            <!--配置哪些资源排除拦截操作-->
            <mvc:exclude-mapping path="/user/login"/>
            <bean class="com.itheima.interceptor.PrivilegeInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

09-SpringMVC Interceptor-User Login Authority Control Code Implementation 3 (Application)

If the JdbcTemplate.queryForObject object fails to query the data, it will throw an exception, causing the program to fail to achieve the expected effect. How to solve this problem?

Handle the exception from the dao layer in the business layer. If an exception occurs, the service layer returns null instead of throwing the exception to the controller

Therefore, modify the business layer code of the landing and add abnormal control

public User login(String username, String password) {
    
    
        try {
    
    
            User user = userDao.findByUsernameAndPassword(username,password);
            return user;
        }catch (EmptyResultDataAccessException e){
    
    
            return null;
        }
    }

1. SpringMVC exception handling mechanism

1.1 The idea of ​​exception handling

There are two types of exceptions in the system: Expected exceptions and RuntimeException. The former obtains exception information by capturing exceptions, and the latter mainly reduces the occurrence of runtime exceptions by means of standardized code development and testing.

The Dao, Service, and Controller of the system are all thrown upwards through throws Exception, and finally the SpringMVC front-end controller is handed over to the exception handler for exception handling, as shown in the following figure:

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-3RcCNKOD-1611805784814)(./img/%E5%9B%BE%E7%89%871.jpg) ]

1.2 Two ways of exception handling

① Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC

② Implement Spring's exception handling interface HandlerExceptionResolver to customize your own exception handler

1.3 Simple Exception Handler SimpleMappingExceptionResolver

SpringMVC has defined this type converter, and can be used according to the project situation to carry out the corresponding abnormal and view mapping configuration

<!--配置简单映射异常处理器-->
    <bean class=“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”>    <property name=“defaultErrorView” value=“error”/>   默认错误视图
    <property name=“exceptionMappings”>
        <map>		异常类型		                             错误视图
            <entry key="com.itheima.exception.MyException" value="error"/>
            <entry key="java.lang.ClassCastException" value="error"/>
        </map>
    </property>
</bean>

1.4 Custom exception handling steps

①Create an exception handler class to implement HandlerExceptionResolver

public class MyExceptionResolver implements HandlerExceptionResolver {
    
    
@Override
public ModelAndView resolveException(HttpServletRequest request, 
    HttpServletResponse response, Object handler, Exception ex) {
    
    
    //处理异常的代码实现
    //创建ModelAndView对象
    ModelAndView modelAndView = new ModelAndView(); 
    modelAndView.setViewName("exceptionPage");
    return modelAndView;
    }
}

② Configure exception handler

<bean id="exceptionResolver"        
      class="com.itheima.exception.MyExceptionResolver"/>

③Write abnormal page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
	<title>Title</title>
</head>
<body>
	这是一个最终异常的显示页面
</body>
</html>

④ Test abnormal jump

@RequestMapping("/quick22")
@ResponseBody
public void quickMethod22() throws IOException, ParseException {
    
    
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
    simpleDateFormat.parse("abcde");
}

1.5 Knowledge points

Exception handling method

配置简单异常处理器SimpleMappingExceptionResolver

自定义异常处理器

Custom exception handling steps

①创建异常处理器类实现HandlerExceptionResolver

②配置异常处理器

③编写异常页面

④测试异常跳转

Guess you like

Origin blog.csdn.net/weixin_45394002/article/details/113320356