使用SSM框架对练习1进行的改进。练习1:使用java实现Linux后台程序运行状态实时显示
新建数据库,主键id设置自增
新建maven项目,导入jar包:ganymed-ssh2-build210.jar
maven配置:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wang</groupId> <artifactId>web</artifactId> <version>1.0-SNAPSHOT</version> <modules> <module>idea-Linux</module> </modules> <packaging>pom</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!-- jsp-api--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <!-- junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <!-- mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.8</version> </dependency> <!-- lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> <!-- spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <!-- servlet-api--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> </dependencies> <!-- 在bulid中配置resources,来防止我们资源导出失败问题--> <build> <resources> <resource> <directory>javaweb/src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>javaweb/src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>7</source> <target>7</target> </configuration> </plugin> </plugins> </build> </project>
项目中添加依赖:
<!-- 使用StringUtils.strip(str,"[]")用以去掉字符串头尾的中括号--> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
创建目录com.wang.utils,连接Linux,LinuxUtils:
package com.wang.utils; import ch.ethz.ssh2.Connection; import java.io.IOException; public class LinuxUtils { private static String hostname = "xxx.xxx.xxx"; private static String username = "root"; private static String password = "xxxxxx"; public static Connection getConnection() throws IOException { Connection conn = new Connection(hostname); conn.connect(); conn.authenticateWithPassword(username, password); return conn; } }
连接Mybatis,MybatisUtils:
package com.wang.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MybatisUtils { // 提升作用域 private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis第一步:获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
mybatis配置,mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration核心配置文件--> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/bank?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="xxxxxx"/> </dataSource> </environment> </environments> <!-- 每一个Mapper.xml都需要在Mybatis核心配置文件中注册--> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
spring配置,springmvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理--> <context:component-scan base-package="com.wang.controller"/> <!-- 让Spring MVC不处理静态资源 .css .js .html .mp3 .mp4--> <mvc:default-servlet-handler/> <!-- 支持mvc注解驱动--> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 后缀--> <property name="suffix" value=".jsp"/> </bean> </beans>
新建UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.wang.mapper.UserMapper"> </mapper>
基础配置完成。项目目录如下:
新建实体类User:
package com.wang.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //实体类 @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pid; private String ppid; private String status; private String date; }
用于处理字符串的实体类Hello:
package com.wang.pojo; import org.apache.commons.lang.StringUtils; import java.util.Arrays; public class Hello extends Object{ private String[] str; public void setStr(String[] str) { this.str = str; } @Override public String toString() { return StringUtils.strip(Arrays.toString(str),"[]"); } }
新建接口UserMapper:
package com.wang.mapper; import com.wang.pojo.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { //insert添加数据 @Insert("insert into user (id,name,pid,ppid,status,date) values (#{id},#{name},#{pid},#{ppid},#{status},#{date})") int addUser(User user); }
在resources下新建用于存储需要向linux发送的命令和进程名称(可自定义)beans.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="hello1" class="com.wang.pojo.Hello"> <property name="str"> <array> <!-- 向Linux发送命令--> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> <value>jps</value> <value>ps -ef|grep TimelyWharfJobMain |grep -v grep</value> </array> </property> </bean> <bean id="hello2" class="com.wang.pojo.Hello"> <property name="str"> <array> <!-- 进程名称 自定义--> <value>num001</value> <value>num002</value> <value>num003</value> <value>num004</value> <value>num005</value> <value>num006</value> <value>num007</value> <value>num008</value> <value>num009</value> <value>num010</value> </array> </property> </bean> </beans>
主程序MyTest:
import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import com.wang.mapper.UserMapper; import com.wang.pojo.Hello; import com.wang.pojo.User; import com.wang.utils.LinuxUtils; import com.wang.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; public class MyTest { //添加数据 @Test public void InsertData(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = (Hello) context.getBean("hello2"); String[] a = String.valueOf(hello).split(", "); String[] str = test().split(","); int i=0; for (String x:a){ //获取sqlSessionFactory对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Date Now = new Date( ); SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); if(str[i].equals("null")){ mapper.addUser(new User(0,x,str[i],str[i+1],"fail",ft.format(Now))); }else { mapper.addUser(new User(0,x,str[i],str[i+1],"success",ft.format(Now))); } //提交事务 sqlSession.commit(); sqlSession.close(); i=i+2; } } private String test() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = (Hello) context.getBean("hello1"); String[] a = String.valueOf(hello).split(", "); StringBuilder b = new StringBuilder(); for(String x : a){ String m = null; String n = null; try { Connection conn = LinuxUtils.getConnection(); Session ssh = conn.openSession(); ssh.execCommand(x); InputStream is = new StreamGobbler(ssh.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is)); while (true) { String line = brs.readLine(); if (line != null) { m = line.substring(9, 15); n = line.substring(16, 22); } break; } ssh.close(); conn.close(); } catch (IOException e) { e.printStackTrace(); } b.append(m).append(",").append(n).append(","); } return b.toString(); } }
测试运行:
与之前的原理相同,test()
用于向Linux发送命令并处理返回信息,将处理的信息交给InsertData()
存储到数据库中。优点在于,需要增加或减少命令时,不需要做大量重复和修改工作,只需要修改beans.xml
即可。程序在读取beans.xml
文件时,获取到的hello1、hello2为[a,a,a]
类型的字符串,需要处理掉两边的[]
,所以创建实体类Hello来进行处理。
UserMapper:
//查询最后10行数据 @Select("select name,pid,ppid,status,date from user order by id desc limit 10") List<User> getUserList01(); //查询最后10次失败记录 @Select("select name,pid,ppid,status,date from user where status='fail' order by id desc limit 10") List<User> getUserList02();
UserMapperImpl:
package com.wang.mapper; import com.wang.pojo.User; import com.wang.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import java.util.List; public class UserMapperImpl implements UserMapper{ @Override public int addUser(User user) { return 0; } @Override public List<User> getUserList01() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> list01 = mapper.getUserList01(); sqlSession.close(); return list01; } @Override public List<User> getUserList02() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> list02 = mapper.getUserList02(); sqlSession.close(); return list02; } }
新建TestServlet:
package com.wang.controller; import com.wang.mapper.UserMapperImpl; import com.wang.pojo.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller @RequestMapping("/hello") public class TestServlet{ @RequestMapping("/h1") public String hello01(Model model){ UserMapperImpl mapper = new UserMapperImpl(); List<User> list = mapper.getUserList01(); model.addAttribute("user1", list); return "hello01"; } @RequestMapping("/h2") public String hello02(Model model){ UserMapperImpl mapper = new UserMapperImpl(); List<User> list = mapper.getUserList02(); model.addAttribute("user2", list); return "hello02"; } }
添加web支持,目录如下:
固定配置web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 1注册DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 关联一个springmvc的配置文件:[servlet-name]-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- 启动级别-1--> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置所有的请求(不包括.jsp)--> <!-- 配置所有的请求(包括.jsp)--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
hello01.jsp:
<%@ page import="com.wang.pojo.User" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <%-- 5s自动刷新--%> <%-- <meta http-equiv="refresh" content="5">--%> <style> #layui-title{ text-align: center; } #layui-button{ text-align: center; } </style> </head> <body> <div id="layui-title"> <h1>Linux程序运行状态实时显示</h1> </div> <div id="layui-container"> <table id="layui-table" border="1px" width="700px" align="center" > <thead> <tr> <th>name</th><th>pid</th><th>ppid</th><th>status</th><th>date</th> </tr> </thead> <tbody> <% List<User> list =(List<User>) request.getAttribute("user1"); for(User i:list){ %> <tr> <td><%=i.getName() %></td> <td><%=i.getPid() %></td> <td><%=i.getPpid()%></td> <td><%=i.getStatus()%></td> <td><%=i.getDate()%></td> </tr> <% } %> </tbody> </table> </div> <div id="layui-button" > <Button onclick="location.reload()">刷新</Button> <Button onclick="window.location='/hello/h2'">记录</Button> <Button onclick="window.location='index.jsp'">退出</Button> </div> </body> </html>
hello02.jsp:
<%@ page import="com.wang.pojo.User" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <style> #layui-title{ text-align: center; } </style> </head> <body> <div id="layui-title"> <h2>运行失败记录</h2> </div> <div id="layui-container"> <table id="layui-table" border="1px" width="700px" align="center" > <thead> <tr> <th>name</th><th>pid</th><th>ppid</th><th>status</th><th>date</th> </tr> </thead> <tbody> <% List<User> list =(List<User>) request.getAttribute("user2"); for(User i:list){ %> <tr> <td><%=i.getName() %></td> <td><%=i.getPid() %></td> <td><%=i.getPpid()%></td> <td><%=i.getStatus()%></td> <td><%=i.getDate()%></td> </tr> <% } %> </tbody> </table> </div> </body> </html>
测试运行:
完成。