一.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;
}
}