JSP学习笔记(二):获取表单的数据
t1.htm
<html>
<head>
<title>test</title>
</head>
<body>
<form name="f1" id="f1" action="t1.jsp" method="post">
<table border="0">
<tr>
<td>内容:</td>
<td><input type="text" name="field1"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<head>
<title>test</title>
</head>
<body>
<form name="f1" id="f1" action="t1.jsp" method="post">
<table border="0">
<tr>
<td>内容:</td>
<td><input type="text" name="field1"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
t1.jsp
<%@ page language="java" contentType="text/html; charset=GB2312" pageEncoding="GB2312"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>test</title>
</head>
<body>
<%=request.getParameter("field1")%>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>test</title>
</head>
<body>
<%=request.getParameter("field1")%>
</body>
</html>
提交表单使用 post 和 get 方式,或者通过网址传递的参数,都可以通过request.getParameter(name)来获取表单的数据。
要想在一个普通类中使用request,可以把PageContext以参数的形式引进去,代码如下:
public void MyFun(PageContext pageContext) throws Exception
{
PrintWriter out = pageContext.getResponse().getWriter();
ServletRequest request = pageContext.getRequest();
out.print(request.getParameter("field1"));
}
{
PrintWriter out = pageContext.getResponse().getWriter();
ServletRequest request = pageContext.getRequest();
out.print(request.getParameter("field1"));
}
在页面中这样使用:
<%
Class1 class1 = new Class1();
class1.MyFun(pageContext);
%>
Class1 class1 = new Class1();
class1.MyFun(pageContext);
%>