发表于: 2022-06-22 19:53:22

1 490



MessageSource实现国际化

applicationContext.xml文件中添加参数:

<beans>
   <bean id="messageSource"
         class="org.springframework.context.support.ResourceBundleMessageSource">
       <property name="basenames">
           <list>
               <value>i18n</value>
               <value>messages.extend</value>
           </list>
       </property>
   </bean>
</beans>


创建一个Resspone类:

import java.io.Serializable;

public class Respone implements Serializable {
private static final long serialVersionUID = -2293285838727787621L;
   private int code;
   private String message;
   private Object data;

   public int getCode() {
return code;
   }

public void setCode(int code) {
this.code = code;
   }

public String getMessage() {
return message;
   }

public void setMessage(String message) {
this.message = message;
   }

public Object getData() {
return data;
   }

public void setData(Object data) {
this.data = data;
   }
}



在controller文件中输入代码:

@Controller
@RequestMapping("user")
public class UserController {


@Autowired
   private MessageSource autowiredMs;



//q请求映射网址

@RequestMapping("/test")
@ResponseBody
public Respone test(String name) {
List<User> user = new ArrayList<>();
   Respone respone = new Respone();
   respone.setCode(0);



   if (name == null) {
respone.setCode(-1);
       respone.setMessage("fail");
       respone.setData(autowiredMs.getMessage("info", new String[] {"张三"},null));
       return respone;
   }else if (name.equals("1")){
respone.setCode(-1);
       respone.setMessage("fail");
       respone.setData(autowiredMs.getMessage("say",null,Locale.US));
       return respone;
   }else if (name.equals("2")){
respone.setCode(-1);
       respone.setMessage("fail");
       respone.setData(autowiredMs.getMessage("say",null,Locale.SIMPLIFIED_CHINESE));
       return respone;
   }else if (name.equals("3")){
respone.setCode(-1);
       respone.setMessage("fail");
       respone.setData(autowiredMs.getMessage("-1",null,null));
       return respone;
   }

respone.setMessage("success");
   respone.setData(user);
   return respone;
}


properties文件代码:

info={0}\u5E05\u7684\u8BA9\u4EBA\u6CA1\u813E\u6C14\u3002
#i18n_zh_CN.properties
say=\u5927\u5BB6\u597D\uFF01
-1=Error
#i18n_en_US.properties
say=Hallo world!
-1=11124mm



成功运行:


返回的错误信息数据:







返回的正确信息:







收获:以上


明天计划:完成接下来的任务。






返回列表 返回列表
评论

    分享到