A software and a product are developed and improved bit by bit, with more and more functions, stronger performance, and better user experience... The improvement of each indicator requires practical things to be done. For example, your product has become bigger and more people use it, not only for Shanghai people, Beijing people, but also for Indian people, French people, etc. It can be said that this product has entered the international stage. When Indian buddies enter the url to access the product, "Welcome, third brother" pops up on the interface, and I guess the buddies are confused on the spot. At this time, internationalization came into being.
To make international dishes, it is really not as complicated as you think. Instead, it is very simple. If you don’t believe it, you can see--
1. Inject ResourceBundleMessageSource
Add beanResourceBundlMessageSource for international processing in SpringMVC.xml
<bean id="messageSource"> <property name="basename" value="i18n"></property> </bean>
The name in the property here is the same as the property name in the injection class. The value here determines the name of the subsequent internationalization file. Remember it is i18n, and you will see its usage immediately.
2. Create international documents
In total, three international attribute files need to be created
i18n.properties - default international file
i18n_en_US.properties - Internationalized document for English environment
i18n_zh_CN.properties - Internationalized document for Chinese environment
Note: Why do the names of the files start with i18n? Because in the springmvc.xml configuration file at the first point, the configured value is i18n
The contents of the i18n.properties and i18n_en_US.properties files are the same as
i18n.username=UserNamei18n.password=Password
i18n_zh_CN.properties
i18n.username=/u7528/u6237/u540Di18n.password=/u5BC6/u7801
3. Create a new page
Create two new pages, one is i18n.jsp, which displays the user name, and there is a hyperlink to jump to i18n2.jsp, and the other is i18n2.jsp, which displays the password, and there is a hyperlink to jump to i18n.jsp.
i18n.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <fmt:message key="i18n.username"></fmt:message><br><br> <a href="i18n2">i18n2</a></body></html>
i18n2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <fmt:message key="i18n.password"></fmt:message><br><br><br> <a href="i18n">i18n</a></body></html>
At the same time, obviously we need to add an entry in index.jsp and link to the i18n.jsp page, as follows
<a href="i18n">i18n</a>
In order to be able to directly click and link without the need to process and jump to the view through handler, we need to add tags in springmvc.xml
<mvc:view-controller path="/i18n" view-name="i18n"/> <mvc:view-controller path="/i18n2" view-name="i18n2"/>
This enables you to directly access the i18n.jsp and i18n2.jsp pages in the address bar.
Small pit: If the encoding method in i18n.jsp and i18n2.jsp adopts the default "ISO-8859-1", the page will display garbled code.
When the encoding is changed to "UTF-8", it can be displayed normally
The above is the basic method of internationalization. If I still want to make an i18n.jsp that does not need to directly access i18n.jsp, but is presented after handler processing, or I also want to make an international dish that does not have to be so troublesome and has to switch languages, is it possible? Of course, let's continue to see--
1. Add tags for i18n.jsp access directly in springmvc.xml before commenting
<!-- <mvc:view-controller path="/i18n" view-name="i18n"/> -->
2. Add processing interface in the Hanlder processing class SpringMVCTest
@Autowiredprivate ResourceBundleMessageSource messageSource;@RequestMapping("/i18n")public String testI18n(Locale locale){ String val = messageSource.getMessage("i18n.username", null, locale); System.out.println(val); return "i18n";}Note that the internationalized processing class ResourceBundleMessageSource is injected here, and the internationalized property value is obtained using its getMessage method.
Start the tomcat service and see
So what if you display the information of the corresponding language in different language environments according to your own settings?
1. Configure SessionLocaleResolver and LocaleChangeInterceptor
<!-- Configure SessionLocaleResolver --><bean id="localeResolver"></bean> <!-- Configure LocaleChangeInterceptor --><mvc:interceptors> <bean></bean></mvc:interceptors>
The LocaleChangeInterceptor here is mainly used to parse requests with locale information into a Locale object and obtain a LocaleResolver object.
After that, the SessionLocalResolver here will convert the above LocalResolver object into a Session property, and take out this property, that is, the Locale object, and return it to the application.
2. Add a hyperlink in index.jsp
<a href="i18n?locale=en_CN">Chinese</a><br><br><a href="i18n?locale=en_US">English</a>
This way, we can see the results
After talking about internationalization, let’s talk about SpringMVC’s support for json.
In the traditional development process, our handler, i.e., controller layer, usually follows the routine of turning to a JSP view; however, such scenarios cannot meet all requirements. For example, we often only need to return data, rather than a JSP page. Then at this time, the @ResponseBody and @ResponseEntity of SPRING MVC3 support such functions. The Controller returns the data directly (we will talk about json data here), rather than pointing directly to the specific view. Here is a simple example of uploading and downloading.
1. File upload
1.1 Implement ajax request in index.jsp using jquery
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script><script> $(function(){ $("#testJson").click(function(){ var url = this.href; var args = {}; $.post(url, args, function(data){ for(var i=0; i<data.length; i++){ var id = data[i].id; var lastName = data[i].lastName; alert(id + ": " + lastName); } }) return false; }) })</script></head><body><a href="emps">list all employees</a><br/><br/> <a href="testJson" id="testJson">testJson</a></body></html>The core here is ajax request written in jquery
The requested url is the defined href;
data is the data returned after the request response;
Under normal circumstances, we should request information from all employees, and through the traversal here, we will get all information from each employee such as id, lastName, etc.
1.2. Here we need to introduce three jar packages
These three are mainly used later in the conversion of return data.
1.3. Add interface in handler SpringMVCTest
@ResponseBody@RequestMapping("testJson")public Collection<Employee> testJson(){ return employeeDao.getAll();}My personal understanding here is to return all employee information queried through employeeDao to the interface as a response, and finally obtain a json data form through a series of processing, and then traverse and parse in the foreground page. And it's all done thanks to the annotation @ResponseBody.
Specifically, there are some internal converters to do these conversions, breaking points in the interface method and entering debugging.
Select DispatcherServlet, find this->handleradiapters->elementData, find RequestMappingHandlerAdapter in this array, click in to find messageConverters, and you can see that there are 7 converters in total
The 7th MappingJackson2HttpMessageConverter here is the converter that we loaded in after adding the above three jar packages. As can be seen, there are enough converters for different data types to process.
1.4 Add link in index.jsp
<form action="testFileUpload" method="POST" enctype="multipart/form-data"> File: <input type="file" name="file"/> Desc: <input type="text" name="desc"/> <input type="submit" value="Submit"/></form><br/>
The final upload result is as follows
2. File download
2.1 Prepare to download the source
Create a new file directory under WebContent, put aaa.txt as the download source
2.2 Add a hyperlink in index.jsp as a download portal
<a href="testResponseEntity" id="testJson">testResponseEntity</a><br/>
2.3 Adding interface in handler SpringMVCTest
@RequestMapping("testResponseEntity")public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{ byte[] body = null; ServletContext servletContext = session.getServletContext(); InputStream in = servletContext.getResourceAsStream("/files/aaa.txt"); body = new byte[in.available()]; in.read(body); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=aaa.txt"); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> response = new ResponseEntity<>(body, headers, statusCode); return response;}Start tomcat and we can see that aaa.txt can be downloaded ~~~
OK, so far, what have we done
1. Support internationalization
2. File upload
3. File download
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.