Spring MVC file upload
1 - spring MVC request - file upload - client form implementation (application)
The file upload client form needs to meet the following requirements:
Form item type = "file"
The form is submitted by post
The enctype attribute of the form is a multi part form, and enctype = "multipart / form data"
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data"> name<input type="text" name="username"><br/> File 1<input type="file" name="uploadFile"><br/> <input type="submit" value="Submit"> </form>
2 - spring MVC request - file upload - principle of file upload (understanding)
3 - spring MVC 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
<!--Profile upload 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 - spring MVC request - file upload - code implementation of single file upload 2 (application)
Complete file upload
@RequestMapping(value="/quick22") @ResponseBody public void save22(String username, MultipartFile uploadFile) throws IOException { System.out.println(username); //Get the name of the uploaded file String originalFilename = uploadFile.getOriginalFilename(); uploadFile.transferTo(new File("C:\\upload\\"+originalFilename)); }
5 - spring MVC request - file upload - code implementation of multi file upload (application)
To upload multiple files, you only need to change the page to multiple file upload items and change the method parameter MultipartFile type to MultipartFile []
<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data"> name<input type="text" name="username"><br/> File 1<input type="file" name="uploadFile"><br/> Document 2<input type="file" name="uploadFile"><br/> <input type="submit" value="Submit"> </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 - spring MVC request - key points of knowledge (understanding, memory)
Interceptor for spring MVC
01 spring MVC interceptor - role of interceptor (understanding)
The interceptor of Spring MVC is similar to the Filter in Servlet development, which is used to preprocess and post process the processor.
The interceptors are connected into a chain in a certain order, which is called interceptor chain. When accessing the intercepted method or field, the interceptors in the interceptor chain will be called in the order they were previously defined. Interceptor is also the concrete implementation of AOP idea.
02 spring MVC interceptor - difference between interceptor and filter (understanding, memory)
The difference between interceptor and filter is shown in the figure:
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-6kSspRn7-1627780186115)(./img/1.png)]
03 spring MVC interceptor - Quick Start (application)
The custom interceptor is very simple. There are only three steps:
① Create an interceptor class to implement the HandlerInterceptor interface
② Configure interceptor
③ Test the interception effect of the interceptor
Write Interceptor:
public class MyInterceptor1 implements HandlerInterceptor { //Execute before the target method executes public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { System.out.println("preHandle....."); } //Execute after the target method executes and before the view object returns public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("postHandle..."); } //Execute after all processes are executed public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("afterCompletion...."); } }
Configuration: configure in the configuration file of spring MVC
<!--Configuring Interceptors --> <mvc:interceptors> <mvc:interceptor> <!--Which resources are intercepted--> <mvc:mapping path="/**"/> <bean class="com.itheima.interceptor.MyInterceptor1"/> </mvc:interceptor> </mvc:interceptors>
Write test program:
Write the controller, send a request to the controller and jump to the page
@Controller public class TargetController { @RequestMapping("/target") public ModelAndView show(){ System.out.println("Target resource execution......"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("name","itcast"); modelAndView.setViewName("index"); return modelAndView; } }
page
<html> <body> <h2>Hello World! ${name}</h2> </body> </html>
04 spring MVC interceptor - quick start details (application)
Under what circumstances will the interceptor execute the target resource after preprocessing, under what circumstances will the interceptor 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 { //Execute before the target method executes public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { System.out.println("preHandle22222....."); return true; } //Execute after the target method executes and before the view object returns public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("postHandle2222..."); } //Execute after all processes are executed public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("afterCompletion2222...."); } }
Configure interceptor 2
<!--Configuring Interceptors --> <mvc:interceptors> <mvc:interceptor> <!--Which resources are intercepted--> <mvc:mapping path="/**"/> <bean class="com.itheima.interceptor.MyInterceptor2"/> </mvc:interceptor> <mvc:interceptor> <!--Which resources are intercepted--> <mvc:mapping path="/**"/> <bean class="com.itheima.interceptor.MyInterceptor1"/> </mvc:interceptor> </mvc:interceptors>
Conclusion:
When the preHandle method of the interceptor returns true, the target resource will be executed. If false, the target resource will not be executed
In the case of multiple interceptors, the configuration before is executed first, and the configuration after is executed
The execution order of methods in the interceptor is: preHandler ------ target resource ----- posthandle ----- aftercompletion
05 spring MVC interceptor - knowledge summary (memory)
The method in the interceptor is described below
06 spring MVC interceptor - user login permission control analysis (understanding)
On the basis of the day06 spring exercise case: the user cannot access the background menu without logging in. Click the menu to jump to the login page. The background function can be operated only after the user logs in successfully
Demand diagram:
07 spring MVC interceptor - user login permission control code implementation 1 (application)
Judge whether the user is logged in: judge whether there is a user in the session. If there is no login, log in first. If there is already login, directly release 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 { //Logic: judge whether the user logs in. Essence: judge whether there is a user in the session HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); if(user==null){ //not logged on response.sendRedirect(request.getContextPath()+"/login.jsp"); return false; } //Release access to target resources return true; } }
Then configure the Interceptor: find the spring - MVC XML, add the following configuration:
<!--Configure permission interceptor--> <mvc:interceptors> <mvc:interceptor> <!--Configure which resources to intercept--> <mvc:mapping path="/**"/> <bean class="com.itheima.interceptor.PrivilegeInterceptor"/> </mvc:interceptor> </mvc:interceptors>
08 spring MVC 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 to return 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){ //Login succeeded. Store user in session session.setAttribute("user",user); return "redirect:/index.jsp"; } return "redirect:/login.jsp"; }
The service layer code is as follows:
//service layer public User login(String username, String password) { User user = userDao.findByUsernameAndPassword(username,password); return user; }
dao layer code is as follows:
//dao layer 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, we still can't log in, because we need to let the interceptor release the login request url and add the configuration of resource exclusion
<!--Configure permission interceptor--> <mvc:interceptors> <mvc:interceptor> <!--Configure which resources to intercept--> <mvc:mapping path="/**"/> <!--Which resources are configured to exclude blocking operations--> <mvc:exclude-mapping path="/user/login"/> <bean class="com.itheima.interceptor.PrivilegeInterceptor"/> </mvc:interceptor> </mvc:interceptors>
09 spring MVC interceptor - user login permission control code implementation 3 (application)
JdbcTemplate. If the queryforobject object cannot find the data, it will throw an exception, resulting in the program unable to achieve the expected effect. How to solve this problem?
The business layer handles exceptions from the dao layer. If an exception occurs, the service layer returns null instead of throwing the exception to the controller
Therefore, modify the login business layer code and add exception control
public User login(String username, String password) { try { User user = userDao.findByUsernameAndPassword(username,password); return user; }catch (EmptyResultDataAccessException e){ return null; } }
1. Spring MVC exception handling mechanism
1.1 ideas for exception handling
There are two types of exceptions in the system: expected exception and runtime exception RuntimeException. The former obtains exception information by capturing exceptions, and the latter mainly reduces the occurrence of runtime exceptions by standardizing code development and testing.
Dao, Service and Controller of the system are thrown upward through throws Exception. Finally, the spring MVC front-end Controller sends it to the exception handler for exception handling, as shown in the following figure:
1.2 two methods of exception handling
① Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC
② Implement the exception handling interface of Spring, HandlerExceptionResolver, and customize its own exception handler
1.3 simple exception handler SimpleMappingExceptionResolver
Spring MVC has defined this type converter. When using it, you can map and configure the corresponding exceptions and views according to the project situation
<!--Configure simple mapping exception handler--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="error"/> Default error view <property name="exceptionMappings"> <map> Exception type Error view <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) { //Code implementation for handling exceptions //Create ModelAndView object ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("exceptionPage"); return modelAndView; } }
② Configure exception handler
<bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>
③ Write exception page
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> This is a final exception display page </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 key points of knowledge
Exception handling method
Configure simple exception handler SimpleMappingExceptionResolver Custom exception handler
Custom exception handling steps
①Create exception handler class implementation HandlerExceptionResolver ②Configure exception handler ③Write exception page ④Test abnormal jump