# BaseController 基礎Controller 工具類

MarlonBrando1998發表於2020-12-23

BaseController 基礎Controller 工具類

  • 工具類BaseController沒啥好說的直接上程式碼:獲取引數、分頁查詢、當前使用者獲取、EsSql查詢分裝等
/**
 * @description: 基礎的類
 * @author: Lidong
 * @time: 2020/7/29 21:14
 **/
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    protected HttpServletRequest request;

    /**
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @Author LiDong
     * @Description //TODO 處理HttpServletRequest拿到引數的Map
     * @Date 20:17 2020/11/30
     * @Param [request]
     **/
    public Map<String, String> getParamMap(HttpServletRequest request) {
        try {
            if (Objects.isNull(this.request)) {
                this.request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            }
            Map<String, String[]> parameterMap = this.request.getParameterMap();
             Map<String, String> map = new HashMap<>(16);
            if (parameterMap != null && parameterMap.size() > 0) {
                for (String key : parameterMap.keySet()) {
                    String[] strings = parameterMap.get(key);
                    String value = Arrays.asList(strings).get(0);
                    map.put(key, String.valueOf(value));
                }
                return map;
            }
            return new HashMap<>(1);
        } catch (Exception e) {
            logger.error("=====>getParamMap()出錯", e.getMessage(), e);
            return new HashMap<>(1);
        }
    }

    /**
     * @return com.li.core.domain.common.CurrentUser
     * @Author LiDong
     * @Description //TODO 得到當前Session中的資訊
     * @Date 20:07 2020/11/30
     * @Param []
     **/
    public CurrentUser getCurrentUser() {
        try {
            if (Objects.isNull(request)) {
                request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            }
            Object user = request.getSession().getAttribute("user");
            if (user == null) {
                return null;
            }
            CurrentUser currentUser = (CurrentUser) user;
            return currentUser;
        } catch (Exception e) {
            logger.error("=====>getCurrentUser()出錯", e.getMessage(), e);
            return null;
        }

    }

    /**
     * 封裝Post查詢Es中的結果
     */
    public String getEsResultBysql(String sql) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            // 請求的Url
            String urlLocation = "http://127.0.0.1:9200/_sql";
            // 請求體
            String content = "{\"query\":\"" + sql + "\"}";
            URL realUrl = new URL(urlLocation);
            // 開啟和URL之間的連線
            URLConnection conn = realUrl.openConnection();
            // 設定通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 傳送POST請求必須設定如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            ((HttpURLConnection) conn).setRequestMethod("POST");
            // 獲取URLConnection物件對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 傳送請求引數
            out.print(content);
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("傳送 POST 請求出現異常!" + e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @return void
     * @Author LiDong
     * @Description //TODO 分頁查詢
     * @Date 20:17 2020/11/30
     * @Param [request]
     **/
    public void getPageInit(HttpServletRequest request) {
        try {
            Map<String, String> paramMap = getParamMap(request);
            int pagenumber = Integer.parseInt(paramMap.getOrDefault("pageNumber", "1"));
            int pagesize = Integer.parseInt(paramMap.getOrDefault("pageSize", "10"));
            PageHelper.startPage(pagenumber, pagesize);
        } catch (Exception e) {
            logger.info("=====>getPage()出錯!", e.getMessage(), e);
        }
    }

}

相關文章