com.ourlife.dev.common.web.BaseController.java Source code

Java tutorial

Introduction

Here is the source code for com.ourlife.dev.common.web.BaseController.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/ourlife/dev">dev</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.ourlife.dev.common.web;

import com.google.common.collect.Maps;
import com.ourlife.dev.common.beanvalidator.BeanValidators;
import com.ourlife.dev.common.utils.DateUtils;
import com.ourlife.dev.modules.sys.entity.User;
import com.ourlife.dev.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ?
 * @author ourlife
 * @version 2013-3-23
 */
public abstract class BaseController {

    /**
     * 
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * ?Bean
     */
    @Autowired
    protected Validator validator;

    /**
     * ???
     * @param object ?
     * @param groups ?
     * @return ??true?? message 
     */
    protected boolean beanValidator(Model model, Object object, Class<?>... groups) {
        try {
            BeanValidators.validateWithException(validator, object, groups);
        } catch (ConstraintViolationException ex) {
            List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
            list.add(0, "??");
            addMessage(model, list.toArray(new String[] {}));
            return false;
        }
        return true;
    }

    /**
     * ???
     * @param object ?
     * @param groups ?
     * @return ??true?? flash message 
     */
    protected boolean beanValidator(RedirectAttributes redirectAttributes, Object object, Class<?>... groups) {
        try {
            BeanValidators.validateWithException(validator, object, groups);
        } catch (ConstraintViolationException ex) {
            List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
            list.add(0, "??");
            addMessage(redirectAttributes, list.toArray(new String[] {}));
            return false;
        }
        return true;
    }

    /**
     * Model?
     * @param message
     */
    protected void addMessage(Model model, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        model.addAttribute("message", sb.toString());
    }

    /**
     * Flash?
     * @param message
     */
    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
    }

    /**
     * ??
     * 1. ?StringHTML?XSS
     * 2. Date?String
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String??StringHTML?XSS
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date ?
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    protected static final int CODE_OK = 1;
    protected static final int CODE_FAILD = 1;
    protected static final String MSG_OK = "success";

    /**
     * json ??
     * @param code
     * @param msg
     * @return
     */
    protected Map withMap(Integer code, String msg) {
        HashMap map = Maps.newHashMapWithExpectedSize(2);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    protected User user() {
        return UserUtils.getUser();
    }

}