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 do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft