jsp实现数据提交以及jsp数据保存到本地
第一个页面"index.jsp"是普通的表单页面为了简单起见,表单使用表格元素进行定位,然后提交到第二个页面,底部有效果图
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<html>
<body>
<h2>清明节离校去向登记</h2>
<br>
<form action="index_request.jsp" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="xinming" required="required" /></td>
</tr>
<tr>
<td>学号:</td>
<td><input type="text" name="xuehao" required="required" /></td>
</tr>
<tr>
<td>去向:</td>
<td><input type="text" name="quxiang" required="required" /></td>
</tr>
<tr>
<td>离校时间:</td>
<td><input type="text" name="lixiao" placeholder="例:1999-1-1" /></td>
</tr>
<tr>
<td>返校时间:</td>
<td><input type="text" name="fanxiao" placeholder="例:1999-1-1" /></td>
</tr>
<tr>
<td>本人电话:</td>
<td><input type="tel" name="benren" required="required" /></td>
</tr>
<tr>
<td>父母电话:</td>
<td><input type="tel" name="fumu" required="required" /></td>
</tr>
</table>
<input type="submit" name="tijiao" value="提交" /> <input type="reset"
name="quxiao" value="取消" />
</form>
</body>
</html>
第二个页面"index_request.jsp"获取表单数据并把数据保存到"D/test1.txt".详细说明已经写在下面代码中.
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<html>
<body>
<h3>提交成功:</h3>
<BR>
<%
//计数器
Integer count = (Integer) application.getAttribute("counter");
if (count == null) {
count = 0;
}
count++;
application.setAttribute("counter", count);
request.setCharacterEncoding("utf-8");//设置接收的字符编码
//接收第一个页面的表单数据
String xue = request.getParameter("xuehao");
String qu = request.getParameter("quxiang");
String li = request.getParameter("lixiao");
String fan = request.getParameter("fanxiao");
String ben = request.getParameter("benren");
String fu = request.getParameter("fumu");
String xin = request.getParameter("xinming");
//创建test1.txt文件
File file = new File("D:/test1.txt");
//数据格式化,方便把文本文件复制到excel做成表格
//request.getRemoteAddr()获取客户端ip地址
String a = xin + "\t" + xue + "\t" + qu + "\t" + li + "\t" + fan + "\t" + ben + "\t" + fu +"\t"+count+"\t"+request.getRemoteAddr()+ "\r\n";
String b = xin + "\t" + xue + "\t" + qu + "\t" + li + "\t" + fan + "\t" + ben + "\t" + fu + "\r\n";//显示在页面中
try {
//把表单数据写到本地文件,注意要使用数据追加的方式
FileOutputStream fileout = new FileOutputStream(file, true);
byte buy[] = a.getBytes();
fileout.write(buy);
fileout.close();
} catch (IOException e) {
e.printStackTrace();
}
out.print(b);
%>
<h2>数据已提交,可以关闭浏览器</h2>
<form action="index.jsp">
<input type="submit" name="xiugai" value="修改数据" />
</form>
<br>
</body>
</html>
结果如图:
把文本数据全部复制到excel可以直接做成表格