spring mvc example of implementing file uploads and carrying other parameters
- 2020-06-07 04:30:40
- OfStack
This is the main jar file used: spring mvc +apache ES5en-ES6en
Step 1: The web. xml file. [Focus on interceptors and related listeners for spring mvc]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- Spring and mybatis Configuration file of -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- Code filter -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring The listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- To prevent Spring Memory overflow listener -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- This can be configured as *.do , corresponding to struts Suffix habit -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 2: ES17en-ES18en configuration file [Key points: spring mvc view mode, spring mvc file upload qualification parameters, spring mvc Resource interception management and others]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- Automatically scan the package to make SpringMVC I think it's in the bag @controller The annotated class is the controller -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<context:annotation-config/>
<context:component-scan base-package="com" />
<!-- avoid IE perform AJAX When to return to JSON Download file appears -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- Start the SpringMVC Annotations feature to complete requests and annotations POJO The mapping of -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON converter -->
</list>
</property>
</bean>
<!-- Defines the presuffix of the file for a jump , view mode configuration -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Here's the configuration I understand is given automatically later action The method of return The string, prefixed and suffixed, becomes 1 a The available url address -->
<property name="prefix" value="/backstage/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Profile uploads. If you don't use file uploads, you don't need to configure them, and if you don't, you don't need to introduce the upload package into the profile -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- The default encoding -->
<property name="defaultEncoding" value="utf-8" />
<!-- Maximum file size -->
<property name="maxUploadSize" value="10485760000" />
<!-- Maximum in memory -->
<property name="maxInMemorySize" value="40960" />
</bean>
<!-- The statement DispatcherServlet Do not intercept the directory declared below -->
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/common/" mapping="/common/**"/>
</beans>
Step 3: The jsp page
<%@ page language="java" pageEncoding="UTF-8"%>
<form action="<%=request.getContextPath()%>/users/add" method="POST" enctype="multipart/form-data">
username: <input type="text" name="username"/><br/>
nickname: <input type="text" name="nickname"/><br/>
password: <input type="password" name="password"/><br/>
yourmail: <input type="text" name="email"/><br/>
yourfile: <input type="file" name="myfiles"/><br/>
<input type="submit" value=" Add a new user "/>
</form>
Step 4: spring mvc controller code
package com.wlsq.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.wlsq.model.News;
import com.wlsq.service.IUserMapperService;
import com.wlsq.util.Pagination;
@Controller
@RequestMapping(value="/users")
public class UserController {
@Autowired
private IUserMapperService userService;
@RequestMapping(value="/userAll")
public ModelAndView searchNews(HttpServletRequest request,HttpServletResponse response){
ModelAndView mv = null;
try{
mv = new ModelAndView();
int pageSize = Integer
.parseInt(request.getParameter("pageSize") == null ? "10"
: request.getParameter("pageSize"));
int pageNum = Integer
.parseInt(request.getParameter("pageNum") == null ? "1"
: request.getParameter("pageNum"));
Map<String, Object> maps = new HashMap<>();
maps.put("pageSize", pageSize);
maps.put("pageNum", (pageNum-1) * pageSize);
List<News> list =userService.selectAllUsers(maps);
int count = userService.selectCountUsers();
Pagination page = new Pagination(count);
page.setCurrentPage(pageNum);
mv.addObject("pnums", page.getPageNumList());
mv.addObject("currentPage", pageNum);
mv.addObject("pnext_flag", page.nextEnable());
mv.addObject("plast_flag", page.lastEnable());
page.lastPage();
mv.addObject("last_page", page.getCurrentPage());
mv.addObject("count", count);
mv.addObject("pageCount", page.getPages());
if(list !=null && list.size()>0){
// The user is
mv.addObject("partners", list);
// Set the logical view name, based on which the view parser resolves to the specific view page
mv.setViewName("/users/users");
}else{
// The user is
mv.addObject("partners", list);
// Set the logical view name, based on which the view parser resolves to the specific view page
mv.setViewName("/users/users");
}
}catch(Exception e){
// Set the logical view name, based on which the view parser resolves to the specific view page
mv.setViewName("/users/users");
}
return mv;
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public String addUser(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException{
String username = request.getParameter("username");
String nickname = request.getParameter("nickname");
String password = request.getParameter("password");
String email = request.getParameter("email");
System.out.println("name:"+username);
System.out.println("nickname:"+nickname);
System.out.println("password:"+password);
System.out.println("email:"+email);
// If it's just uploading 1 For a file, you only need to MultipartFile The type receives the file and does not need to be explicitly specified @RequestParam annotations
// If you want to upload multiple files, then I'm going to use it here MultipartFile[] Type to receive files, and also specify @RequestParam annotations
// And when uploading multiple files, all in the foreground form <input type="file"/> the name Everything ought to be myfiles Otherwise, in the parameters myfiles Unable to get all uploaded files
for(MultipartFile myfile : myfiles){
if(myfile.isEmpty()){
System.out.println(" File not uploaded ");
}else{
System.out.println(" The length of the file : " + myfile.getSize());
System.out.println(" The file type : " + myfile.getContentType());
System.out.println(" The file name : " + myfile.getName());
System.out.println(" File formerly known as : " + myfile.getOriginalFilename());
System.out.println("========================================");
// If I'm using theta Tomcat Server, the file will be uploaded \\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\ folder
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
// You don't have to deal with it here IO The flow is closed because FileUtils.copyInputStreamToFile() Method will be used automatically IO Stream off, I was looking at its source to know
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
}
}
return "../../index";
}
}
Remember to create a directory in WEB-ES41en for uploading files (upload)