springmvc interceptor

The source code of the interceptor is as follows

public interface HandlerInterceptor {
	boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception;
	void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception;
	void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception;

}

 

Let's first take a look at this method boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler), there is a handler in it, in fact, it belongs to HandlerMethod.

 

       public Object getBean() {
       //Get the control layer to be operated
		return this.bean;
	}

	public Method getMethod() {
      // get the method to operate
		return this.method;
	}
       public MethodParameter[] getMethodParameters() {
      // get the parameters to be manipulated
		return this.parameters;
	}

 

So this method operates after the front controller and before the real controller.

And postHandle contains ModleAndView, which is carried out after the real controller operation.

Write a regular verification class first, which privatizes the constructor, and all verification methods are class methods.

 

import org.springframework.util.StringUtils;

/**
* The class description specifically certifies the data format
* @author rfk
*/
public class ValueRuleValidator {
	private ValueRuleValidator() {}
	/**
	 * Use regular to verify whether the data is an integer
	 * @param str the data to be verified
	 * @return true if the data is all numbers, false otherwise
	 */
	public static boolean isInt(String str) {
		if(!StringUtils.isEmpty(str)) {
			return str.matches("\\d+");
		}
		return false;
	}
	/**
	 * Use regular to verify whether the data is of type long
	 * @param str the data to be verified
	 * @return If the data to be verified is all numbers, return true, otherwise return false
	 */
	public static boolean isLong(String str) {
		return isInt(str);
	}
	/**
	 * Use regular to verify whether the data is of type double
	 * @param str the data to be verified
	 * @return Returns true if the data to be verified is of Double type, otherwise returns false
	 */
	public static boolean isDouble(String str) {
		if(!StringUtils.isEmpty(str)) {
			return str.matches("\\d+(\\.\\d+)?");
		}
		return false;
	}
	/**
	 * Use regular to verify whether the data is of date type
	 * @param str the data to be verified
	 * @return If the verified data is of type xxxx-xx-xx, it returns true, otherwise it returns false, and the transmitted data needs to be processed into type xxxx-xx-xx in front
	 */
	public static boolean isDate(String str) {
		if(!StringUtils.isEmpty(str)) {
			return str.matches("\\d{4}-\\d{2}-\\d{2}");
		}
		return false;
	}
	/**
	 * Use regular to verify whether the data is of type xxxx-xx-xx xx:xx:xx
	 * @param str the data to be verified
	 * @return The verified data conforms to the standard format and returns true, otherwise it returns false
	 */
	public static boolean isDateTime(String str) {
		if(!StringUtils.isEmpty(str)) {
			str.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
		}
		return false;
	}
	/**
	 * Verify that the verification code entered by the user is the same as the background verification code
	 * @param str the verification code entered by the user
	 * @param rand The verification code obtained in the background
	 * @return If the verification code is the same, return true, otherwise return false;
	 */
	public static boolean isRand(String str,String rand) {
		if(!StringUtils.isEmpty(str) && !StringUtils.isEmpty(rand)) {
			return str.equalsIgnoreCase(rand);
		}
		return false;
	}
	/**
	 * Determine whether the data is of boolean type
	 * @param str the data to be verified
	 * @return If the data is boolen type, return true, otherwise false;
	 */
	public static boolean isBoolean(String str) {
		if(!StringUtils.isEmpty(str)) {
			return "true".equalsIgnoreCase(str)||"false".equalsIgnoreCase(str);
		}
		return false;
	}
	/**
	 *
	 * Rules written by @param rule
	 * @param contentType transfer data type
	 * @return
	 */
	public static boolean isPhoto(String rule,String contentType) {
		if(!StringUtils.isEmpty(rule)&&!StringUtils.isEmpty(contentType)) {
			String result [] =rule.split("\\|");
			for(int x=0;x<result.length;x++) {
				if(contentType.equalsIgnoreCase(result[x]))
					return true;
			}
		}
		return false;
	}
}

 

 Then write a data validation class, which is mainly for common data judgment;

 

/**
 * class description
 *
 * @author rfk
 */
public class ValidationUtil {
	private HttpServletRequest request;
	private String rule;
	private MessageSource message;
	private Map<String, String> map = new HashMap<>();

	public ValidationUtil(HttpServletRequest request, String rule, MessageSource message) {
		this.request = request;
		this.rule = rule;
		this.message = message;
		this.handleValidateion();
	}
	/**
	 *
	 * @return return validation error message
	 */
	public Map<String, String> getErrors() {
		return this.map;
	}

	/**
	 * Perform data validation
	 */
	private void handleValidateion() {
		String[] result = rule.split("//|");
		for (int x = 0; x < result.length; x++) {
			String[] temp = result[x].split(":");
			String parameterValue = this.request.getParameter(temp[0]);
			switch (temp[1]) {
			case "int":
				//int.msg=Verified data is not of type int
				if (!ValueRuleValidator.isInt(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("int.msg", null, null));
				}
				break;
			case "long":
				if (!ValueRuleValidator.isLong(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("long.msg", null, null));
				}
				break;
			case "double":
				if (!ValueRuleValidator.isDouble(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("int.msg", null, null));
				}
				break;
			case "string":
				if (!StringUtils.isEmpty(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("string.msg", null, null));
				}
				break;
			case "date":
				if (!ValueRuleValidator.isDate(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("date.msg", null, null));
				}
				break;
			case "datatime":
				if (!ValueRuleValidator.isDateTime(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("datetime.msg", null, null));
				}
				break;
			case "rand":
				if (!ValueRuleValidator.isRand(parameterValue,
						(String) this.request.getSession().getAttribute("rand"))) {
					this.map.put(temp[0], this.message.getMessage("rand.msg", null, null));
				}
				break;
			case "boolean":
				if (!ValueRuleValidator.isBoolean(parameterValue)) {
					this.map.put(temp[0], this.message.getMessage("boolean.msg", null, null));
				}
				break;
			}
		}
	}
}

 

