通过spring取得国际化文件

本文介绍了一个用于管理航班信息的控制器,该控制器提供了多个功能,包括切换办公室、加载页面等操作,并通过与TAPI连接交互来实现这些功能。
/* 
 * @(#) ScheduleController.java 2010-4-8
 * 
 * Copyright 2010 by TravelSkay Corporation.
 * No. 11 Huixinxijie, Beijing
 * 
 * All rights reserved.
 * 
 * This software is the confidential and proprietary information of
 * TravelSkay Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with TravelSkay.
 * 
 */
package com.travelsky.pss.flight.base.web;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.travelsky.pss.abframe.base.util.Crypt;
import com.travelsky.pss.core.dao.tapi.TAPIConnection;
import com.travelsky.pss.core.exception.ApplicationException;
import com.travelsky.pss.flight.base.dao.entity.DAEntity;
import com.travelsky.pss.flight.base.service.IFlightService;
import com.travelsky.pss.flight.base.web.vo.FlightVo;



/**
 * 
 * 登录控制 Copyright: Copyright (c) 2011 Company: 
 * 
 * @author 
 * @version 1.0 2011-6-20下午02:52:41
 * @see HISTORY 2011-6-20下午02:52:41 创建文件
 ************************************************* 
 */
@Controller
@RequestMapping("/flight")
public class FlightController {
	
	/**
	 * 注入用户管理服务接口
	 */

	@Autowired
	private IFlightService flightService = null;

	private MessageSourceAccessor messages;// 获取国际化文件内�?

	@Autowired
	public void setMessages(MessageSource messageSource) {
		messages = new MessageSourceAccessor(messageSource);
	}

