获取表单数据
- login.html 中的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="GBK">
<title>用户登录</title>
</head>
<body>
<form action ="http://127.0.0.1:8080/unit8/Servlet4" method="post">
用户名:<input type = "text" name="uname">
密码:<input type = "password" name="upwd">
<input type="submit">
</form>
</body>
</html>
- 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" 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>unit8</display-name>
<welcome-file-list>
<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>Servlet4</servlet-name>
<servlet-class>com.unit8.servlet.Servlet4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet4</servlet-name>
<url-pattern>/Servlet4</url-pattern>
</servlet-mapping>
</web-app>
- Servlet 中的代码
package com.unit8.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet4 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
String uname = request.getParameter("uname");
String upwd = request.getParameter("upwd");
PrintWriter pw = response.getWriter();
if(uname!=null && upwd!=null){
if("zhangsan".equals(uname)&&"123".equals(upwd)){
pw.print("恭喜你!"+uname+"登陆成功!");
} else{
pw.print("您输入的的用户名或密码错误!");
}
} else {
pw.print("您输入的用户名或密码为空!");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- login.html 中 method = “get” 时
<form action ="http://127.0.0.1:8080/unit8/Servlet4" method="get">
- 运行结果
- 改成 post 后的结果(前六步代码中的 method = post)