HTML表单用于从用户处获取数据, 当表单提交后, 在服务端获取这些数据进行进一步处理,比如业务逻辑验证、将数据保存到数据库中等。
创建一个HTML表单用于获取用户的信息:
index.jsp
<%
@page
contentType=
"text/html"
pageEncoding=
"UTF-8"
%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Form Demo</title>
<style type=
"text/css"
>
label{ margin-right:20px;}
input{ margin-top:5px;}
</style>
</head>
<body>
<form action=
"handleUserInfo.jsp"
method=
"post"
<fieldset>
<legend>用户信息</legend>
<label
for
=
"name"
>名字</label>
<input type=
"text"
name=
/> <br/>
"email"
>邮箱</label>
"submit"
value=
</fieldset>
</form>
</body>
</html>
在form标签中,可以看到使用post方法将表单数据发送到服务器。我们需要创建一个负责获取表单数据并进行处理的JSP文件handleUserInfo.jsp。
handleUserInfo.jsp
<title>JSP 表单演示</title>
String name = request.getParameter(
);
String email = request.getParameter(
<p>Hi <%=name%>!
你提交的邮箱地址是: <%=email%>.</p>
在处理脚本Servelet的中,我们使用了request对象的getParameter()方法来获取表单数据, 它返回名称对应的表单字段的值。getParameter()方法的返回值总是字符串类型的,因此,如果表单字段的值是数字,则必须对getParameter()返回值进行转换。如果字段不存在,则返回null。
getParameter()
null
之前的HTML表单的代码和处理表单的JSP代码分别位于不同的文件中。现在让我们看一下如何在单个JSP页面中处理HTML表单。
首先,我们需要在HTML表单中添加一个额外的隐藏字段。当用户提交表单数据时,我们通过这个隐藏字段的值来判断是否提交了表单。
<title>JSP 处理表单</title>
String val = request.getParameter(
"isSubmitted"
int
isSubmitted =
0
;
if
(val !=
) {
isSubmitted = Integer.parseInt(val);
(isSubmitted ==
1
out.println(
"<p>Hi "
+ name +
"!你提交的邮箱地址是:"
+ email +
".</p>"
}
) {%>
"index.jsp"
"hidden"
"1"
/>
<%}%>
注意,在action中的文件名必须和文件一致,或者留空。当不是提交表单时,request.getParameter("isSubmitted")返回为空, 转换后isSubmitted值为0。 所以将显示表单。当提交表单后,isSubmitted值为1。 JSP页面将继续获取name 和email的值并进行显示。
request.getParameter("isSubmitted")
isSubmitted
在这里,为了演示,我们是把用户提交的数据未经过处理直接就进行显示了。但是为了系统安全,处理表单时要记住的最重要的一点是:永远不要信任从客户端提交的数据。
如果你遇到这样的问题:
descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.UnsupportedClassVersionError: Class org.mypackage.hello.NameHandler has unsupported major or minor version numbers, which are greater than those found in the Java Runtime Environment version 1.8.0_221
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 5.0 logs.
在Libraries中选择Properties:
Properties
原文链接:https://codingdict.com/