	/**
	 * 
	 * 跳转到航班控制页�?
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             Date: 2011-6-17下午05:22:46
	 */
	@RequestMapping(value = "forwardMain", method = RequestMethod.GET)
	public ModelAndView forwardMain(HttpServletRequest request)
			throws Exception {
	
		String topId = request.getParameter("selectId");
		ModelAndView mav = new ModelAndView("flight/base/flightLogin");
		mav.addObject("topId", topId);
		return mav;
	}

	
	/**
	 * 
	 * 切换Office
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             Date: 2011-6-20下午02:50:58
	 */
	@RequestMapping(value = "changeOffice", method = RequestMethod.GET)
	public ModelAndView changeOffice(HttpServletRequest request)
			throws Exception {

		long id = (Long) request.getSession().getAttribute("OperatorId");
		String topId = request.getParameter("topId");
		// OperatorVo opeVo = operatorService.getOperatorVoById(ope.getId()+"");
		FlightVo fliVo = flightService.getFlightVoById(id + "");
		String icsId = fliVo.getIcsId();
		String icsPwd = Crypt.decrypt(fliVo.getIcsPwd());
		String icsLev = fliVo.getIcsSecurityLevel().toString();
		String offices = fliVo.getOffice();
		String[] office = offices.split(",");
		List<String> officeList = Arrays.asList(office);
		String officeUsas = request.getParameter("office");
		boolean soResult = false;
		TAPIConnection tapiConnection = (TAPIConnection) request.getSession()
				.getAttribute("tapiConnection");
		if (tapiConnection == null
				|| tapiConnection.getCurrentSession() == null
				|| !tapiConnection.getCurrentSession().isConnected()) {
			throw new ApplicationException(
					"error.flight.common.usas.cannotconnect");
		}
		ModelAndView mav = new ModelAndView("flight/base/flightWelcome");
		try {
			soResult = flightService.execSO(tapiConnection.getCurrentSession());
			
			if (soResult) {
				tapiConnection.getCurrentSession().executeCommand(
						"SI:" + icsId + "/" + icsPwd + "/" + icsLev + "/"
								+ officeUsas);
			}
			List<DAEntity> daList = flightService.queryDAList(tapiConnection
					.getCurrentSession());
			mav.addObject("officeUsas", officeUsas);
			mav.addObject("office", officeList);
			mav.addObject("daList", daList);
			mav.addObject("topId", topId);
			return mav;
		} catch (Exception e1) {
			String errorTAPI = e1.getMessage();
			Locale locale = (Locale) request.getSession().getAttribute(
					SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
			String errorMessage = messages.getMessage(
					"error.flight.common.usas.notconnect", locale);//转换消息
			mav.addObject("errorMessage", errorMessage);
			mav.addObject("errorTAPI", errorTAPI);
			mav.addObject("officeUsas", officeUsas);
			mav.addObject("office", officeList);
			mav.addObject("topId", topId);
			return mav;
		}
	}
	/**
	 * 
	 * 跳转到其他URL
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             Date: 2011-6-17下午05:22:22
	 */
	@RequestMapping(value = "loadPage", method = RequestMethod.GET)
	public ModelAndView loadPage(HttpServletRequest request) throws Exception {
		String url = request.getParameter("url");

		return new ModelAndView("flight/" + url);
	}
	/**
	 * 
	 * 退出主机登录,跳转到首�?
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             Date: 2011-6-22下午04:52:37
	 */
	@RequestMapping(value = "forwardSystemIndex", method = RequestMethod.GET)
	public ModelAndView execSO(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView("/welcome");
		TAPIConnection tapiConnection = (TAPIConnection) request.getSession().getAttribute(
				"tapiConnection");
		try {
			flightService.execSO(tapiConnection.getCurrentSession());
			return mav;}
		catch(Exception e){
			return mav;
		}
		
	}

	/**
	 * 
	 * 跳转到框架页�?
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             Date: 2011-7-13下午02:10:58
	 */
	@RequestMapping(value = "forwardFlightMain", method = RequestMethod.GET)
	public ModelAndView forwardFlightMain(HttpServletRequest request)
			throws Exception {
		long id = (Long) request.getSession().getAttribute("OperatorId");
		// OperatorVo opeVo = operatorService.getOperatorVoById(ope.getId()+"");
		FlightVo fliVo = flightService.getFlightVoById(id + "");
		String offices = fliVo.getOffice();
		String[] office = offices.split(",");
		List<String> officeList = Arrays.asList(office);
		String officeUsas = request.getParameter("office");
		String topId = request.getParameter("topId");
		String selectId = request.getParameter("selectId");
		String welcome = request.getParameter("welcome");
		ModelAndView mav = new ModelAndView("flight/base/flightMain");
		mav.addObject("officeUsas", officeUsas);
		mav.addObject("office", officeList);
		mav.addObject("topId", topId);
		mav.addObject("selectId", selectId);
		mav.addObject("welcome", welcome);
		return mav;
	}

	/**
	 * 
	 * 跳转到到欢迎�?
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 *             Date: 2011-7-13下午02:10:58
	 */
	@RequestMapping(value = "forwardWelcome", method = RequestMethod.GET)
	public ModelAndView forwardWelcome(HttpServletRequest request)
			throws Exception {
		String url = request.getParameter("url");
		ModelAndView mav = new ModelAndView(url);
		return mav;
	}
}
<think>我们正在讨论Spring Boot中获取国际化资源文件的方法。根据引用[2],Spring Boot通过MessageSourceProperties和ResourceBundleMessageSource来管理国际化资源。用户想要知道如何使用Resource对象来获取这些国际化资源文件(可能是直接获取文件内容或路径)。 引用[3]提供了四种获取resource文件夹下资源文件的方法,我们可以参考这些方法来获取国际化资源文件国际化资源文件通常位于classpath下,如`messages.properties`、`messages_en.properties`等。 注意:国际化资源文件一般通过MessageSource来访问,而不是直接读取文件。但用户明确要求使用Resource来获取,所以我们将展示如何通过Resource对象获取国际化资源文件的内容。 步骤: 1. 确定国际化资源文件的位置,默认在classpath根目录下,但也可以在`spring.messages.basename`中配置(例如:`classpath:i18n/messages`)。 2. 使用Spring的ResourceLoader或者通过ClassPathResource来加载资源文件。 示例代码: 假设我们的国际化资源文件名为`messages.properties`,位于`src/main/resources`目录下(即classpath根目录)。 我们可以使用以下方法之一: 方法一:使用ClassPathResource ```java import org.springframework.core.io.ClassPathResource; import org.springframework.util.FileCopyUtils; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; // ... // 指定资源路径,注意:路径不需要前缀classpath:,直接从classpath根目录开始 ClassPathResource resource = new ClassPathResource("messages.properties"); try { String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } ``` 方法二:使用ResourceLoader(推荐在Spring Bean中使用) 在Spring管理的Bean中,可以注入ResourceLoader,然后使用它来加载资源。 ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; @Component public class MyComponent { private final ResourceLoader resourceLoader; public MyComponent(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @PostConstruct public void init() { // 加载资源文件,路径可以是classpath:开头 Resource resource = resourceLoader.getResource("classpath:messages.properties"); try { String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意:国际化资源文件可能有多个(如不同语言),我们需要根据实际文件名来加载。例如,要加载英文资源文件,可以指定文件名为`messages_en.properties`。 但是,直接读取国际化资源文件并不是常见的做法,因为Spring Boot已经通过MessageSource为我们提供了国际化的支持。通常,我们使用MessageSource来获取国际化的消息。 例如,使用MessageSource的方式: ```java @Autowired private MessageSource messageSource; public String getMessage(String code, Object[] args, Locale locale) { return messageSource.getMessage(code, args, locale); } ``` 但是,用户要求使用Resource获取,所以我们提供了上述直接读取文件的方法。 另外,引用[3]中提到的第三种方法(使用ClassLoader获取输入流)也可以使用: ```java InputStream inputStream = getClass().getClassLoader().getResourceAsStream("messages.properties"); // 然后读取输入流 ``` 不过请注意,如果文件jar包内,使用getFile()方法可能会抛出FileNotFoundException,因为jar包内的资源不是一个文件系统路径。因此,推荐使用getInputStream()来读取内容。 总结:在Spring Boot中,可以通过ClassPathResource、ResourceLoader或ClassLoader来获取国际化资源文件的内容,但要注意文件路径和读取方式(避免使用getFile(),而使用流)。 相关问题: 1. Spring Boot中如何配置多个国际化资源文件? 2. 如何在非Spring管理的类中获取国际化资源文件? 3. 使用Resource读取资源文件时,如何处理不同环境下的路径问题? </think>在 Spring Boot 中通过 `Resource` 获取国际化资源文件的方法如下,结合引用[2]的国际化和引用[3]的资源加载技术: ### 一、核心方法(推荐) #### 1. **使用 `ResourceLoader` 注入(推荐)** ```java @Autowired private ResourceLoader resourceLoader; public Resource getI18nResource(String filename, Locale locale) { // 示例路径: i18n/messages_zh_CN.properties String path = "classpath:i18n/" + filename + "_" + locale + ".properties"; return resourceLoader.getResource(path); } ``` #### 2. **使用 `ClassPathResource`** ```java Resource resource = new ClassPathResource("i18n/messages_en_US.properties"); try (InputStream inputStream = resource.getInputStream()) { // 处理文件流 } catch (IOException e) { e.printStackTrace(); } ``` --- ### 二、关键注意事项 1. **文件位置** 国际化文件需放在 `src/main/resources` 下,例如: ``` resources/ ├── i18n/ │ ├── messages.properties # 默认 │ ├── messages_zh_CN.properties │ └── messages_en_US.properties ``` 2. **路径规范** - 路径需与 `spring.messages.basename` 配置匹配(默认 `messages`)[^2] - 文件名格式:`{basename}_{language}_{region}.properties` 3. **读取文件内容** 使用 Spring 工具类简化操作: ```java String content = StreamUtils.copyToString( resource.getInputStream(), StandardCharsets.UTF_8 ); ``` --- ### 三、对比方案 | 方法 | 优点 | 缺点 | |----------------------|------------------------------|-------------------------------| | `ResourceLoader` | 支持动态路径,灵活度高 | 需依赖注入 | | `ClassPathResource` | 无需注入,适合工具类 | 路径硬编码 | | `ClassLoader` | 兼容旧版 Spring | 需手动处理编解码[^3] | --- ### 四、完整示例 ```java @Service public class I18nService { @Autowired private ResourceLoader resourceLoader; public Properties loadMessages(Locale locale) throws IOException { Resource resource = resourceLoader.getResource( "classpath:i18n/messages_" + locale.toLanguageTag() + ".properties" ); Properties props = new Properties(); try (InputStream is = resource.getInputStream()) { props.load(new InputStreamReader(is, StandardCharsets.UTF_8)); } return props; } } ``` > **注意**:生产环境建议使用 Spring 内置的 `MessageSource` 接口(引用[2]),而非直接操作资源文件: > ```java > @Autowired private MessageSource messageSource; > String msg = messageSource.getMessage("hello", null, locale); > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值