📄 myform.jsp.htm
字号:
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>Implementing a Form in a JSP Page (Java Developers Almanac Example)
</TITLE>
<META CONTENT="Patrick Chan" NAME="AUTHOR">
<META CONTENT="Code Examples from The Java Developers Almanac 1.4" NAME="DESCRIPTION">
<META CONTENT="Addison-Wesley/Patrick Chan" NAME="OWNER">
<META CONTENT="3/20/02" NAME="revision">
<META CONTENT="no-cache" HTTP-EQUIV="Pragma">
<LINK href="/almanac.css" media="screen" type="text/css" rel="stylesheet">
</HEAD>
<BODY>
<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0">
<TR>
<TD></TD>
</TR>
</TABLE>
<br>
<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0">
<TR>
<TD></TD>
</TR>
<TR>
<TD rowspan="3"><A HREF="/?l=ex"><IMG BORDER="0" ALIGN="BOTTOM" HSPACE="10" SRC="/egs/almanac14a.jpg"></A></TD><TD VALIGN="top">
<h1>The Java Developers Almanac 1.4</h1>
<br>
Order this book from <a href="/cgi-bin/scripts/redirect.pl?l=ex&url=http://www.amazon.com/exec/obidos/ASIN/0201752808/xeo">Amazon</a>.
</TD>
</TR>
<TR>
<TD align="right" valign="bottom">
<FORM method="get" action="/cgi-bin/search/find.pl">
<INPUT size="25" name="words" type="text"><INPUT value="Search" type="submit">
</FORM>
</TD>
</TR>
</TABLE>
<HR color="#6666cc">
<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0">
<TR>
<TD valign="top"><script type="text/javascript">
<!--
google_ad_client = "pub-6001183370374757";
google_ad_width = 120;
google_ad_height = 600;
google_ad_format = "120x600_as";
google_ad_channel = "4777242811";
google_ad_type = "text_image";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "6666CC";
google_color_url = "6666CC";
google_color_text = "000000";
//--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script></TD><TD> </TD><TD valign="top">
<DIV ALIGN="LEFT">
<A HREF="/">Home</A>
>
<A HREF="../index.html">List of Packages</A>
>
<A HREF="../javax.servlet.jsp/pkg.html">javax.servlet.jsp</A><font color="#666666" class="xsmall-font">
[18 examples]
</font>
>
<B><A HREF="../javax.servlet.jsp/pkg.html#Java Server Pages">Java Server Pages</A></B><font color="#666666" class="xsmall-font">
[7 examples]
</font>
</DIV><P>
<h3>e1049. Implementing a Form in a JSP Page</h3>
There are many different strategies for implementing a form. Some
strategies involve a JSP page that shows the form and another to show
field validation errors. This example combines both pages in one
since in most cases, the page that shows validation errors looks like
the original page except for error messages next to the fields with
errors.
<P> When the page is first shown, no validation is done. When the
form is submitted, the new values are submitted to the same page
except that this time, the page will validate the values. If the
values are all valid, the form is processed and the browser is
redirected to a success page.
<P> The above behavior is implemented using a request parameter
called <code>process</code>. If set to <code>"true"</code>, the page will validate the
values and possibly process the form; otherwise, the page simply shows
a blank form. The request parameter is added when the user submits the
form.
<P> It is good practice to avoid placing the form validation code
in the JSP page. The example encapsulates the validation and form
processing code in a bean called <code>com.mycompany.MyForm</code>. When the
form is submitted, an instance of this bean is instantiated and loaded
with the submitted values for validation and processing.
<P> It is also considered good practice not to place error messages
in business objects such as in the <code>MyForm</code> class. The strategy
used in this example is to create and store a map of error messages in
the page instance and supply this map to every new <code>MyForm</code>
instance to use. In this way, all presentation related information is
contained in one JSP file. This makes it easier to maintain and
potentially localize the page. Another strategy is to use resource
bundles. However, unless all content on the page is moved in the
resource bundle, it may be simpler to keep the error messages in the
page to avoid having to manage two sources of content.
<P> See also <a href="../javax.servlet.jsp/myformts.jsp.html" class="eglink"><b>e1050</b> Implementing a Form That Prevents Duplicate Submissions in a JSP Page</a>.
<pre> <%-- Instantiate the form validation bean and supply the error message map --%>
<%@ page import="com.mycompany.*" %>
<jsp:useBean id="form" class="com.mycompany.MyForm" scope="request">
<jsp:setProperty name="form" property="errorMessages" value='<%= errorMap %>'/>
</jsp:useBean>
<%
// If process is true, attempt to validate and process the form
if ("true".equals(request.getParameter("process"))) {
%>
<jsp:setProperty name="form" property="*" />
<%
// Attempt to process the form
if (form.process()) {
// Go to success page
response.sendRedirect(<font color="#0066ff"><i>"formDone.jsp"</i></font>);
return;
}
}
%>
<html>
<head><title>A Simple Form</title></head>
<body>
<%-- When submitting the form, resubmit to this page --%>
<form action='<%= request.getRequestURI() %>' method="POST">
<%-- email --%>
<font color=red><%= form.getErrorMessage("email") %></font><br>
Email: <input type="TEXT" name="email" value='<%= form.getEmail() %>'>
<br>
<%-- zipcode --%>
<font color=red><%= form.getErrorMessage("zipcode") %></font><br>
Zipcode: <input type="TEXT" name="zipcode" value='<%= form.getZipcode() %>'>
<br>
<input type="SUBMIT" value="OK">
<input type="HIDDEN" name="process" value="true">
</form>
</body>
</html>
<%!
// Define error messages
java.util.Map errorMap = new java.util.HashMap();
public void jspInit() {
errorMap.put(MyForm.ERR_EMAIL_ENTER, "Please enter an email address");
errorMap.put(MyForm.ERR_EMAIL_INVALID, "The email address is not valid");
errorMap.put(MyForm.ERR_ZIPCODE_ENTER, "Please enter a zipcode");
errorMap.put(MyForm.ERR_ZIPCODE_INVALID, "The zipcode must be 5 digits");
errorMap.put(MyForm.ERR_ZIPCODE_NUM_ONLY, "The zipcode must contain only digits");
}
%>
</pre>
Here is the code for the <code>com.mycompany.MyForm</code> bean:
<pre> package com.mycompany;
import java.util.*;
public class MyForm {
/* The properties */
String email = "";
String zipcode = "";
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email.trim();
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode.trim();
}
/* Errors */
public static final Integer ERR_EMAIL_ENTER = new Integer(1);
public static final Integer ERR_EMAIL_INVALID = new Integer(2);
public static final Integer ERR_ZIPCODE_ENTER = new Integer(3);
public static final Integer ERR_ZIPCODE_INVALID = new Integer(4);
public static final Integer ERR_ZIPCODE_NUM_ONLY = new Integer(5);
// Holds error messages for the properties
Map errorCodes = new HashMap();
// Maps error codes to textual messages.
// This map must be supplied by the object that instantiated this bean.
Map msgMap;
public void setErrorMessages(Map msgMap) {
this.msgMap = msgMap;
}
public String getErrorMessage(String propName) {
Integer code = (Integer)(errorCodes.get(propName));
if (code == null) {
return "";
} else if (msgMap != null) {
String msg = (String)msgMap.get(code);
if (msg != null) {
return msg;
}
}
return "Error";
}
/* Form validation and processing */
public boolean isValid() {
// Clear all errors
errorCodes.clear();
// Validate email
if (email.length() == 0) {
errorCodes.put("email", ERR_EMAIL_ENTER);
} else if (!email.matches(".+@.+\\..+")) {
errorCodes.put("email", ERR_EMAIL_INVALID);
}
// Validate zipcode
if (zipcode.length() == 0) {
errorCodes.put("zipcode", ERR_ZIPCODE_ENTER);
} else if (zipcode.length() != 5) {
errorCodes.put("zipcode", ERR_ZIPCODE_INVALID);
} else {
try {
int i = Integer.parseInt(zipcode);
} catch (NumberFormatException e) {
errorCodes.put("zipcode", ERR_ZIPCODE_NUM_ONLY);
}
}
// If no errors, form is valid
return errorCodes.size() == 0;
}
public boolean process() {
if (!isValid()) {
return false;
}
// Process form...
// Clear the form
email = "";
zipcode = "";
errorCodes.clear();
return true;
}
}
</pre>
<P><table width="600" CELLSPACING="0" CELLPADDING="2" BORDER="0">
<tr>
<td bgcolor="#6666cc" align="center"><font color="#ffffff">
<b>Related Examples</b></font></td>
</tr>
</table>
e1046. <a class="eglink" href="basic.html?l=rel">
The Quintessential JSP Page
</a>
<br>
e1047. <a class="eglink" href="code.html?l=rel">
Running Java Code in a JSP Page
</a>
<br>
e1048. <a class="eglink" href="attr.html?l=rel">
Saving Data in a JSP Page
</a>
<br>
e1050. <a class="eglink" href="myformts.jsp.html?l=rel">
Implementing a Form That Prevents Duplicate Submissions in a JSP Page
</a>
<br>
e1051. <a class="eglink" href="precompile.html?l=rel">
Precompiling a JSP Page
</a>
<br>
e1052. <a class="eglink" href="nosession.html?l=rel">
Preventing the Creation of a Session in a JSP Page
</a>
<br>
<table width="600" CELLSPACING="0" CELLPADDING="2" BORDER="0">
<tr>
<td align="left">
<br>
See also:
<a class="eglink" href="/egs/javax.servlet.jsp/pkg.html?l=rel#Java%20Server%20Pages%20Headers">
Java Server Pages Headers
</a>
<a class="eglink" href="/egs/javax.servlet.jsp/pkg.html?l=rel#Java%20Server%20Pages%20Input">
Java Server Pages Input
</a>
<a class="eglink" href="/egs/javax.servlet.jsp/pkg.html?l=rel#Java%20Server%20Pages%20Output">
Java Server Pages Output
</a>
</td>
</tr>
</table>
<br>
<br>
<FONT class="xsmall-font">
© 2002 Addison-Wesley.
</FONT></TD><TD> </TD><TD valign="top"><A href="http://compositesw.com/devzone?ref=javaalmanac"><IMG alt="Click Here" height="600" width="120" border="0" src="/csw_oad_120x600_final.gif"></A></TD>
</TR>
</TABLE>
</BODY>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META CONTENT="NO-CACHE" HTTP-EQUIV="PRAGMA">
</HEAD>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -