package cn.xxx.base;

import cn.xxx.gecustomer.beans.GeCustomer;
import cn.xxx.gecustomer.beans.GeCustomerProperty;
import cn.xxx.utils.UserPersonalConstant;
import cn.xxx.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 所有controller的基类
 *
 * @author
 *
 */
public abstract class BaseController extends ApplicationObjectSupport {

    public Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${project.version}")
    public String ver;

    /**
     * 要跳转的页面
     *
     * @Title: go
     * @Description: TODO
     * @param path
     * @return
     * @author  2017年9月15日 下午1:51:10
     */
    protected ModelAndView go(String path) {
        return new ModelAndView(path);
    }

    /**
     * 到bean信息
     *
     * @param name
     * @return
     */
    protected Object getObject(String name) {
        return this.getApplicationContext().getBean(name);
    }

    /**
     * 获取登录用户信息
     *
     * @return
     */
    public IUserInfo getUserSessionVo() {
        Subject subject = SecurityUtils.getSubject();
        Object obj = null;//subject.getSession().getAttribute(UserAuthenticationRealm.LOGIN_SESSION_ATTR);
        if (obj instanceof IUserInfo) {
            return (IUserInfo) obj;
        }
        return null;
    }

    public String getOrganCode() {
        return (String) this.getSession().getAttribute(WebUtil.ORGAN_CODE);
    }

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpSession getSession() {
        return getRequest().getSession();
    }

    public HttpServletResponse getResponse() {
        return  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取国际化信息
     *
     * @param key
     * @return
     */
    public String getI18nMsg(String key) throws Exception {
        // 从后台代码获取国际化信息
        String value = new RequestContext(this.getRequest()).getMessage(key);
        return value != null ? value : "";
    }

    /**
     * 返回国际化国家标识串
     *
     * @return
     * @throws Exception
     */
    public String getI18nCountry() throws Exception {
        String lc = null;
        RequestContext requestContext = new RequestContext(this.getRequest());
        String language = requestContext.getLocale().getLanguage();
        String country = requestContext.getLocale().getCountry();
        if (country == null || "".equals(country)) {
            if ("zh".equals(language)) {
                country = "CN";
            } else if ("en".equals(language)) {
                country = "US";
            }
        }
        // logger.debug("本地国际化语言:" + language + "本地国际化国家:" + country);
        lc = "_" + language + (StringUtils.isEmpty(country) ? "" : "_" + country);
        return lc;
    }

    /**
     * 请求方式判断
     *
     * @param request
     * @return
     */
    public boolean isAjaxRequest(HttpServletRequest request) {
        if (!(request.getHeader("accept").indexOf("application/json") > -1
                || (request.getHeader("X-Requested-With") != null
                        && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)
                || "XMLHttpRequest".equalsIgnoreCase(request.getParameter("X_REQUESTED_WITH")))) {
            return false;
        }
        return true;
    }
    /**
     * 保存信息到request中
     *
     * @param key
     * @param value
     */
    public void setRequestAttribute(String key, Object value) {
        this.getRequest().setAttribute(key, value);
    }

    protected String getCookie(String cookieName) {
        Cookie[] cookies = getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }

        return null;
    }

