web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name></display-name> <servlet> <servlet-name>register</servlet-name> <servlet-class>com.amark.servlet.RegisterServlet</servlet-class> </servlet>
//一个Servlet可以映射多个URL
<servlet-mapping> <servlet-name>register</servlet-name> <url-pattern>/servlet/RegisterServlet</url-pattern> </servlet-mapping></web-app><servlet-mapping> <servlet-name>register</servlet-name> <url-pattern>/register.htm</url-pattern> </servlet-mapping>
html提交表单
<body> <form name="f1" action="servlet/RegisterServlet" method="post"> <table border="1"> <tr> <td>Username:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password"></td> </tr> <tr> <td>Sex</td> <td align="center"> <input type="radio" name="sex" value="1">男 <input type="radio" name="sex" value="2">女 </td> </tr> <tr> <td>Job</td> <td align="center"> <select name="job"> <option value="ceo">CEO</option> <option value="techer">Techer</option> <option value="cooker">Cooker</option> <option value="student">Student</option> </select> </td> </tr> <tr> <td>hobby</td> <td align="center"> <input type="checkbox" name="hobby" value="1">篮球 <input type="checkbox" name="hobby" value="2">羽毛球 <input type="checkbox" name="hobby" value="3">乒乓球 </td> </tr> <tr> <td colspan="2"> <textarea rows="5" cols="30" name="memo"></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <input type="reset" value="Reset"> <input type="submit" value="Register"> </td> </tr> </table> </form> </body>
RegisterServlet类
public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); String password=request.getParameter("password"); String sex=request.getParameter("sex"); String job=request.getParameter("job"); String []hobby=request.getParameterValues("hobby"); String memo=request.getParameter("memo"); PrintWriter out=response.getWriter(); out.println("<html><head></head><body>"); out.println("username:"+username); out.println("</br>password:"+password); if(sex=="1") out.println("</br>sex:男"); else if(sex=="2") out.println("</br>sex:女"); out.println("</br>job:"+job); out.println("</br>hobby:"); for(String temp:hobby) out.println(temp); out.println("</br>memo:"+memo); out.println("</body></html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//post比get安全,一般用post获取表单
doGet(request, response);}}