一. 编写Servlet类
1. 继承HttpServlet类
2.重写doGet或者doPost方法(看html里是get请求还是post请求),用来接收客户端的请求。
package ServletStudy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//需要设置字体的字符集为UTF-8,来解决POST请求的中文乱码问题(英文可以正常显示,POST请求和GET请求一致)
req.setCharacterEncoding("UTF-8"); //要在获取请求参数之前调用才有效
String username = req.getParameter("username"); //getParameter():获取请求的参数
String password = req.getParameter("password");
String sex = req.getParameter("sex");
String[] hobby = req.getParameterValues("hobby"); //getParameterValues():获取请求的参数(多个值的时候使用)
String country = req.getParameter("country");
System.out.println("姓名:" + username + ",密码:" + password + ",性别:" + sex + ",爱好:" + Arrays.asList(hobby) + ",国家:" + country);
}
}
二. 在web.xml中配置访问Servlet程序的地址
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Servlet</servlet-name> <!-- 编写的Servlet程序的类名 -->
<servlet-class>ServletStudy.Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name> <!-- 编写的Servlet程序的类名 -->
<url-pattern>/servlet</url-pattern> <!-- 通常是类名的小写,该地址将指向编写的Servlet程序 -->
</servlet-mapping>
</web-app>
三. HTML页面
在表单里加上 action属性,指明要访问的Servlet程序的地址(该地址是web.xml里配的uer-pattern里的地址),并指明请求的类型是get请求还是post请求
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action = "http://localhost:8080/WebStudy_war_exploded/servlet" method = "post">
用户:<input type = "text" name = "username"/> <br/>
密码:<input type = "password" name = "password"/> <br/>
性别:<input type = "radio" name = "sex" value= "man"> 男
<input type = "radio" name = "sex" value= "woman"/> 女 <br/>
爱好:<input type = "checkbox" name = "hobby" value= "Java">Java
<input type = "checkbox" name = "hobby" value= "Python"/>Python
<input type = "checkbox" name = "hobby" value= "C++"/>C++ <br/>
国家:<select name = "country">
<option>请选择</option>
<option value= "China">中国</option>
<option value= "USA">美国</option>
<option value= "UK">英国</option>
</select> <br/>
<input type = "submit" value = "提交"/>
</form>
</body>
</html>
客户端的请求(get/post)→ web.xml → Servlet程序