SpringMvc的簡單入門(二)之數據校驗

一.SpringMvc的數據校驗

 1.前端驗證是不安全的可以通過一些手段繞過 ,後端驗證是絕對安全的


創建maven項目,加載驗證的架包

<!-- jsr303的驗證框架 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.3.2.Final</version>
		</dependency>

在web.xml配置

<!-- 在使用springmvc的標籤或者國際化 都需要spring的支持 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%
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>My JSP 'reg.jsp' starting page</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 algin="centet">
     <form action="<%=path %>/reg" method="post"> 
         用戶名 :<input type="text" name="name"/>*
         <font color=red><form:errors path="user.name"></form:errors></font>
         <br/>
         密碼 :<input type="password" name="password"/>*
         <font color=red><form:errors path="user.password"></form:errors></font>
         <br/>
         重複密碼 :<input type="password" name="repassword"/>*
         <font color=red><form:errors path="user.repassword"></form:errors></font>
         <br/>
         郵件 :<input type="text" name="email"/>*
         <font color=red><form:errors path="user.email"></form:errors></font>
         <br/>
         年齡:<input type="text" name="age"/>*
         <font color=red><form:errors path="user.age"></form:errors></font>
         <br/>
         手機號碼:<input type="text" name="phone"/>*
         <font color=red><form:errors path="user.phone"></form:errors></font>
         <br/>
         網址:<input type="text" name="ur"/>*
         <font color=red><form:errors path="user.ur"></form:errors></font>
         <br/>
         出生日期:<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:端口/ -->
         <input type="button" οnclick="checkSubmit()" value="註冊"/>
     </form><br/>
 
  </body>
</html>

註解驗證

package springmvc.less03.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="用戶名不能爲空")
	private String name;
	@NotEmpty(message="密碼不能爲空")
	private String password;
	//.表示任意字符+大於等於1個字符\.表示.
	@Pattern(message="郵箱格式錯誤",regexp=".+@.+\\..+")
	private String email;
	@NotEmpty(message="再次輸入不能爲空")
	private String repassword;
	@Size(min=11,max=11,message="手機號碼必須是11位")
	private String phone;
	@NotEmpty(message="年齡不能爲空")
	@Min(value=1,message="年齡必須大於1")
	@Max(value=100,message="年齡必須小於100")
	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="時間格式錯誤",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;
	}
}


content層

package springmvc.less03.controller;
import javax.validation.Valid;
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.less03.entity.Userin;
	/**
	 * 後臺驗證步驟
	 * 1 Javabean添加註解
	 * 2 action中使用@Valid表示Javabean 使用Errors或者BindingResult判斷是否驗證失敗
	 * 3 出現jar包衝突 4.3.2Final
	 * @author Administrator
	 *
	 */
@Controller
public class RegController {
	@RequestMapping(value="/reg",method=RequestMethod.POST)
	public String quert(@ModelAttribute("user") @Valid Userin user,BindingResult error){
		//編程式驗證 
		if(!user.getPassword().equals(user.getRepassword())){
			error.addError(new FieldError("user","repassword","兩次密碼不一致"));
		}/**if(user.getAge()==null || "".equals(user.getAge().trim())){
			error.addError(new FieldError("userin", "age", "年齡不能爲空"));
		}else{
			
			Integer age;
			try {
				age = Integer.parseInt(user.getAge());
				if(age<1 || age>100){
					error.addError(new FieldError("userIn", "age", "年齡必須在1-100之間"));
				}
			} catch (Exception e) {
				error.addError(new FieldError("userIn", "age", "年齡必須是數字"));
			}
			
		}*/
		if(error.hasErrors()){
			return "/less03/reg.jsp";
		}
		return "/less03/suc.jsp";
	}
		
	
}


二.數據的傳輸

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'res.jsp' starting page</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">
	-->

  </head>
  
  <body>
   性別 :${requestScope.sex}
  </body>
</html>
package springmvc.less03.controller;

import java.util.Map;

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;
	/**
	 * springmvc中Model相關對象 是處理和數據相關的對象
	 *  @ModelAttribute 重命名 參數數據
	 * Model(ModelMap|Map)傳遞數據到視圖(request.setAttribute)
	 * ModelAndView 綁定數據到視圖 (ModelMap用於傳遞數據 View對象用於跳轉)
	 * @author Administrator
	 *
	 */
@Controller
public class ModeController {

	@RequestMapping(value="/case",method=RequestMethod.GET)
	public String case1(Map map) throws Exception{
		map.put("sex", "girl");
		return "/less03/res.jsp";
	}	
	@RequestMapping(value="/case2",method=RequestMethod.GET)
	public ModelAndView case2() throws Exception{
		ModelAndView mav=new ModelAndView();
		//跳轉路徑
		mav.setViewName("/less03/res.jsp");
		//傳值
		mav.addObject("sex", "boy");
		return mav;
	}
	
}
三.重定向和轉發

package springmvc.less01.hellow;

public class User {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


package springmvc.less03.controller;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import springmvc.less01.hellow.User;
//先檢查有沒有容器user
@SessionAttributes("user")

@Controller
public class SessionController {
	
	@ModelAttribute("user")
	public User getUser(){
		User user = new User();
		return user;
	}
	/**
	 * http://localhost:8080/s/se?id=1
	 * 請求轉發 forward: 不需要任何處理
	 * 請求重定向 redirect: 使用SessionAttribute方式 用於在重定向中傳值  將值存儲在session中 【用完記住清除】
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/se",method=RequestMethod.GET)
	public String case1(@ModelAttribute("user") User user) throws Exception{
		return "redirect:/re";
	}

	@RequestMapping(value="/re",method=RequestMethod.GET)
	public String case2(Map map,HttpServletResponse res,SessionStatus sessionStatus) throws Exception{
		User user=(User)map.get("user");
		res.getWriter().println(user.getId());
		//關閉session
		sessionStatus.setComplete();
		return null;
	}
	
}



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