SpringMvc的简单入门(三)之国际化

本文介绍SpringMVC中的视图解析配置、国际化资源文件设置及国际化验证实现。包括视图解析器配置、国际化资源加载、页面国际化标签使用、获取本地资源配置、国际化验证配置及实体验证规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.视图解析

1.在mvc-servlet.xml中配置视图解析器

 
  <!-- 视图解析器 -->
  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  	<property name="prefix" value="/"></property>
  	<property name="suffix" value=".jsp"></property>
  </bean>
访问的jsp页面不用再加.jsp
@RequestMapping(value="/re",method=RequestMethod.POST)
	public String quert(@ModelAttribute("user") @Valid Userin user,BindingResult error){

		return "less04/re";
	}
二.国际化

1.在spring.xml配置国际化的设计

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"


	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
	http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
	
	">


	<!-- 国际化 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="/springmvc/less04/resource/my"></property>
	</bean>
	
</beans>

二.创建国际化语言

username=username
password=password
repassword=repassword
age=age
phone=phone
dob=data
email=email
register=register
userError=The user name cannot be empty
pwd=Password cant be empty
repwd=can not be empty
pho=The phone number must be eleven
ag=Age cannot be empty
ag1=Age must be greater than 1
ag2=Age must be less than 100
data=Time format error

2.页面,国际化需要<%@taglib uri="http://www.springframework.org/tags" prefix="f"%>标签 code配置的资源的键

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="f"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>easety注册</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
      function checkSubmit(){
      
        //校验 不通过不提交
        /**
        var name=document.getElementsByName("name")[0].value;
        if(name==null || name==""){
            alert("用户名不能为空");
        	return;
        }
        var password=document.getElementsByName("password")[0].value;
        var repassword=document.getElementsByName("repassword")[0].value;
        if(password!=repassword){
            alert("两次输入密码不一致");
        	return;
        }
        **/
      	document.forms[0].submit();
      }
   
   </script>
  </head>
  
  <body >
  <div style="margin-top:82px;text-align: center;">


  	<a href="${pageContext.request.contextPath}/mid?a=zh_CN">中文</a><a href="${pageContext.request.contextPath}/mid?a=en_GB">English</a>
     <form action="<%=path %>/myreg" method="post"> 
         <f:message code="username"></f:message> :<input type="text" name="name"/>*
         <font color=red><form:errors path="user.name"></form:errors></font>
         <br/>
         <f:message code="password"></f:message> :<input type="password" name="password"/>*
         <font color=red><form:errors path="user.password"></form:errors></font>
         <br/>
         <f:message code="repassword"></f:message> :<input type="password" name="repassword"/>*
         <font color=red><form:errors path="user.repassword"></form:errors></font>
         <br/>
         <f:message code="email"></f:message> :<input type="text" name="email"/>*
         <font color=red><form:errors path="user.email"></form:errors></font>
         <br/>
         <f:message code="age"></f:message>:<input type="text" name="age"/>*
         <font color=red><form:errors path="user.age"></form:errors></font>
         <br/>
         <f:message code="phone"></f:message>:<input type="text" name="phone"/>*
         <font color=red><form:errors path="user.phone"></form:errors></font>
         <br/>
        <f:message code="dob"></f:message><input type="text" name="dob"/>*
         <font color=red><form:errors path="user.dob"></form:errors></font>
         <br/>      
   <!-- 时间 输入格式  yyyy-MM-dd -->     
   <!-- 网址  http://www.baidu.com   http://ip:端口/ -->
        <button onclick="checkSubmit()"><f:message code="register"></f:message> </button>
     </form><br/>
 	</div>
  </body>
</html>

3.在mvc-servlet.xml中配置 获取本地资源

 <!-- 该拦截器用于拦截URL上参数  只是当jsp经过action之后 才会将当前国家和语言存储在session 同事从session中获取-->
  <mvc:interceptors>
  	<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  	<!-- 没传就读浏览器的 -->
  	<property name="paramName" value="a"></property>
  	</bean>
  	
  </mvc:interceptors>
  <!-- 参数需要被临时存储在某个地方 当用户再次访问使用之前设置的参数 -->
  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  </bean>

国际化验证

<!-- 将springmvc注解的action交给springmvc处理 国际化验证需要配置validator-->
  <mvc:annotation-driven  validator="localValidatorFactoryBean">
  	<mvc:message-converters>
<bean id="localValidatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  	<property name="validationMessageSource" ref="messageSource"></property>
  </bean>
验证

package springmvc.less04.entity;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class Userin {
	/**
	 * NotNull 属性名!=null
	 * NotEmpty 属性名!=null &!属性名e.quals("")
	 */
	@NotEmpty(message="{userError}")
	private String name;
	@NotEmpty(message="{pwd}")
	private String password;
	//.表示任意字符+大于等于1个字符\.表示.
	@Pattern(message="{eml}",regexp=".+@.+\\..+")
	private String email;
	@NotEmpty(message="{repwd}")
	private String repassword;
	@Size(min=11,max=11,message="{pho}")
	private String phone;
	@NotEmpty(message="{ag}")
	@Min(value=1,message="{ag1}")
	@Max(value=100,message="{ag2}")
	private String age;
	@Pattern(message="网址格式错误",regexp="^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$")
	private String ur;
	
	@Pattern(message="data",regexp="(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)")
	private String dob;
	
	public String getDob() {
		return dob;
	}
	public void setDob(String dob) {
		this.dob = dob;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	public String getUr() {
		return ur;
	}
	public void setUr(String ur) {
		this.ur = ur;
	}
}
controller层

package springmvc.less04.controller;
import java.io.OutputStream;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import springmvc.less04.entity.Userin;
	
@Controller
public class ViewController {
	@RequestMapping(value="/re",method=RequestMethod.POST)
	public String quert(@ModelAttribute("user") @Valid Userin user,BindingResult error){

		return "less04/re";
	}
	@Autowired
	MessageSource ms;
	@RequestMapping(value="/nation",method=RequestMethod.GET)
	public String quert(HttpServletResponse res, OutputStream os,Locale locale) throws Exception{
		res.setContentType("text/html;charset=UTF-8");
		os.write(ms.getMessage("password", null, locale).getBytes("UTF-8"));
		return null;
	}
	
	@RequestMapping(value="/mid",method=RequestMethod.GET)
	public String mid() throws Exception{
		return "less04/reg";
	}
	
	@RequestMapping(value="/myreg",method=RequestMethod.POST)
	public String quer(@ModelAttribute("user") @Valid Userin user,BindingResult error){
		if(!user.getPassword().equals(user.getRepassword())){
			error.addError(new FieldError("user","repassword","两次密码不一致"));
		}
		if(error.hasErrors()){
			return "less04/reg";
		}
		return "less03/suc";
	}
	
}





























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值