zoukankan      html  css  js  c++  java
  • 通过web页面修改nginx配置

    资源路径:https://download.csdn.net/download/song_yan_/12002460

    nginx动态配置

    一、页面展示

     

    二、前端代码

    (1)jsp页面(nginxConfig.jsp

    <%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/plugins/zTree/metroStyle/metroStyle.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/public/nginx.css">
    </head>
    <body>
        <div class="btn_group">
            <button type="button" id="btn_add" class="btn btn-primary" onclick="save()">保存</button>
            <button type="button" id="btn_add" class="btn btn-primary" onclick="start()">启动</button>
            <button type="button" id="btn_add" class="btn btn-primary" onclick="stop()">停止</button>
            <button type="button" id="btn_add" class="btn btn-primary" onclick="restart()">重启</button>
        </div>
        <pre id="editor">${content}</pre>
        <script src="${pageContext.request.contextPath}/static/plugins/layui/2.4.3/layui.all.js"></script>
        <script src="${pageContext.request.contextPath}/static/plugins/ace/ace.js"></script>
        <script src="${pageContext.request.contextPath}/static/plugins/ace/ext-language_tools.js"></script>
        <script >
            var contextPath = "${pageContext.request.contextPath}"
            var $ = layui.jquery
    
            //初始化配置文件区域的高度
            var height = document.body.clientHeight - 100;
            $("#editor").height(height + "px")
    
            //初始化文件编辑组件
            ace.require("ace/ext/language_tools");
            var editor = ace.edit("editor");
            editor.setOptions({
                enableBasicAutocompletion : true,
                enableSnippets : true,
                enableLiveAutocompletion : true,
            });
            editor.setTheme("ace/theme/monokai");
            editor.getSession().setMode("ace/mode/text");
            editor.setFontSize(16);
    
            //保存配置文件
            function save() {
                var fileContent = editor.getValue()
                var index = layer.load();
                $.ajax({
                    url : contextPath + "/nginx/save",
                    data : {
                        fileContent : fileContent
                    },
                    type : "POST",
                    dataType : 'json',
                    success : function(data) {
                        layer.close(index);
                        if (data.flag) {
                            layer.alert(data.msg, {
                                icon : 1
                            });
                        } else {
                            alert()
                            layer.alert(data.msg, {
                                icon : 5
                            });
                        }
                    }
                })
            }
    
            //启动nginx
            function start() {
                var index = layer.load();
                $.ajax({
                    url : contextPath + "/nginx/start",
                    data : {},
                    type : "POST",
                    dataType : 'json',
                    success : function(data) {
                        layer.close(index);
                        if (data.success) {
                            layer.alert(data.msg, {
                                icon : 1
                            });
                        } else {
                            layer.alert(data.msg, {
                                icon : 5
                            });
                        }
                    }
                })
            }
    
            //停止nginx
            function stop() {
                var index = layer.load();
                $.ajax({
                    url : contextPath + "/nginx/stop",
                    data : {},
                    type : "POST",
                    dataType : 'json',
                    success : function(data) {
                        layer.close(index);
                        if (data.success) {
                            layer.alert(data.msg, {
                                icon : 1
                            });
                        } else {
                            layer.alert(data.msg, {
                                icon : 5
                            });
                        }
                    }
                })
            }
    
            //重启nginx
            function restart() {
                var index = layer.load();
                $.ajax({
                    url : contextPath + "/nginx/reStart",
                    type : "POST",
                    dataType : 'json',
                    success : function(data) {
                        layer.close(index);
                        if (data.success) {
                            layer.alert(data.msg, {
                                icon : 1
                            });
                        } else {
                            layer.alert(data.msg, {
                                icon : 5
                            });
                        }
                    }
    
                })
            }
        </script>
    </body>
    </html>

    (2)Js(见附件)

    (3)Css(见附件)

    三、配置信息

    (1)配置:在global.properties文件中配置

     

    (1)使用(在NginxService.java中会使用到):

     

    四、Controller代码(NginxController .java)

    package com.googosoft.controller.fzgn.rz;
    
    import java.io.IOException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    import com.googosoft.controller.base.BaseController;
    import com.googosoft.service.nginx.NginxService;
    
    /** 
    * @author sonyan
    * @version 2019年11月27日 下午3:22:59 
    * @desc nginx
    */
    
    @Controller
    @RequestMapping(value="/nginx")
    public class NginxController extends BaseController{
        @Autowired
        private NginxService nginxService;
        
        /**
         * 跳转到nginx配置页面
         * @return
         * @throws IOException
         */
        @RequestMapping(value="/nginx")
        public ModelAndView nginx() throws IOException{
            ModelAndView mv = this.getModelAndView();
            mv.addObject("content", nginxService.getConfContent());
            mv.setViewName("/nginx/nginxConfig"); 
            return mv;
        }
        
        /**
         * nginx重启
         * @return
         */
        @RequestMapping("/reStart")
        @ResponseBody
        public  Object reStart() {
            return nginxService.reStart();
        }
        
        /**
         * 保存配置文件
         */
        @RequestMapping("/save")
        @ResponseBody
        public Object save(String fileContent){
            return nginxService.save(fileContent);
        }
        
        /**
         * 代理开启
         * @return
         */
        @RequestMapping("/start")
        @ResponseBody
        public Object start() {
            return nginxService.start();
        }
    
        /**
         * 代理关闭
         * @return
         */
        @RequestMapping("/stop")
        @ResponseBody
        public Object stop() {
            return nginxService.stop();
        }
    
    } 

    五、Service代码(NginxService .java)

    package com.googosoft.service.nginx;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.ResourceBundle;
    import org.springframework.stereotype.Service;
    
    import com.googosoft.controller.fzgn.rz.NginxUtil;
    import com.googosoft.service.base.BaseService;
    import com.googosoft.util.FileUtil;
    import com.googosoft.util.Validate;
    
    /** 
    * @author sonyan
    * @version 2019年11月27日 下午4:22:08 
    * @desc
    */
    @Service("nginxService")
    public class NginxService extends BaseService{
        String nginxPath = ResourceBundle.getBundle("global").getString("nginxPath");
        String nginxConfPath = ResourceBundle.getBundle("global").getString("nginxConfPath");
        String nginxConfDir = ResourceBundle.getBundle("global").getString("nginxConfDir");
        
        /**
         * 获取配置文件的内容
         * @return
         */
        public String getConfContent() {
            try {
                return readToString(nginxConfPath,"UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }
        
        /**
         * nginx重启
         * @return
         */
        public Map<String, Object> reStart() {
            Map<String, Object> relSet =new HashMap<String, Object>();
            boolean success = false;
            String msg = "";
            if (NginxUtil.getNginxProcessStatus()) {
                try {
                    NginxUtil.killProc();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (NginxUtil.getNginxProcessStatus()) {
                        msg = "代理关闭时出错";
                    }
                }
                try {
                    NginxUtil.startProc(nginxPath);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (NginxUtil.getNginxProcessStatus()) {
                        msg = "代理重启成功";
                        success = true;
                    } else {
                        msg = "代理启动时出错";
                    }
                }
            }else{
                msg = "代理未启动";
            }
            relSet.put("msg", msg);
            relSet.put("success", success);
            return relSet;
        }
        
        /**
         * 保存配置文件内容
         * @param fileContent
         * @return
         */
        public Map<String, Object> save(String fileContent) {
            Map<String, Object> relSet = new HashMap<>();
            try{
                FileUtil.writeStringToFile(nginxConfPath, fileContent);
                relSet.put("flag", true);
                relSet.put("msg", "配置文件保存成功.");
            }catch(Exception e){
                e.printStackTrace();
                relSet.put("flag", false);
                relSet.put("msg", "配置文件保存失败.");
            }
            return relSet;
        }
        
        /**
         * nginx启动
         * @return
         */
        public Map<String, Object> start() {
            Map<String, Object> relSet = new HashMap<>();
            boolean success = false;
            String msg = "";
    
            if (!NginxUtil.getNginxProcessStatus()) {
                try {
                    NginxUtil.startProc(nginxPath);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (NginxUtil.getNginxProcessStatus()) {
                        msg = "代理开启成功";
                        success = true;
                    } else {
                        msg = "代理开启失败";
                    }
                }
            } else {
                msg = "代理已开启";
            }
    
            relSet.put("msg", msg);
            relSet.put("success", success);
            return relSet;
        }
        
        /**
         * nginx停止
         * @return
         */
        public Map<String, Object> stop() {
            Map<String, Object> relSet = new HashMap<>();
            boolean success = false;
            String msg = "";
    
            if (NginxUtil.getNginxProcessStatus()) {
                try {
                    NginxUtil.killProc();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (!NginxUtil.getNginxProcessStatus()) {
                        msg = "代理关闭成功";
                        success = true;
                    } else {
                        msg = "代理关闭失败";
                    }
                }
            }else{
                msg = "代理未启动";
            }
            
            relSet.put("msg", msg);
            relSet.put("success", success);
            return relSet;
        }
        
        public String readToString(String filePath,String enconding) throws IOException {
            File file = new File(filePath);
            Long filelength = file.length();
            byte[] filecontent = new byte[filelength.intValue()];
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
            return new String(filecontent, Validate.isNullToDefaultString(enconding, "UTF-8") );
        }
    
    }

    六、工具类

    (1)NginxUtil.java

    package com.googosoft.controller.fzgn.rz;
    
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.SocketTimeoutException;
    
    /**
     * @Description: nginx工具类
     * @author songyan
     * @date 2019年08月01日 下午05:26:01
     */
    public class NginxUtil {
        private static InetAddress ip  ;
        private static int port=80;
        private static String NginxWindowsPath = "D://nginx-1.16.1";
    
        /**
         * @desc 判断进程是否开启
         */
        public static boolean getNginxProcessStatus() {
            boolean result = false;
            Socket connect = new Socket();
            try {
                connect.connect(new InetSocketAddress(ip,port), 1000); // 连接服务器,每隔1秒重试
                result = connect.isConnected();
                return result;
            } catch (SocketTimeoutException e) {
                result = false;
                return result;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    connect.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 跨平台启动nginx
         * @throws IOException
         */
        public static void startProc(String nginxPath) throws IOException {
                startWinProc(nginxPath);
        }
    
        /**
         * 跨平台关闭nginx
         * @throws IOException
         */
        public static void killProc() throws IOException {
                KillWin();
        }
    
        /**
         * 开启windows系统的nginx
         * @throws IOException
         */
        private static void startWinProc(String nginxPath) throws IOException {
            String command = "cmd /c start nginx";
            CommandUtil.executeCmd(command,  nginxPath);
        }
    
        /**
         * 关闭windows系统的nginx
         * @throws IOException
         */
        public static void KillWin() throws IOException {
            CommandUtil.executeCmd("taskkill /F /IM nginx.exe");
        }
        
    }

    (2)CommandUtil.java

    package com.googosoft.controller.fzgn.rz;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    /**
     * @author sonyan
     * @version 2019年9月12日 下午5:27:02
     * @desc
     */
    public class CommandUtil {
    
        public static String executeCmd(String command) throws IOException {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder build = new StringBuilder();
            while ((line = br.readLine()) != null) {
                build.append(line);
            }
            return build.toString();
        }
    
        public static Process executeCmd(String command, String dirPath) throws IOException {
            File dir = new File(dirPath);
            String[] str = new String[] {};
            return Runtime.getRuntime().exec(command, str, dir);
        }
    
        public static Process getProcessByProcessBuilder(String command, String filePath) {
            Process proc = null;
            try {
                ProcessBuilder pb = new ProcessBuilder("cmd", "/c", command);
                pb.directory(new File(filePath));
                proc = pb.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return proc;
        }
    
        public static Process getProcessByRuntime(String command, String filePath) {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(command, null, new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return process;
        }
        
        
    }
  • 相关阅读:
    20172318 2017-2018-2 《程序设计与数据结构》第5周学习总结
    20172318 2017-2018-2 《程序设计与数据结构》第4周学习总结
    20172318 2017-2018-2 《程序设计与数据结构》实验1报告
    20172318 《程序设计与数据结构》第三周学习总结
    20172318 2017-2018-2 《程序设计与数据结构》第2周学习总结
    20172318 2016-2017-2 《Java程序设计》第一周学习总结
    寒假作业03
    寒假作业02
    20172311 2017-2018-2 《程序设计与数据结构》第五周学习总结
    20172311 《程序设计与数据结构》第四周学习总结
  • 原文地址:https://www.cnblogs.com/excellencesy/p/11947060.html
Copyright © 2011-2022 走看看