xml文件
<?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>
<servlet-name>ExpServlet</servlet-name>
<servlet-class>edu.xalead.ExpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExpServlet</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
</web-app>
servlet文件
package edu.xalead;
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;
import java.util.Map;
public class ExpServlet extends HttpServlet {
/**
* service方法
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
// public void service(HttpServletRequest request,HttpServletResponse response){
// if (request.getMethod().equals("GET"));
// doGet(request,response);
// else if (request.getMethod().equals("POST"));
// doPost(request,response);
// }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST方法处理开始");
}
/**
* 这里要注意的是,如果是取数据。
* 就将请求方法写在doGet方法里,
* 如果是表单,就将表单写到doPost方法里。
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//取出请求方法
String method = req.getMethod();
//取出请求路径
String url = req.getRequestURL().toString();
//取出协议及版本
String protocol = req.getProtocol();
//取出请求头中的内容
//那些键值对统一叫头
String host_head = req.getHeader("host");
String accept_head = req.getHeader("accept");
String userAgent_head = req.getHeader("user-agent");
System.out.println(method + " " + url + protocol);
System.out.println("host:" + host_head);
System.out.println("user-agent:" + userAgent_head);
System.out.println("accept:" + accept_head);
//取查询字符串中的数据
String name = req.getParameter("name");
String sex = req.getParameter("sex");
System.out.println("name:" + name + ",sex:" + sex);
//取查询字符串中的集合数据
String[] names = req.getParameterValues("name");
/*将数组变成一个列表输出*/
System.out.println(Arrays.asList(names));
//查询字符串在request当中本质是存储为Map集合,用以下方法可取出
Map<String, String[]> params = req.getParameterMap();
String[] namePamrams = params.get("name");//取到name属性值的集合
System.out.println(Arrays.asList(namePamrams));//转换成列表输出
String[] sexParams = params.get("sex");
System.out.println(Arrays.asList(sexParams));//转换成列表输出
resp.getWriter().println("Hello World !");
} catch (Exception e) {
System.out.println(e);
}
}
}