SpringMvc的簡單入門(三)之國際化

一.視圖解析

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 οnclick="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";
	}
	
}





























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章