谷歌 http://www.googto.com/
1、表单
这里form中action不能带"/",不带/表示相对路径,带“/”表示绝对路径,必须写成/项目名称/url。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户登录</title> </head> <body> <div> <form action="loginServlet" method="post"> <table> <tr> <td>用户名:</td> <td><input id="userCode" name="userCode" type="text"></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password"></td> </tr> <tr> <td><input type="submit" value="登录"></td> </tr> </table> </form> </div> </body> </html>
2、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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>pro-web02</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>loginServlet</servlet-name> <servlet-class>cn.com.login.web.LoginController</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> </web-app>
这里的url-pattern中必须带/,不然会报错java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping
3、LoginController重写doPost和doGet代码
参考w3cSchool中servlet教程
http://www.runoob.com/servlet/servlet-form-data.html
public class LoginController extends HttpServlet{ private static final long serialVersionUID = 1L; public LoginController() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); System.out.println("用户名" + request.getParameter("userCode")); PrintWriter out = response.getWriter(); String title = "Using GET Method to Read Form Data"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>名字</b>:" + request.getParameter("userCode") + "\n" + "</ul>\n" + "</body></html>"); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
时间: 2024-11-13 05:29:16