Home  >  Article  >  Java  >  Introduction to page internationalization and file upload in SpringMVC (with code)

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

不言
不言forward
2018-09-28 15:53:232062browse
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:cnblogs.com. If there is any infringement, please contact admin@php.cn delete