6 常用request、response方法

1. 什么是request、response

2. request

2.1 代码

  1. 获取url信息
  2. 获取参数信息
  3. 获取请求头部信息
  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.util.Arrays;
  4. import java.util.Enumeration;
  5. import java.util.Map;
  6. import java.util.Set;
  7. import javax.servlet.ServletConfig;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. public class RegisterServlet extends HttpServlet {
  13. @Override
  14. public void init(ServletConfig config) throws ServletException {
  15. // TODO Auto-generated method stub
  16. super.init(config);
  17. System.out.println("RegisterServlet加载完成");
  18. }
  19. protected void service(HttpServletRequest request, HttpServletResponse response)
  20. throws ServletException, IOException{
  21. System.out.println("=====URL信息======");
  22. System.out.println("浏览器发出请求时的完整URL,包括协议 主机名 端口(如果有): " + request.getRequestURL());
  23. System.out.println("浏览器发出请求的资源名部分,去掉了协议和主机名: " + request.getRequestURI());
  24. System.out.println("请求行中的参数部分: " + request.getQueryString());
  25. System.out.println("浏览器所处于的客户机的IP地址: " + request.getRemoteAddr());
  26. System.out.println("浏览器所处于的客户机的主机名: " + request.getRemoteHost());
  27. System.out.println("浏览器所处于的客户机使用的网络端口: " + request.getRemotePort());
  28. System.out.println("服务器的IP地址: " + request.getLocalAddr());
  29. System.out.println("服务器的主机名: " + request.getLocalName());
  30. System.out.println("得到客户机请求方式: " + request.getMethod());
  31. System.out.println("=====参数信息======");
  32. //获取简单的参数信息
  33. System.out.println("获取单值参数name:" + request.getParameter("name"));
  34. //获取多值参数信息
  35. String[] hobits = request.getParameterValues("hobits");
  36. System.out.println("获取具有多值的参数hobits: " + Arrays.asList(hobits));
  37. //获取参数键值对映射
  38. System.out.println("通过 getParameterMap 遍历所有的参数: ");
  39. Map<String, String[]> parameters = request.getParameterMap();
  40. Set<String> paramNames = parameters.keySet();
  41. for (String param : paramNames) {
  42. String[] value = parameters.get(param);
  43. System.out.println(param + ":" + Arrays.asList(value));
  44. }
  45. System.out.println("=====请求头信息======");
  46. Enumeration<String> headerNames= request.getHeaderNames();
  47. while(headerNames.hasMoreElements()){
  48. String header = headerNames.nextElement();
  49. String value = request.getHeader(header);
  50. System.out.printf("%s\t%s%n",header,value);
  51. }
  52. String html = "<div style='color:red'>成功</div>";
  53. response.setContentType("text/html; charset=UTF-8");
  54. PrintWriter pw = response.getWriter();
  55. }
  56. }

2.2 效果

图片.png

3 response

https://how2j.cn/k/servlet/servlet-response/556.html#step1610