SpringMVC之服务端的校验

前端是可以校验数据的,那为什么还需要服务器校验呢?

最早的校验,就是服务端校验。早期的网站,用户输入一个邮箱地址,校验邮箱地址需要将地址发送到服务端,服务端进行校验,校验成功后,给前端一个响应。有了JavaScript,校验工作可以放在前端去执行。那么为什么还需要服务端校验呢? 因为前端传来的数据不可信。前端很容易获取都后端的数据接口,如果有人绕过页面,就会出现非法数据,所以服务端也要数据校验,总的来说:
1.前端校验要做,目的是为了提高用户体验
2.后端校验也要做,目的是为了数据安全

Springmvc本身没有校验功能,它使用hibernate的校验框架,hibernate的校验框架和orm没有关系

1、创建web项目,导入相关jar包

SpringMVC之服务端的校验_第1张图片
web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>springmvcfileuploaddisplay-name>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
 <servlet>
 	<servlet-name>springMvcservlet-name>
 	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
 	<init-param>
 		<param-name>contextConfigLocationparam-name>
 		<param-value>classpath:applicationContext.xmlparam-value>
 	init-param>
 	<load-on-startup>2load-on-startup>
 servlet>
 <servlet-mapping>
 	<servlet-name>springMvcservlet-name>
 	<url-pattern>/url-pattern>
 servlet-mapping>
 
 <filter>
 	<filter-name>encodingfilter-name>
 	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
 	<init-param>
 		<param-name>encodingparam-name>
 		<param-value>utf-8param-value>
 	init-param>
 	<init-param>
 		<param-name>forceRequestEncodingparam-name>
 		<param-value>trueparam-value>
 	init-param>
 	<init-param>
 		<param-name>forceResponseEncodingparam-name>
 		<param-value>trueparam-value>
 	init-param>
 filter>
 <filter-mapping>
 	<filter-name>encodingfilter-name>
 	<url-pattern>/*url-pattern>
 filter-mapping>
web-app>

applicationContext.xml



<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
		
		
		<context:component-scan base-package="com.zhouym.validate">context:component-scan>
		
		<mvc:annotation-driven validator="validator">mvc:annotation-driven>
		
		<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" id="validator">
			<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
			
			<property name="validationMessageSource" ref="validatemessageSource"/>
		bean>
		<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="validatemessageSource">
			<property name="basename" value="classpath:validateMessages"/>
			
			<property name="defaultEncoding" value="UTF-8"/>
			<property name="cacheSeconds" value="120"/>
		bean>
beans>

封装User对象,用来保存页面提交的信息

package com.zhouym.validate;

import javax.validation.constraints.Size;


public class User {
	//需要注意的是,如果给成员校验注解,但实际并没有对它进行校验,则会报错
	private int id;
	
	@Size(max=12,min=6,message="{USER_USERNAME_SIZE}")
	private String username;
	
	@Size(max=12,min=6,message="{USER_PASSWORD_SIZE}")
	private String password;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}	
	
}

Controller

package com.zhouym.validate;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
	//valadate对user对象中的属性已进行验证,并将验证结果放入BindingResult对象中
	@RequestMapping("/add")
	public String add(@Validated User user,BindingResult br,Model m) {
		//获取所有的errors信息
		List<ObjectError> allErrors = br.getAllErrors();
		if (allErrors != null && allErrors.size() > 0) {
			for (ObjectError objectError : allErrors) {
				System.out.println(objectError.getDefaultMessage());
			}			
		}
		//将验证消息放到作用域中
		m.addAttribute("errors",allErrors);
		return "/index.jsp";
	}
}

前端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
	<h1>用户管理:h1>
	<c:if test="${!empty errors }">
		<c:forEach items="${errors }" var="e">
			${e.defaultMessage }<br>
		c:forEach>
	c:if>
	<form action="add" method="post">
		用户名:<input type="text" name="username"><br>   码:<input type="password" name="password"><br>
		<input type='submit' value="提交">
	form>
body>
html>

SpringMVC之服务端的校验_第2张图片
测试结果
SpringMVC之服务端的校验_第3张图片

你可能感兴趣的:(Sping,MVC)