6 常用request、response方法
1. 什么是request、response
2. request
2.1 代码
- 获取url信息
- 获取参数信息
- 获取请求头部信息
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
System.out.println("RegisterServlet加载完成");
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
System.out.println("=====URL信息======");
System.out.println("浏览器发出请求时的完整URL,包括协议 主机名 端口(如果有): " + request.getRequestURL());
System.out.println("浏览器发出请求的资源名部分,去掉了协议和主机名: " + request.getRequestURI());
System.out.println("请求行中的参数部分: " + request.getQueryString());
System.out.println("浏览器所处于的客户机的IP地址: " + request.getRemoteAddr());
System.out.println("浏览器所处于的客户机的主机名: " + request.getRemoteHost());
System.out.println("浏览器所处于的客户机使用的网络端口: " + request.getRemotePort());
System.out.println("服务器的IP地址: " + request.getLocalAddr());
System.out.println("服务器的主机名: " + request.getLocalName());
System.out.println("得到客户机请求方式: " + request.getMethod());
System.out.println("=====参数信息======");
//获取简单的参数信息
System.out.println("获取单值参数name:" + request.getParameter("name"));
//获取多值参数信息
String[] hobits = request.getParameterValues("hobits");
System.out.println("获取具有多值的参数hobits: " + Arrays.asList(hobits));
//获取参数键值对映射
System.out.println("通过 getParameterMap 遍历所有的参数: ");
Map<String, String[]> parameters = request.getParameterMap();
Set<String> paramNames = parameters.keySet();
for (String param : paramNames) {
String[] value = parameters.get(param);
System.out.println(param + ":" + Arrays.asList(value));
}
System.out.println("=====请求头信息======");
Enumeration<String> headerNames= request.getHeaderNames();
while(headerNames.hasMoreElements()){
String header = headerNames.nextElement();
String value = request.getHeader(header);
System.out.printf("%s\t%s%n",header,value);
}
String html = "<div style='color:red'>成功</div>";
response.setContentType("text/html; charset=UTF-8");
PrintWriter pw = response.getWriter();
}
}
2.2 效果
3 response
https://how2j.cn/k/servlet/servlet-response/556.html#step1610