com.yzsl.web.CommonController.java Source code

Java tutorial

Introduction

Here is the source code for com.yzsl.web.CommonController.java

Source

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

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yzsl.bean.User;
import com.yzsl.util.FastjsonFilter;

/**
 * get? Tomcat? conf/server.xml<Connector port="8080" />?<Connector port="8080" uRIEncoding="utf-8" />
 * 
 * ?
 * @author ThinkGem
 * @version 2013-3-23
 */
public abstract class CommonController {

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

    /**
     * current session's user
     * @return
     */
    protected User getCurrentUser() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        return user;
    }

    /**
     * ??
     * 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 : text.trim());
                //            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) {
                try {

                    setValue(DateUtils.parseDate(text, "MM-dd-yyyy", "MM/dd/yyyy", "yyyy-MM-dd", "yyyy/MM/dd"));
                    logger.debug("---" + getValue());
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    public void writeJson(HttpServletResponse response, Object object) {
        writeJsonByFilter(response, object, null, null);
    }

    /**
     * ??JSON???
     * 
     * @param object
     * @param includesProperties
     *            ??
     * @param excludesProperties
     *            ???
     */
    public void writeJsonByFilter(HttpServletResponse response, Object object, String[] includesProperties,
            String[] excludesProperties) {
        try {
            FastjsonFilter filter = new FastjsonFilter();// excludesincludes
            if (excludesProperties != null && excludesProperties.length > 0) {
                filter.getExcludes().addAll(Arrays.<String>asList(excludesProperties));
            }
            if (includesProperties != null && includesProperties.length > 0) {
                filter.getIncludes().addAll(Arrays.<String>asList(includesProperties));
            }
            //logger.info("JSON?[" + excludesProperties + "]??[" + includesProperties + "]");
            String json;
            String User_Agent = getRequest().getHeader("User-Agent");
            if (StringUtils.indexOfIgnoreCase(User_Agent, "MSIE 6") > -1) {
                // SerializerFeature.BrowserCompatible?\\uXXXX??IE6
                json = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat,
                        SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.BrowserCompatible);
            } else {
                // SerializerFeature.WriteDateUseDateFormat???yyyy-MM-dd hh24:mi:ss
                // SerializerFeature.DisableCircularReferenceDetect?
                json = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat,
                        SerializerFeature.DisableCircularReferenceDetect);
            }
            //logger.info("??JSON" + json);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(json);
            response.getWriter().flush();
            response.getWriter().close();
            //         getResponse().setContentType("text/html;charset=utf-8");
            //         getResponse().getWriter().write(json);
            //         getResponse().getWriter().flush();
            //         getResponse().getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * request
     * 
     * @return
     */
    public HttpServletRequest getRequest() {
        //      return ServletActionContext.getRequest();
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * response
     * 
     * @return
     */

    /**
     * session
     * 
     * @return
     */
    public HttpSession getSession() {
        //      return ServletActionContext.getRequest().getSession();
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

}