


Introduction to page internationalization and file upload in SpringMVC (with code)
In fact, the page internationalization in SpringMVC is basically the same as the verification internationalization in the previous chapter.
1. Internationalize the page
1) First, we add the internationalized bean configuration to the Spring configuration file
<!-- 注册国际化信息,必须有id,指定资源文件名称,资源文件在src目录下 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="i18n"></property> </bean> <!-- 配置LocalResolver用来获取本地化语言 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <!-- 配置LocaleChanceInterceptor拦截器 --> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors>
2) Then add our resource file. The prefix of this resource file must be the same as the value of the bean we configured above.
We write the content we need to internationalize in the resource file
Then when we jump to the page Internationalized resources need to be loaded
@RequestMapping(value="login",method=RequestMethod.GET) public String login(Locale locale,Map<String ,Object> map){ String name = messageSource.getMessage("name", null, locale); String pass = messageSource.getMessage("pass", null, locale); String title = messageSource.getMessage("title", null, locale); String submit = messageSource.getMessage("submit", null, locale); map.put("title", title); map.put("pass", pass); map.put("name", name); map.put("submit", submit); map.put("user", new User()); return "login"; }
We can use jstl or spring tag data internationalization information in the page. The form tag in spring is used to enter the prompt information after spring verification error (mentioned in the previous chapter)
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
Then the internationalization information in our page can be displayed
<form:form action="login" method="post" commandName="user"> <fmt:message key="name"/> <form:input path="username"/> <form:errors path="username"/> <br> <fmt:message key="pass"/> <form:input path="userpass"/> <input type="submit" value="<spring:message code="submit"/>"> </form:form>
We can also complete a language switching function. We add two hyperlinks to the page. When a request is received , SpringMVC will look for a local parser in the context, and use it to obtain the localization type information corresponding to the request. SpringMVC also allows you to assemble an interceptor that dynamically changes the localization type, so that you can specify a request parameter. Controls the localization type for an individual request.
<a href="login?locale=zh_CN">中文</a> <a href="login?locale=en_US">英文</a>
After receiving the request, SpringMVC will first determine whether there is this parameter. If there is this parameter, it will be added to the session. If there is no such parameter, it will go to the session to find it. If it is not found in the session, it will read and browse by default. language of the machine.
2. File upload
SpringMVC’s file upload is very simple. It directly provides direct support. This support is through Implemented by the plug-and-play MultipartResolver interface. Spring uses its implementation class CommonsMultipartResolver to implement it. There is no automatic assembly in the SpringMVC context so we need to configure it manually. We will directly implement a multi-file upload here. If you can upload multiple files, are you afraid of uploading a single file?
Before configuration, we first import the jar packages for file upload. These packages are not available in our spring.
Then we manually configure the Bean
<!-- 配置文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 指定默认的编码格式 --> <property name="defaultEncoding" value="UTF-8" /> <!-- 指定允许上传的文件大小,单位Byte --> <property name="maxUploadSize" value="512000" /> </bean>
You can also set the type and so on in this bean, there are You can read the source code if needed.
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"/><br> <input type="file" name="file"/><br> <input type="file" name="file"/><br> <input type="submit" value="submit"> </form>
enctype="multipart/form-data" Note that this must be added when uploading files, and it must be a post request.
Then let’s take a look at how our server receives the file. Use MultipartFile[] to upload multiple files and be sure to add the annotation @RequestParam("file") before the parameter, otherwise an error will be reported. We only need to use a MultipartFile object for single file upload, and no annotations are required.
/** * 单文件上传 : MultipartFile file * 多文件上传 : @RequestParam("file") MultipartFile[] file * 多文件上传必须加上 @RequestParam("file")注解否则会报错 * @author:MiYa. * @time:2018-9-28 11:50 */ @RequestMapping(value="upload",method=RequestMethod.POST) public String testFileUpload(HttpServletRequest request , @RequestParam("file") MultipartFile[] file){ for (int i = 0; i < file.length; i++) { MultipartFile multipartFile = file[i]; System.out.println(" ContentType: " + multipartFile.getContentType()); System.out.println(" Name: " + multipartFile.getName()); System.out.println(" OriginalFilename: " + multipartFile.getOriginalFilename()); System.out.println(" Size: " + multipartFile.getSize()); //判断是否提交文件,如果没有那么跳过上传 if(multipartFile.isEmpty()){ continue; } // 获取文件的上传路径 String uploadpath = request.getServletContext().getRealPath("uploads"); //获取文件名称 String filename = multipartFile.getOriginalFilename(); //截取文件后缀 String fileext = filename.substring(filename.lastIndexOf(".")); //生成新的随机文件名称 String newfileName = UUID.randomUUID() + fileext; //文件保存路径 File savepath = new File(uploadpath + "/" + newfileName); //上传文件 try { multipartFile.transferTo(savepath); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return "welcome"; }
Sort out the methods commonly used by MultipartFile:
isEmpty(): Determine whether to submit the file
getContextType(): Get File type
getName(): Get the form element name
getOriginalFilename(): Get the file name
getSize(): Get the file size
getBytes( ): Get byte array
The above is the detailed content of Introduction to page internationalization and file upload in SpringMVC (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

The difference between spring and springmvc: 1. Positioning and functions; 2. Core functions; 3. Application areas; 4. Extensibility. Detailed introduction: 1. Positioning and functions. Spring is a comprehensive application development framework that provides dependency injection, aspect-oriented programming, transaction management and other functions. It is designed to simplify the development of enterprise-level applications, and Spring MVC is the Spring framework. A module in it is used for the development of Web applications and implements the MVC pattern; 2. Core functions and so on.

SpringBoot and SpringMVC are two frameworks commonly used in Java development. They are both provided by the Spring framework, but they have some differences in functions and usage methods. This article will introduce the characteristics and differences of SpringBoot and SpringMVC respectively. 1. Features of SpringBoot: Simplified configuration: SpringBoot greatly simplifies the project configuration process through the principle of convention over configuration. It can automatically configure the parameters required by the project, and developers

The differences between springboot and springmvc are: 1. Different meanings; 2. Different configurations; 3. Different dependencies; 4. Different development times; 5. Different productivity; 6. Different ways to implement JAR packaging function; 7. Whether batch processing is provided Function; 8. Different functions; 9. Different community and documentation support; 10. Whether deployment descriptors are required.

With the development of the Internet, Web services are becoming more and more common. As an application programming interface, JavaAPI is constantly launching new versions to adapt to different application scenarios. As a popular open source framework, SpringMVC can help us easily build web applications. This article will explain in detail how to use SpringMVC for Web service processing in JavaAPI development, including configuring SpringMVC, writing controllers, and using

The role of interceptor SpringMVC's interceptor is similar to the filter in Servlet development, which is used to pre-process and post-process the processor. Interceptors are connected into a chain in a certain order, and this chain is called an interceptor chain (InterceptorChain). When an intercepted method or field is accessed, the interceptors in the interceptor chain will be called in the order they were previously defined. Interceptors are also the specific implementation of AOP ideas. The difference between interceptors and filters: Filter (Filter) The scope of use of interceptor (Intercepter) is part of the servlet specification and can be used by any JavaWeb project. Spri

Analyzing the similarities and differences between SpringBoot and SpringMVC SpringBoot and SpringMVC are very important development frameworks in the Java field. Although they are both part of the Spring framework, there are some obvious differences in usage and functionality. This article will compare SpringBoot and SpringMVC and analyze the similarities and differences between them. First, let's learn about SpringBoot. SpringBo
