日期:2014-05-16  浏览次数:20458 次

jsp+servlet 表单验证

<%@ page Xlanguage="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'test.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>


<body>
<p align="center">表单提交</p>
<form action="servlet/testresult" method="post">
<table align="center">
<tr><td>name:</td><td><input type="text" name="username"/></td></tr>
<tr><td>sex:</td><td>男<input type="radio" name="sex" value="男"/>&nbsp;&nbsp;女<input type="radio" name="sex" value="女"/></td></tr>
<tr><td>address:</td><td><input type="text" name="address"/></td></tr>
<tr><td>likes:</td><td><input type="checkbox" name="likes" value="sing"/>sing<input type="checkbox" name="likes" value="dance"/>dance<input type="checkbox" name="likes" value="game"/>game</td></tr>
<tr><td>&nbsp;</td><td><input type="submit" value="submit"/><input type="reset" value="reset"/></td></tr>
</table>
</from>
</body>
</html>
package com.csdn.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class testresult extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");

String name = request.getParameter("username");
String sex = request.getParameter("sex");
String address = request.getParameter("address");
String[] likes = request.getParameterValues("likes");
String likes1="";
if(likes!=null){
for(String like:likes){
likes1 +=like+" ";
}
}
String url="/test.jsp";
if(name!=null && !name.equals("")){
request.setAttribute("username", name);
request.setAttribute("sex", sex);
request.setAttribute("address", address);
request.setAttribute("likes",likes1);
url="/testresult.jsp";
}
request.getRequestDispatcher(url).forward(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}
<%@ page Xlanguage="java" import="java.util.*" pageEncoding="utf-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
&l