    /**
     * 设置 cookie
     *
     * @param cookieName
     * @param value
     * @param age
     */
    protected void setCookie(String cookieName, String value, int age) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setMaxAge(age);
        // cookie.setHttpOnly(true);
        getResponse().addCookie(cookie);
    }

    /**
     * 返回成功信息对象
     *
     * @return
     */
    public ReturnInfoVo<Object> getReturnSuccessVo() throws Exception {
        return new ReturnInfoVo<Object>(true, this.getI18nMsg(Constants.COMMON_SUCCESS_MSG_KEY));
    }

    /**
     * 解析返回信息,处理国际化部分
     *
     * @param riv
     * @return
     */
    public <T> ReturnInfoVo<T> returnInfoVoParser(ReturnInfoVo<T> riv) {
        try {
            List<ReturnInfoVo<T>.MsgVo> msgList = riv.getMsgList();
            if (!msgList.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                ReturnInfoVo<T>.MsgVo msg;

                String info;
                for (int i = 0; i < msgList.size(); i++) {
                    msg = msgList.get(i);

                    if (Constants.NEEDI18N) {
                        info = this.getI18nMsg(msg.getMsg());
                    } else {
                        info = msg.getMsg();
                    }
                    if (msg.getParams() != null && msg.getParams().length > 0) {
                        info = String.format(info, msg.getParams());
                    }
                    sb.append(info);

                    sb.append(";");
                    if (i != msgList.size() - 1) {
                        sb.append("\r\n");
                    }

                }
                riv.setMsg(sb.toString());
            } else {
                if (riv.isSuccess()) {
                    riv.setMsg(this.getI18nMsg(Constants.COMMON_SUCCESS_MSG_KEY));
                } else {
                    riv.setMsg(this.getI18nMsg(Constants.COMMON_FAILED_MSG_KEY));
                }
            }
        } catch (Exception e) {
            logger.error("解析返回信息对象失败", e);
        }
        return riv;
    }

    /**
     * 方法名称: render<br>
     * 描述:返回给浏览器
     */
    public void render(String text, String contentType){
        HttpServletResponse response;
        try{
          response = getResponse();
          response.setContentType(contentType);
          response.getWriter().write(text);
          response.getWriter().flush();
        }
        catch (IOException e) {
          throw new IllegalStateException(e);
        }
    }

    /**
     * 方法名称: renderText<br>
     * 描述:返回普通文本浏览器
     */
    public void renderText(String text){
        render(text, "text/plain;charset=UTF-8");
    }

    /**
     * 方法名称: renderJson<br>
     * 描述:返回JSON格式数据
     */
    public void renderJson(String text){
        render(text,"text/json;charset=UTF-8");
    }

    /**
     * 方法名称: getCurrentLoginGeCustomer<br>
     * 描述:获取当前登录用户<br>
     *     保全、登录
     * 作者: <br>
     * 修改日期:2014-9-30下午07:06:26<br>
     */
    protected GeCustomer getCurrentLoginGeCustomer() {
        Object obj = this.getRequest().getSession().getAttribute(UserPersonalConstant.LOGIN_USER);
        if (obj instanceof GeCustomer) {
            return (GeCustomer) obj;
        } else {
            return null;
        }
    }

    /**
     * 方法名称: getCurrentLoginGeCustomerProperty<br>
     * 描述:获取当前登录用户属性信息<br>
     * 作者: <br>
     * 修改日期:2014-9-30下午07:06:26<br>
     */
    protected GeCustomerProperty getCurrentLoginGeCustomerProperty() {
        Object obj = this.getRequest().getSession().getAttribute(UserPersonalConstant.LOGIN_USER_PROPERTY);
        if (obj instanceof GeCustomerProperty) {
            return (GeCustomerProperty) obj;
        } else {
            return null;
        }
    }

    /**
     * 获取农银在线登录用户 <br/>
     * Date: 2017年6月8日 下午4:51:55
     *    绑定、产品、支付
     * @author
     * @param
     * @return
     */
    protected GeCustomer getOnlineCurrentLoginGeCustomer() {
        Object obj = this.getRequest().getSession().getAttribute(UserPersonalConstant.ONLINE_LOGIN_USER);
        if (obj instanceof GeCustomer) {
            return (GeCustomer) obj;
        } else {
            return null;
        }
    }

    /**
     * 方法名称:initCurrentLoginGeCustomer<br>
     * 描述:存放登录用户信息<br>
     * 作者:<br>
     * 修改日期:2014年8月18日下午7:57:07<br>
     */
    protected void initCurrentLoginGeCustomer() {
        Object obj = this.getRequest().getSession().getAttribute(UserPersonalConstant.LOGIN_USER);
        if (obj != null && obj instanceof GeCustomer) {
            // 有登陆用户,带登陆信息到填写投保信息页
            this.setRequestAttribute("geCustomer", (GeCustomer) obj);
        }
    }

    /**
     * 方法名称: getUUID<br>
     * 描述:获得唯一标识(目前用于验证表单提交唯一性)<br>
     * 作者: <br>
     * 修改日期:2014年10月13日上午3:15:24<br>
     */
    protected String getUUID() {
        return UUID.randomUUID().toString();
    }

}

工具类封装之--BaseController的更多相关文章

  1. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  2. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  3. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  4. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  5. (转载) 百度地图工具类封装(包括定位,附近、城市、范围poi检索,反地理编码)

    目录视图 摘要视图 订阅 赠书 | 异步2周年,技术图书免费选      程序员8月书讯      项目管理+代码托管+文档协作,开发更流畅 百度地图工具类封装(包括定位,附近.城市.范围poi检索, ...

  6. 小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_40、Redis工具类封装讲解和实战

    笔记 4.Redis工具类封装讲解和实战     简介:高效开发方式 Redis工具类封装讲解和实战         1.常用客户端 https://redisdesktop.com/download ...

  7. flink---实时项目--day02-----1. 解析参数工具类 2. Flink工具类封装 3. 日志采集架构图 4. 测流输出 5. 将kafka中数据写入HDFS 6 KafkaProducer的使用 7 练习

    1. 解析参数工具类(ParameterTool) 该类提供了从不同数据源读取和解析程序参数的简单实用方法,其解析args时,只能支持单只参数. 用来解析main方法传入参数的工具类 public c ...

  8. 关于TornadoFx和Android的全局配置工具类封装实现及思路解析

    原文地址: 关于TornadoFx和Android的全局配置工具类封装实现及思路解析 - Stars-One的杂货小窝 目前个人开发软件存在设置页面,可以让用户自定义些设置,但我发现,存储数据的代码逻 ...

  9. Android Sqlite 工具类封装

    鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用. 该封装类主要支持一下功能 支持多用户数据储存 支持 Sqlite数据库升级 支持传入 Sql 语句建表 支持 SQLit ...

随机推荐

  1. WCF部署失败

    HTTP 错误 404.3 - Not Found 由于扩展配置问题而无法提供您请求的页面.如果该页面是脚本,请添加处理程序.如果应下载文件,请添加 MIME 映射. 最可能的原因:•可能是缺少处理程 ...

  2. vue项目打包之后js文件过大怎么办?

  3. spring框架学习之--数据库操作增删改查

    基于spring的NamedParameterJdbcTemplate操作数据库 首先在 resources 文件夹下添加数据库配置文件jdbc.properties 配置常用的数据库信息 consu ...

  4. ASP.NET微信支付XXE漏洞修复

    1. XXE场景 关于XML解析存在的安全问题指引 微信支付商户,最近暴露的XML外部实体注入漏洞(XML External Entity Injection,简称 XXE),该安全问题是由XML组件 ...

  5. emqx源码编译

    1  下载  github上下载 2  找台虚拟机,安装编译所需的环境,erlang   make等 3  执行make命令 重点说一下第3步: 主要是make命令报错 解释:执行make命令后,依赖 ...

  6. 细说@Html.ActionLink()的用法(转)

    细说@Html.ActionLink()的用法   一.@Html.ActionLink()概述 在MVC的Rasor视图引擎中,微软采用一种全新的方式来表示从前的超链接方式,它代替了从前的繁杂的超链 ...

  7. #WEB安全基础 : HTTP协议 | 0x14 HTTP的详细安全问题

    我们提到过HTTP是不安全的. 由于任何人都可以向服务器发送请求,而并不会验证身份,所以这就会引发一些问题: 1,发出响应的服务器是否为正确的服务器 2,发送请求的客户端是否为正确的客户端 3,通信双 ...

  8. Asp.net(C#)年月日时分秒毫秒

    年月日时分秒毫秒格式:yyyyMMddHHmmssfff

  9. WCF基础二

    1:地址 . WCf 的每一个服务都有一个唯一地址,地址包括传输协议和服务位置. HTTP:采用http\https协议进行传输,默认端口为80. TCP:采用ne.tcp协议进行传输,默认端口为80 ...

  10. MyBatis探究-----核心配置文件mybatis-config.xml中配置mappers的几种方式

    1.package name="映射文件所在包名" 必须保证接口名(例如IUserDao)和xml名(IUserDao.xml)相同,还必须在同一个包中 例如:<packag ...