Write a file upload class, mainly to judge the uploaded file

public class FileValidationUtil {
	private HttpServletRequest request;
	private MultipartResolver multipartResolver;
	private String key;
	private MessageSource messageSource;
	private Map<String, String> errors = new HashMap<>();
	/**
	 *
	 * @param request  
	 * @param multipartResolver encapsulated form
	 * @param key validation rules
	 * @param messageSource internationalized resource reading class
	 */
	public FileValidationUtil(HttpServletRequest request, MultipartResolver multipartResolver, String key,
			MessageSource messageSource) {
		super();
		this.request = request;
		this.multipartResolver=new CommonsMultipartResolver();
		this.key = key;
		this.messageSource = messageSource;
	}

	public void validateMime() {
		if (this.multipartResolver.isMultipart(request)) {
			String rule = this.messageSource.getMessage(this.key, null, null);
			if (request instanceof DefaultMultipartHttpServletRequest) {
				DefaultMultipartHttpServletRequest newRequest = (DefaultMultipartHttpServletRequest) request;
				Map<String, MultipartFile> filemap = newRequest.getFileMap();
				if (filemap.size() > 0) {
					Iterator<Map.Entry<String, MultipartFile>> iterator = filemap.entrySet().iterator();
					while (iterator.hasNext()) {
						Map.Entry<String, MultipartFile> mEntry = iterator.next();
						if (mEntry.getValue().getSize() > 0) {
							if (!ValueRuleValidator.isPhoto(rule, mEntry.getValue().getContentType())) {
								this.errors.put(mEntry.getKey(),
										messageSource.getMessage(this.key + "error", null, null));
							}
						}
					}

				}
			}
		}

	}
	public Map<String, String> getErrors() {
		return this.errors;
	}

}

 

write interceptor

 

public class VaildationInterceptor implements HandlerInterceptor {
	private static final Log log = LogFactory.getLog(VaildationInterceptor.class);
	@Resource
	private MessageSource message;

	/**
	 * This method is mainly after org.springframework.web.servlet.DispatcherServlet, Controller performs data validation
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod newHandler = (HandlerMethod) handler;
			// Splice out the key read by the resource file, such as emp.add
			String key = newHandler.getBean().getClass().getSimpleName() + "." + newHandler.getMethod();
			// Get rules based on key, such as emp.add=id:int|name:string|biredate:date
			String rule = this.message.getMessage(key, null, null);
			if (rule != null) {
				// Perform data authentication, here is mainly the authentication of standard data
				ValidationUtil validat = new ValidationUtil(request, rule, message);
				//Basic data validation, if there is an error return false
				/* ValidationUtil validat = new ValidationUtil(request, rule, message);
				 * FileValidationUtil fileValidationUtil =new FileValidationUtil(request, key, message);
				 * if (validat.getErrors().size() > 0 ||fileValidationUtil.getErrors().size() > 0 ) {
				 * 		if(validat.getErrors().size() > 0){
				 * //How to do it
				 * 			}
				 * 		if(fileValidationUtil.getErrors().size() > 0){
				 * //How to do it
				 * 			}
				 * 		if(validat.getErrors().size() > 0 &&fileValidationUtil.getErrors().size() > 0 ){
				 * //How to do it.
				 * 		}
					// If there is data that has not passed the authentication, put the data in errors
					request.setAttribute("errors", validat.getErrors());
					String errorsUrl = null;
					try {
						// For example, the emp.add.err.page page is the page where the data is added
						errorsUrl = this.message.getMessage(key + ".error.page", null, null);
					} catch (Exception e) {
						errorsUrl = this.message.getMessage("error.page", null, null);
						log.error(e);
					}
					request.getRequestDispatcher(errorsUrl).forward(request, response);
					return false;
				}
				 */
				if (validat.getErrors().size() > 0) {
					// If there is data that has not passed the authentication, put the data in errors
					request.setAttribute("errors", validat.getErrors());
					String errorsUrl = null;
					try {
						// For example, the emp.add.err.page page is the page where the data is added
						errorsUrl = this.message.getMessage(key + ".error.page", null, null);
					} catch (Exception e) {
						errorsUrl = this.message.getMessage("error.page", null, null);
						log.error(e);
					}
					request.getRequestDispatcher(errorsUrl).forward(request, response);
					return false;
				}else {
					//If there is no error in the basic data judgment, it must enter here, so it is necessary to judge whether there is an error here, return false if there is an error, and return true if there is no error
					/*Originally wanted to talk about the validation here and put it after ValidationUtil validat = new ValidationUtil(request, rule, message);
					 * Later, it was found that if it was placed behind him, the judgment was wrong. After using || judgment, it was still necessary to judge when the error was placed.
					 */
					FileValidationUtil fileValidationUtil =new FileValidationUtil(request, key, message);
					if(fileValidationUtil.getErrors().size()>0) {
						request.setAttribute("errors", validat.getErrors());
						String errorsUrl = null;
						try {
							// For example, the emp.add.err.page page is the page where the data is added
							errorsUrl = this.message.getMessage(key + ".error.page", null, null);
						} catch (Exception e) {
							errorsUrl = this.message.getMessage("error.page", null, null);
							log.error(e);
						}
						request.getRequestDispatcher(errorsUrl).forward(request, response);
						return false;
					}
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//This method is mainly performed after the controller, so the modelerAndview can be obtained here
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// final execution
	}

}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326672199&siteId=291194637