在sm框架下:jsp从页面输入一个IP地址和一个数字,通过get方式向/home下的shell脚本传递这两个参数,写出具体完整代码包括代码所在的文件名
时间: 2024-06-12 18:04:22 浏览: 147
1. 在jsp页面中,需要有一个表单来输入IP地址和数字:
```html
<form action="/myapp/ipAction" method="get">
<label for="ip">IP地址:</label>
<input type="text" id="ip" name="ip"><br>
<label for="number">数字:</label>
<input type="number" id="number" name="number"><br>
<input type="submit" value="提交">
</form>
```
2. 在后端代码中,需要处理这个请求并调用shell脚本,我们可以新建一个IPAction类来处理:
```java
package com.example.myapp.action;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IPAction extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ip = request.getParameter("ip");
int number = Integer.parseInt(request.getParameter("number"));
String[] cmd = { "/bin/sh", "-c", "/home/your_script.sh " + ip + " " + number };
Process process = Runtime.getRuntime().exec(cmd);
String line;
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
response.getWriter().write("执行成功,输出为:\n" + output.toString());
} else {
response.getWriter().write("执行失败,错误码为:" + exitVal);
}
}
}
```
3. 在web.xml中配置这个servlet:
```xml
<servlet>
<servlet-name>IPAction</servlet-name>
<servlet-class>com.example.myapp.action.IPAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IPAction</servlet-name>
<url-pattern>/ipAction</url-pattern>
</servlet-mapping>
```
4. 创建一个名为your_script.sh的shell脚本,放在/home下,内容如下:
```bash
#!/bin/bash
ip=$1
number=$2
echo "您输入的IP地址为:$ip"
echo "您输入的数字为:$number"
```
5. 最后,需要将JSTL和Servlet API添加到项目依赖中,这里使用Maven作为依赖管理工具,在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
```
这样,在访问jsp页面并输入IP地址和数字后,点击提交按钮,就可以向/home下的shell脚本传递这两个参数,并获取执行结果。
阅读全文