search
HomeJavajavaTutorialIntroduction to page internationalization and file upload in SpringMVC (with code)

This article brings you an introduction to page internationalization and file uploading in SpringMVC (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.