java基础-11 Web

目录

 

Eclipse中集成Tomcat

网站访问的全过程

Web

Idea配置tomcat:https://www.jianshu.com/p/3c75f7fd2f90

什么是WEB

什么是JavaWEB

软件架构

WEB服务器

常见哪些web服务器

WEB开发中的资源

Tomcat的目录结构

动态WEB资源的目录结构

Tomcat项目发布的三种方式

虚拟主机

HTTP协议

Servlet

Servlet的实现子类

使用Eclipse开发Servlet

Servlet的生命周期

代码演示Servlet的生命周期

Servlet的启动时加载

Servlet的访问路径的配置

ServletConfig对象

ServletContext

Response

Response对象响应的中文乱码处理

Request

获得请求头的方法


  • Eclipse中集成Tomcat

1.选择window

2.弹出界面选择Server

3.添加服务

4.选择Tomcat服务

5.配置服务

6.设置服务

7.创建一个web项目

  • 网站访问的全过程

Web

Idea配置tomcat:https://www.jianshu.com/p/3c75f7fd2f90

  • 什么是WEB

web(World Wide Web)即全球广域网,也称为万维网,它是一种基于超文本和HTTP的、全球性的、动态交互的、跨平台的分布式图形信息系统。是建立在Internet上的一种网络服务,为浏览者在Internet上查找和浏览信息提供了图形化的、易于访问的直观界面,其中的文档及超级链接将Internet上的信息节点组织成一个互为关联的网状结构。

  • 什么是JavaWEB

使用Java语言进行WEB的开发

  • 软件架构

  1. CS结构的软件
    1. CS:Client/Server 客户端和服务器,这种软件往往需要安装。比如QQ、迅雷、播放器。
    2. 优缺点:
      1. 优点:
        1. 可以减轻服务器端压力,将部分代码写到客户端。
        2. 界面很美观。
      2. 缺点:
        1. 一旦服务器更新了,客户端也需要更新。
        2. 分布式开发比较弱。
  2. BS结构的软件
    1. BS:Browser/Server 浏览器和服务器,这种软件不需要安装,只需要通过浏览器就可以访问。
    2. 优缺点:
      1. 优点:
        1. 服务器一旦更新,不需要更新客户端,因为客户端就是浏览器
        2. 比较强的分布式能力
      2. 缺点:
        1. 服务器端压力会比较大。
        2. 界面效果不如CS结构软件。
  • WEB服务器

  1. 服务器:
    1. 硬件:其实就是一台电脑(这台电脑配置要求很高)。
    2. 软件:需要在这台电脑上安装web服务器的软件。
  • 常见哪些web服务器

  1. Tomcat              :Apache组织提供的一个开源的免费的web服务器。满足EE的Serlet和JSP的规范。
  2. WebSphere      :IBM公司开发的一个收费的大型web服务器。满足了EE开发的所有规范。
  3. WebLogic         :BEA公司开发的一个收费的大型web服务器。满足了EE开发的所有规范。
  4. IIS                     :应用在.NET平台上。
  5. Apache             :应用在PHP平台上。
  • WEB开发中的资源

  1. 静态web资源
    1. HTML
    2. CSS
    3. JS
  2. 动态web资源
    1. ServletJSP
    2. PHP
    3. ASP
  • Tomcat的目录结构

  1. bin             :二进制文件(命令文件:开启和关闭)
  2. conf           :配置文件
  3. lib              :tomcat所需要的jar包
  4. logs           :tomcat服务器日志文件
  5. temp         :tomcat运行产生临时文件
  6. webapps  :需要发布的项目需要放在webapps
  7. work         :JSP翻译(编译)成Servlet产生的代码
  • 动态WEB资源的目录结构

website

         |------静态页面(HTML、CSS、JS、图片)

         |------JSP页面

         |------WEB-INF

                            |-----web.xml   (必须的)

                            |-----classes       (可选的)

                            |-----lib               (可选的)

  • Tomcat项目发布的三种方式

  1. 一种:直接将项目复制到tomcat/webapps下
  2. 二种:在tomcat/conf/server.xml配置tomcat的虚拟路径
  3. 三种:在tomcat/conf/Catalina/localhost/下配置tomcat的虚拟路径

Tomcat的项目发布方式一

  • 一种:直接将项目复制到tomcat/webapps下

访问地址:http://localhost:8080/项目名称/index.html               index.html可省略

 

  • 二种:在tomcat/conf/server.xml配置tomcat的虚拟路径( 不推荐使用第二种方式,原因:需要修改tpmcat的核心配置文件,可能导致tomcat启动都报错)

这种方式是需要配置Tomcat的虚拟路径。

虚拟路径:配置一个名称与一个真实的路径进行绑定,然后访问这个名称从而找到真实路径。
如何配置虚拟路径
在tomcat/conf/server.xml中进行配置(可以在tomcat的文档中找到)。
    第一步:创建一个项目
    第二步:配置虚拟路径

...
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
			   
		<Context path="/toroidals" docBase="F:\桌面\资料\web 项目\登录\cpts_1036_bnv"></Context>
		
      </Host>
    </Engine>
  </Service>
</Server>
  • 三种:在tomcat/conf/Catalina/localhost/下配置tomcat的虚拟路径

第三种方式也需要配置虚拟路径,第二种需要修改server.xml。server.xml是tomcat的核心配置文件,一旦你修改错了,那么tomcat服务器就会出现问题。推荐使用第三种配置方式。

  1. 第一步:创建web项目
  2. 第二步:创建一个xml(在tomcat/conf/Catalina/localhost)
  3. 第三步:配置虚拟路径:文件的名称就是虚拟路径(itcast),只需要访问itcast就可以访问C:\ccc这个路径

<?xml version='1.0' encoding='utf-8'?>
<Context path="/toroidals" docBase="F:\桌面\资料\web 项目\登录\cpts_1036_bnv"></Context>
  • 虚拟主机

虚拟主机:在电脑上设置一个目录,使用一个名称与该目录进行绑定。这个路径称为是虚拟主机。主机是可以发布web项目的。

  • 虚拟主机的配置

修改百度主页为自定义主页

修改本地的hosts文件

C:\Windows\System32\drivers\etc\hosts

192.168.115.1 www.baidu.com

注意: 

  1. HTTP服务器,默认的端口号为80/tcp
  2. HTTPS(securely transferring web pages)服务器,默认的端口号为443/tcp 443/udp
  3. TOMCAT,默认的端口号为8080; 

修改 server.xml

修改端口号

将路径中的website去掉

配置默认的首页

web.xml

  • HTTP协议

什么是HTTP协议: 超文本传输协议

http是一个简单的请求-响应协议,它通常运行在TCP之上。它指定了客户端可能发送给服务器什么样的消息以及得到什么样的响应。请求和响应消息的头以ASCII码形式给出;而消息内容则具有一个类似MIME的格式。这个简单模型是早期Web成功的有功之臣,因为它使得开发和部署是那么的直截了当。

什么是https: 超文本传输安全协议

HTTPS (全称:Hyper Text Transfer Protocol over SecureSocket Layer),是以安全为目标的 HTTP 通道,在HTTP的基础上通过传输加密和身份认证保证了传输过程的安全性  。HTTPS 在HTTP 的基础下加入SSL 层,HTTPS 的安全基础是 SSL,因此加密的详细内容就需要 SSL。 HTTPS 存在不同于 HTTP 的默认端口及一个加密/身份验证层(在 HTTP与 TCP 之间)。这个系统提供了身份验证与加密通讯方法。现在它被广泛用于万维网上安全敏感的通讯,例如交易支付等方面

HTTP的特性

  1. 基于请求和响应模型
    1. 必须要先有请求,后有响应。
    2. 请求和响应必须成对出现。
  2. 简单快捷
    1. 因为发送请求的时候只需要发送请求方式和请求路径即可

HTTP的版本

  1. HTTP1.0   :
  2. HTTP1.1  

分析HTTP协议

请求部分详解

请求部分可以分成三块

  1. 请求行
    1. 请求方式
      1. 请求方式有很多种,常用就两种GETPOST
      2. GETPOST的区别?
        1. GET:请求的参数会显示到地址栏。通常是有大小的限制。没有请求体
        2. POST:请求的参数不会显示到地址栏(在请求体中)。POST没有大小的限制。有请求体(请求参数)。只有表单设置method=”post”才是post请求。
    2. 请求路径
    3. 协议版本
  2. 请求头
    1. 请求头的格式一般都是一个key对应一个value的,也有一个key对应多个value的情况。
    2. 记住一些请求头:
      1. Referer              :代表网页的来源。(防盗链)。
      2. User-Agent       :获得客户端浏览器类型。
  3. 请求体
    1. 只有POST请求方式才有请求体,而且请求体是POST方式请求参数。

响应部分详解

响应部分分成三块内容

  1. 响应行
    1. 协议版本
    2. 状态码
      1. 200  :代表响应成功
      2. 302  :需要进行重定向操作
      3. 304  :需要查找本地缓存
      4. 404  :请求资源不存在
      5. 500  :服务器内部错误
    3. 状态码描述
  2. 响应头
    1. 通常一个key对应一个value,也有一个key对应多个value。
    2. 记住响应头:
      1. Location   :重定向的路径。
      2. Refresh     :定时刷新。
      3. Content-Disposition:文件下载的时候使用。
  3. 响应体
    1. 就是显示到浏览器上页面的代码。
  • Servlet

什么是Servlet: Servlet其实就一个运行在web服务器上的小的Java程序,用于处理从web客户端发送的请求,并且对请求作出响应。

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容。

狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。Servlet运行于支持Java的应用服务器中。从原理上讲,Servlet可以响应任何类型的请求,但绝大多数情况下Servlet只用来扩展基于HTTP协议的Web服务器。

最早支持Servlet标准的是JavaSoft的Java Web Server,此后,一些其它的基于Java的Web服务器开始支持标准的Servlet。

  • 使用Servlet

    编写一个Java类实现Servlet的接口
    配置Servlet

实现servlet接口,重写service方法

package com.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletTest implements Servlet{

	/*
	 * 处理用户请求,对请求做出响应 
	 */
	@Override
	public void service(ServletRequest request, ServletResponse respose) throws ServletException, IOException {
		// 向页面输出一个"海纳百川, 有容乃大, 壁立千仞, 无欲则刚"
		respose.getWriter().println("send masegge 海纳百川, 有容乃大, 壁立千仞, 无欲则刚");
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}

在web.xml中配置这个类的映射

  <!-- 配置Servlet -->
   <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.servlet.ServletTest</servlet-class>
  </servlet>
  <!-- 配置Servlet映射 -->
   <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

启动服务直接访问: http://localhost:8080/JavaWeb/hello

此处中文未能正常显示

  • Servlet的执行流程
  1. 根据请求路径http://localhost:8080/JavaWeb/hello到web.xml <servlet-mapping> 查找 url-pattern 匹配项
  2. 找到url-pattern对应的servlet-name
  3. 在 <servlet> 中找到 servlet-name 对应的类
  4. 执行类中的 service方法
  • Servlet的实现子类

Servlet接口                      

         |

GenericServlet类             通用的Servlet,是一个与协议无关的Servlet

         |

HttpServlet类                    Http专用的Servlet

实现关系的概述

SUN设计之初,认为以后的互联网不仅仅只使用http协议,可以通过GenericServlet实现。HttpServlet是一个与协议相关的Servlet是专门用来处理HTTP协议的请求。通常编写一个Servlet一般都会让这个Servlet继承HttpServlet重写service方法。

service方法内部根据请求方式不同执行不同的doXXX的方法(get请求执行doGet方法,如果是post请求就会执行doPost方法)。

所以往往继承了HttpServlet之后不需要重写service方法,只需要重写doGetdoPost方法即可。往往请求要处理的内容的代码都是一致的,所以需要让doGetdoPost相互调用可以简化编程。

配置 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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JavaWeb</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>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.servlet.ServletTest</servlet-class>
  </servlet>
  
  <!-- 配置Servlet映射 -->
   <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
    <!-- 配置Servlet -->
   <servlet>
    <servlet-name>HttpServlet</servlet-name>
    <servlet-class>com.servlet.HttpServletTest</servlet-class>
  </servlet>
  <!-- 配置Servlet映射 -->
   <servlet-mapping>
    <servlet-name>HttpServlet</servlet-name>
    <url-pattern>/httpServlet</url-pattern>
  </servlet-mapping>
  
</web-app>

继承 HttpServlet 类

package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpServletTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是GET请求就会执行doGet中的代码
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是Post请求就会执行doPost中的代码
		resp.getWriter().println("httpServlet... 嚣张");
	}
}
  • 使用Eclipse开发Servlet

新建Servlet

第二个为 url映射路径

package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EclipseServletTest
 */
public class EclipseServletTest extends HttpServlet {
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EclipseServletTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

注意 web.xml 不用再手动配置,eclipse会自动添加

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JavaWeb</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>HelloServlet</servlet-name>
    <servlet-class>com.servlet.ServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>HttpServlet</servlet-name>
    <servlet-class>com.servlet.HttpServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HttpServlet</servlet-name>
    <url-pattern>/httpServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>EclipseServletTest</display-name>
    <servlet-name>EclipseServletTest</servlet-name>
    <servlet-class>com.servlet.EclipseServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EclipseServletTest</servlet-name>
    <url-pattern>/eclispeServlet</url-pattern>
  </servlet-mapping>
</web-app>
  • Servlet的生命周期

Servlet生命周期:Servlet对象从创建到销毁的过程。

  1. Servlet何时被创建又是何时被销毁的?

Servlet中有init,service,destroy方法,这几个方法称为是Servlet生命周期相关的方法。

  1. Servlet是在第一次被访问的时候会被实例化,只要Servlet一被实例化那么Servlet中的init方法就会执行(init只会执行一次)。
  2. 任何一次从客户端发送来的请求,那么Servlet中的service方法就会执行(在service方法的内部根据请求的方式不同调用不同doXXX方法)。
  3. 当Servlet从服务器中移除或者服务器关闭的时候Servlet对象被销毁,里面的destroy方法就会执行,然后垃圾回收就会将其回收掉。
  • 代码演示Servlet的生命周期

public class ServletDemo implements Servlet{
	
	/*
	 * Servlet对象被实例化的时候init方法就会执行,而且只执行一次。(Servlet是单例的)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("init执行了......");
	}
	
	/*
	 * service方法:任何一次请求都会执行service方法。可以执行多次。
	 */
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("service执行了......");
	}
	
	/*
	 * Servlet从服务器中移除或者服务器关闭的时候销毁Servlet。执行一次。
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("destroy执行了......");
	}
...
init执行了......              第一次发送请求
service执行了......           第一次发送请求
service执行了......           第二次发送请求
service执行了......           第三次发送请求
...

destroy执行了......           停止tomcat服务
...
  • Servlet的启动时加载

  • 为什么使用启动时加载

Servlet对象是第一次被访问的时候会被创建的,init方法就会执行。假设在init方法中做了一些比较耗时的操作(比如:加载了一些配置文件并且解析可能需要花费3秒钟)。第一个用户第一次访问这个Servlet的时候,需要等待3秒钟。如何使第一个用户在第一次访问的时候不需要花费这么长时间?

  • 什么是启动时加载

Servlet默认是在第一次访问的时候创建的对象,现在通过一个配置将Servlet的实例化的过程放在服务器启动的时候(让服务器启动的时候创建Servlet的对象)。如果现在这样做那么之前花费的时间就会在服务器启动的时候一起花费掉了。对于用户来讲就不需要额外花费这个时间。

  • 配置启动时加载

注意: load-on-startup 的启动优先级不能高于2,一般设置为2,因为tomcat默认servlet启动优先为1(数字越小优先级越高)

    <servlet>
    <description></description>
    <display-name>ServletDemo</display-name>
    <servlet-name>ServletDemo</servlet-name>
    <servlet-class>com.servlet.ServletDemo</servlet-class>
    <!-- 配置启动时加载 -->
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/ServletDemo</url-pattern>
  </servlet-mapping>
...
信息: Starting Servlet engine: [Apache Tomcat/9.0.27]
init执行了......                启动时
十一月 20, 2019 5:19:36 下午 org.apache.coyote.AbstractProtocol start
信息: 开始协议处理句柄["http-nio-8080"]
十一月 20, 2019 5:19:36 下午 org.apache.coyote.AbstractProtocol start
信息: 开始协议处理句柄["ajp-nio-8009"]
十一月 20, 2019 5:19:36 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in [413] milliseconds
service执行了......             第一次发送请求
service执行了......             第二次发送请求
service执行了......             第三次发送请求
十一月 20, 2019 5:20:08 下午 org.apache.catalina.core.StandardServer await
信息: A valid shutdown command was received via the shutdown port. Stopping the Server instance.
十一月 20, 2019 5:20:08 下午 org.apache.coyote.AbstractProtocol pause
信息: Pausing ProtocolHandler ["http-nio-8080"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol pause
信息: Pausing ProtocolHandler ["ajp-nio-8009"]
十一月 20, 2019 5:20:09 下午 org.apache.catalina.core.StandardService stopInternal
信息: Stopping service [Catalina]
destroy执行了......             停止tomcat服务
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol stop
信息: Stopping ProtocolHandler ["http-nio-8080"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol stop
信息: Stopping ProtocolHandler ["ajp-nio-8009"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol destroy
信息: 正在摧毁协议处理器 ["http-nio-8080"]
十一月 20, 2019 5:20:09 下午 org.apache.coyote.AbstractProtocol destroy
信息: 正在摧毁协议处理器 ["ajp-nio-8009"]
  • Servlet的访问路径的配置

  • Servlet中的urlPattern的配置
  1. 完全路径匹配
    1. 以 / 开始                 比如:/ServletDemo1    /aaa/ServletDemo2

  1. 目录匹配
    1. 以 / 开始,以 /*结束           比如:/*          /aaa/*      /aaa/bbb/*

  1. 扩展名匹配
    1. 不能以 / 开始,以*开始               比如:*.action        *.do          *.jsp

  • 访问的优先级

完全路径匹配  >  目录匹配  >  扩展名匹配

  • ServletConfig对象

ServletConfig用来获得Servlet的相关的配置信息。

如何获得 ServletConfig 对象,调用 Servlet 的 getServletConfig() 方法。

 ServletConfiggetServletConfig()
          Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.

 ServletConfig 方法

Method Summary
 StringgetInitParameter(String name)
          返回包含指定初始化参数的值的 String,如果参数不存在,则返回 null。 
 EnumerationgetInitParameterNames()
          Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
 ServletContextgetServletContext()
          返回对调用者在其中执行操作的 ServletContext 的引用。 
 StringgetServletName()
         返回此 servlet 实例的名称。该名称可能是通过服务器管理提供的,在 Web 应用程序部署描述符中分配,或者对于未注册(和未命名)的 servlet 实例,该名称将是该 servlet 的类名称。
  <servlet>
    <servlet-name>httpServlet1</servlet-name>
    <servlet-class>com.servlet.HttpServletTest</servlet-class>
    <!-- 配置Servlet的初始化参数 -->
    <init-param>
    	<param-name>userName</param-name>
    	<param-value>root</param-value>
    </init-param>
        <init-param>
    	<param-name>password</param-name>
    	<param-value>123456</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>httpServlet1</servlet-name>
    <url-pattern>/httpServlet2</url-pattern>
  </servlet-mapping>
public class HttpServletTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获得ServletConfig对象
		ServletConfig seConf = this.getServletConfig();
		//获取初始化参数的值
		String userName = seConf.getInitParameter("userName");
		String password = seConf.getInitParameter("password");
		System.out.println("userName: " + userName + ", password: " + password);
		System.out.println("-------------------");
		
		//获得所有初始化参数的名称
		Enumeration<String> names = seConf.getInitParameterNames();
		while(names.hasMoreElements()) {
			String name = names.nextElement();
			String value = seConf.getInitParameter(name);
			System.out.println("name: " + name + ", value: " + value);
		}
		System.out.println("-------------------");
		
		//获得Servlet的名称
		String servletName = seConf.getServletName();
		System.out.println(servletName);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是Post请求就会执行doPost中的代码
		doGet(req, resp);
	}

}

/*
userName: root, password: 123456
-------------------
name: password, value: 123456
name: userName, value: root
-------------------
httpServlet1
*/
  • ServletContext

ServletContext:Servlet的上下文对象。ServletContext对象对Servlet之前和之后的内容都知道。这个对象一个web项目只有一个。在服务器启动的时候为每个web项目创建一个单独的ServletContext对象。

作用一:用来获取web项目信息

因为一个web项目只有一个ServletContext对象,所以这个对象对整个项目的相关内容都是了解的。

  1. 方法:获取文件的MIME类型

获取web项目请求工程名:

获取web项目的初始化参数:

  • 作用二:读取web项目下的文件

之前使用IO流就可以读取文件(java项目中)。现在是一个web项目,web项目需要发布到tomcat下才能访问的。获取web项目下的文件如果使用传统的IO就会出现问题(原因:路径中使用的是相对路径,相对的是JRE环境)。

public class HttpServletTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获得ServletContext对象
		test3();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 如果是Post请求就会执行doPost中的代码
		doGet(req, resp);
	}
	
	/**
	 * 读取web项目下的文件:使用ServletContext读取
	 * @throws IOException 
	 */
	private void test3() throws IOException{
		// 使用ServletContext方式:
		Properties properties = new Properties();
		
		// 创建一个文件的输入流:
		//传统模式,根据getServletContext获取绝对路径
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		System.out.println(path);
		InputStream is = new FileInputStream(path);
		
		//创建一个文件的输入流:
		//InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		
		properties.load(is);
		// 获取数据:
		String driverClassName = properties.getProperty("driverClassName");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		// 输出到控制台
		System.out.println(driverClassName);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}	
	/**
	 * 读取web项目下的文件:使用ServletContext读取
	 * @throws IOException 
	 */
	private void test2() throws IOException{
		// 使用ServletContext方式:
		Properties properties = new Properties();
		// 创建一个文件的输入流:
		// InputStream is = new FileInputStream("classes/db.properties");
		InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		properties.load(is);
		// 获取数据:
		String driverClassName = properties.getProperty("driverClassName");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		// 输出到控制台
		System.out.println(driverClassName);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}

	/**
	 * 传统方式读取文件(不好使)
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void test1() throws FileNotFoundException, IOException {
		// 传统方式:
		Properties properties = new Properties();
		// 创建一个文件的输入流:
		InputStream is = new FileInputStream("classes/db.properties");
		properties.load(is);
		// 获取数据:
		String driverClassName = properties.getProperty("driverClassName");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		// 输出到控制台
		System.out.println(driverClassName);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}
}

/*
E:\JAVA2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JavaWeb\WEB-INF\classes\db.properties
com.mysql.jdbc.Driver
jdbc:mysql:///test
root
123456
*/
  • 作用三:ServletContext对象作为域对象存取数据

什么是域对象
域对象:指的是将数据存入到域对象中,这个数据就会有一定的作用范围。域指的是一定的作用范围。

  • ServletContext作为域对象的作用范围

ServletContext是在服务器启动的时候为每个web项目单独创建一个ServletContext对象。当web项目从服务器中移除,或者是关闭服务器的时候ServletContext对象会被销毁。向ServletContext中保存的数据一直存在(当服务器关闭的时候ServletContext对象被销毁,然后里面数据才会失效)。范围:整个web应用。

  • ServletContext作为域对象:
返回类型方法描述
ObjectgetAttribute(String name)返回具有给定名称的 servlet 容器属性,如果不具有该名称的属性,则返回 null。
 EnumerationgetAttributeNames()返回包含此 servlet 上下文中可用属性的名称的 Enumeration。使用带有一个属性名称的 #getAttribute 方法获取属性值。
 voidremoveAttribute(String name)从 servlet 上下文中移除具有给定名称的属性。
 voidsetAttribute(String name, Object object)将对象绑定到此 servlet 上下文中的给定属性名称。如果已将指定名称用于某个属性,则此方法将使用新属性替换具有该名称的属性。 如果在 ServletContext 上配置了侦听器,则容器将相应地通知它们。 如果传递了 null 值,则效果将与调用 removeAttribute() 相同。
public class ServletContextAttribute1 extends HttpServlet {
	
	@Override
	public void init(){
		//当ServletContextAttribute1被创建时,向ServletContext存入一个值
		this.getServletContext().setAttribute("name1", "ServletContextAttribute1");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取存入的值
		Object name1 = this.getServletContext().getAttribute("name1");
		System.out.println(name1);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}



public class ServletContextAttribute2 extends HttpServlet {
	
	@Override
	public void init(){
		//当ServletContextAttribute2被创建时,向ServletContext存入一个值
		this.getServletContext().setAttribute("name2", "ServletContextAttribute2");
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name1 = (String)this.getServletContext().getAttribute("name1");
		System.out.println(name1);
		String name2 = (String)this.getServletContext().getAttribute("name2");
		System.out.println(name2);
		System.out.println("-----------------------");
		Enumeration<String> names = this.getServletContext().getAttributeNames();
		while(names.hasMoreElements()) {
			String name = names.nextElement();
			Object value = this.getServletContext().getAttribute(name);
			System.out.println("name: " + name + ", value: " + value);
		}	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




/*
ServletContextAttribute1


ServletContextAttribute1
ServletContextAttribute2
-----------------------
name: javax.servlet.context.tempdir, value: E:\JAVA2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\JavaWeb
name: org.apache.catalina.resources, value: org.apache.catalina.webresources.StandardRoot@1c90fab5
name: org.apache.tomcat.InstanceManager, value: org.apache.catalina.core.DefaultInstanceManager@6e5b32b6
name: org.apache.catalina.jsp_classpath, value: /D:/software/apache-tomcat-9.0.27/lib/;/D:/software/apache-tomcat-9.0.27/lib/annotations-api.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-ant.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-ha.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-storeconfig.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina-tribes.jar;/D:/software/apache-tomcat-9.0.27/lib/catalina.jar;/D:/software/apache-tomcat-9.0.27/lib/ecj-4.13.jar;/D:/software/apache-tomcat-9.0.27/lib/el-api.jar;/D:/software/apache-tomcat-9.0.27/lib/jasper-el.jar;/D:/software/apache-tomcat-9.0.27/lib/jasper.jar;/D:/software/apache-tomcat-9.0.27/lib/jaspic-api.jar;/D:/software/apache-tomcat-9.0.27/lib/jsp-api.jar;/D:/software/apache-tomcat-9.0.27/lib/servlet-api.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-api.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-coyote.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-dbcp.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-cs.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-de.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-es.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-fr.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-ja.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-ko.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-pt-BR.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-ru.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-i18n-zh-CN.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-jdbc.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-jni.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-util-scan.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-util.jar;/D:/software/apache-tomcat-9.0.27/lib/tomcat-websocket.jar;/D:/software/apache-tomcat-9.0.27/lib/websocket-api.jar;/D:/software/apache-tomcat-9.0.27/bin/bootstrap.jar;/D:/software/apache-tomcat-9.0.27/bin/tomcat-juli.jar;/D:/software/Java/jdk1.8.0_171/lib/tools.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/access-bridge-64.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/cldrdata.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/dnsns.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/jaccess.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/jfxrt.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/localedata.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/nashorn.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunec.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunjce_provider.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunmscapi.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/sunpkcs11.jar;/D:/software/Java/jdk1.8.0_171/jre/lib/ext/zipfs.jar
name: javax.websocket.server.ServerContainer, value: org.apache.tomcat.websocket.server.WsServerContainer@609cd10d
name: name2, value: ServletContextAttribute2
name: name1, value: ServletContextAttribute1
name: org.apache.jasper.compiler.TldCache, value: org.apache.jasper.compiler.TldCache@64a359c6
name: org.apache.tomcat.JarScanner, value: org.apache.tomcat.util.scan.StandardJarScanner@7cbf05fa
*/
  • Response

  • Response关于响应行的方法

 

ModifierConstructor描述
voidsetStatus(int sc) 设置此响应的状态代码。
voidsetStatus(int sc, String sm) 从版本 2.1 起,由于消息参数的含义不明确。使用 setStatus(int) 设置状态代码,使用 sendError(int, String) 发送带描述的错误。 设置此响应的状态代码和消息。 sc 状态代码 sm 状态消息 
 
  1. 设置响应的状态码
    1. 200 正确
    2. 302 重定向
    3. 304 查找本地缓存
    4. 404 请求资源不存在
    5. 500 服务器内部错误
  • Response关于响应头的方法
  1. set开头的方法:针对一个key对应一个value的情况。
    1. 举例:比如有一个头 content-Type:text/html  setHeader(“content-Type”,”text/plain”);
    2. 最终得到头的结果:content-Type:text/plain
 voidsetDateHeader(String name, long date)
          Sets a response header with the given name and date-value.
 voidsetHeader(String name, String value)
          Sets a response header with the given name and value.
 voidsetIntHeader(String name, int value)
          Sets a response header with the given name and integer value.
  1. add开头的方法:针对一个key对应多个value的情况。
    1. 举例:比如有一个content-Type:text/html    addHeader(“content-Type”,”text/plain”);
    2. 最终得到头的结果:content-Type:text/html,text/plain
 voidaddCookie(Cookie cookie)
          Adds the specified cookie to the response.
 voidaddDateHeader(String name, long date)
          Adds a response header with the given name and date-value.
 voidaddHeader(String name, String value)
          Adds a response header with the given name and value.
 voidaddIntHeader(String name, int value)
          Adds a response header with the given name and integer value.
  • Response关于响应体的方法

在httpServletResponse的父类中

ServletOutputStreamgetOutputStream()
          Returns a ServletOutputStream suitable for writing binary data in the response.
 PrintWritergetWriter()
          Returns a PrintWriter object that can send character text to the client.

重定向的方法

 voidsendRedirect(String location)
          Sends a temporary redirect response to the client using the specified redirect location URL.

设置浏览器打开页面时候采用的字符集

 voidsetContentType(String type)
          Sets the content type of the response being sent to the client, if the response has not been committed yet.

设置响应字符流的缓冲区字符集

 voidsetCharacterEncoding(String charset)
          Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

服务器向浏览器回写Cookie的方法

 voidaddCookie(Cookie cookie)
          Adds the specified cookie to the response.
  • Response对象API的代码演示

重定向:302状态码和Location响应头结合使用的效果。

public class NotFoundRedirect extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");  //解决中文不能正常显示问题
		response.getWriter().println("404页面找不到了!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}


public class ResultRedirect extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//重定向
		response.setStatus(302);
		//设置响应头
		response.setHeader("Location", "/JavaWeb/NotFoundRedirect");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

  • 实际开发中可以使用:response.sendRedirect(“/JavaWeb/NotFoundRedirect”);替换重定向两句写法
public class ResultRedirect extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//重定向
		response.setStatus(302);
		//设置响应头
		//response.setHeader("Location", "/JavaWeb/NotFoundRedirect");
		//替换重定向两句写法
		response.sendRedirect("/JavaWeb/NotFoundRedirect");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

定时刷新

public class Fresh extends HttpServlet {
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//定时刷新
		response.setContentType("text/html;charset=UTF-8");  //解决中文不能正常显示问题
		response.getWriter().println("页面5秒后跳转");
		response.setHeader("Refresh", "5;url=/JavaWeb/NotFoundRedirect");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

使用JS完成读秒的效果

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="5;url=/JavaWeb/demo2.html">
<title>Insert title here</title>
<script type="text/javascript">
	var i = 5;
	function load(){
		window.setInterval("changeSeconds()",1000);
	}
	
	function changeSeconds(){
		i--;
		document.getElementById("span1").innerHTML=i;
	}
</script>
</head>
<body onload="load()">
<h1>demo1.html</h1>
<h3>页面将在<span id="span1">5</span>秒后跳转到demo2.html</h3>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>demo2.html</h1>
</body>
</html>
  • Response对象响应的中文乱码处理

ServletOutputStreamgetOutputStream()
          Returns a ServletOutputStream suitable for writing binary data in the response.
 PrintWritergetWriter()
          Returns a PrintWriter object that can send character text to the client.

使用字节流响应中文

  1. 编写代码

****使用上述代码向页面输出中文是否会有乱码?

  1. 不一定
    1. 其实这个乱码的产生与中文转成字节数组及浏览器打开方式(打开的时候采用的默认字符集)有关
  2. 解决:
    1. 将中文转成字节数组的时候和浏览器默认打开的时候采用的字符集一致即可。

使用字符流响应中文

  1. 编写代码

****使用上述代码向页面输出中文是否会产生乱码?

  1. 一定乱码
    1. 原因:
      1. 字符流是有缓冲区的,response获得字符流,response设计默认的缓冲区编码是ISO-8859-1。这个字符集不支持中文的。
    2. 解决:
      1. 设置response获得字符流缓冲区的编码和设置浏览器默认打开时候采用的字符集一致即可。

字符流向页面响应中文,有一种简化的方式:

 

/**
 * Response响应中文的处理
 */
public class ResponseDemo3 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		test2(response);
	}
	/**
	 * 使用字符流输出中文
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	private void test2(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
		// 设置浏览器默认打开的时候采用的字符集:
		// response.setHeader("Content-Type", "text/html;charset=UTF-8");
		// 设置response获得字符流的缓冲区的编码:
		// response.setCharacterEncoding("UTF-8");
		// 简化代码
		response.setContentType("text/html;charset=UTF-8");
		// 会不会产生乱码
		response.getWriter().println("中文");
	}
	/**
	 * 使用字节流输出中文
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	private void test1(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
		// 使用字节流的方式输出中文:
		ServletOutputStream outputStream = response.getOutputStream();
		// 设置浏览器默认打开的时候采用的字符集
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		// 设置中文转成字节数组字符集编码
		outputStream.write("中文".getBytes("UTF-8"));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
  • Request

什么是Request对象:开发的软件都是B/S结构软件,从浏览器向服务器提交一些数据,将这些内容进行封装就封装成了一个请求对象(Request对象)。

获得请求的方式

StringgetMethod()
          返回用于发出此请求的 HTTP 方法的名称,例如 GET、POST 或 PUT。

获得请求路径后的提交参数的字符串

 StringgetQueryString()
          返回包含在请求 URL 中路径后面的查询字符串。如果 URL 没有查询字符串,则此方法返回 null。

获得请求路径的URL和URI

URL:URL(Uniform Resource Locator,统一资源定位符),它是WWW的统一资源定位标志,就是指网络地址。

URI:统一资源标识符(Uniform Resource Identifier,URI)是一个用于标识某一互联网资源名称的字符串。 该种标识允许用户对任何(包括本地和互联网)的资源通过特定的协议进行交互操作。

StringBuffergetRequestURL()重新构造客户端用于发出请求的 URL。返回的 URL 包含一个协议、服务器名称、端口号、服务器路径,但是不包含查询字符串参数。
StringgetRequestURI()返回此请求的 URL 的一部分,从协议名称一直到 HTTP 请求的第一行中的查询字符串。Web 容器不会解码此 String。例如: HTTP 请求的第一行  返回的值 
POST /some/path.html HTTP/1.1  /some/path.html  
GET http://foo.bar/a.html HTTP/1.0   /a.html  
HEAD /xyz?a=b HTTP/1.1  /xyz  

获得客户机的IP地址: 方法在其父类里面

 StringgetRemoteAddr()
         返回发送请求的客户端或最后一个代理的 Internet Protocol (IP) 地址。
  • 获得请求头的方法

获得一个key对应一个value的请求头

 StringgetHeader(String name)
          Returns the value of the specified request header as a String.

获得一个key对应多个value的请求头

EnumerationgetHeaders(String name)
          Returns all the values of the specified request header as an Enumeration of String objects.

获得请求参数的方法

  • 获得提交的参数(一个name对应一个value)

  • 获得提交的参数(一个name对应多个value)

  • 获得提交的参数,将提交的参数的名称和对应的值存入到一个Map集合中

请求地址: http://192.168.109.1:8080/JavaWeb/RequestDemo1?id=01&name=‘l李茂贞’

package com.request;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RequestDemo1
 */
public class RequestDemo1 extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得请求的方式
		String requestMethod = request.getMethod();
		System.out.println("获得请求的方式:" + requestMethod);
		
		//获得请求路径后的提交参数的字符串
		String parameters = request.getQueryString();
		System.out.println("获取路径后的参数:" + parameters);
		
		//获得客户机的IP地址: 方法在其父类里面
		String ip = request.getRemoteAddr();
		System.out.println("客户机的IP地址:" + ip);
		
		// 获得请求头的信息
		System.out.println("获得客户机浏览器类型:"+request.getHeader("User-Agent"));
		
		// 获得请求路径的URL和URI
		System.out.println("请求路径的URL:"+request.getRequestURL());
		System.out.println("请求路径的URI:"+request.getRequestURI());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

/*
获得请求的方式:GET
获取路径后的参数:id=01&name=%27%E6%9D%8E%E8%8C%82%E8%B4%9E%27
客户机的IP地址:192.168.109.1
获得客户机浏览器类型:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36
请求路径的URL:http://192.168.109.1:8080/JavaWeb/RequestDemo1
请求路径的URI:/JavaWeb/RequestDemo1

*/
  • Request作为域对象存取数据的方法

  • 向request域中存数据

  • 从request域中获取数据

  • 从request域中移除数据

 

 

 StringgetParameter(String name)
          以 String 形式返回请求参数的值,如果该参数不存在,则返回 null。
 MapgetParameterMap()
          返回此请求的参数的 java.util.Map。请求参数是与请求一起发送的额外信息。
 EnumerationgetParameterNames()
          返回包含此请求中所包含参数的名称的 String 对象的 Enumeration。如果该请求没有参数,则此方法返回一个空的 Enumeration。 
 String[]getParameterValues(String name)
          返回包含给定请求参数拥有的所有值的 String 对象数组,如果该参数不存在,则返回 null。 
/**
 * 表单提交数据
 */
public class RequestDemo02 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// getParameter接收用户名和密码:
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username:" + username + ", password:" + password);
		
		// 接收爱好:
		String[] hobby = request.getParameterValues("hobby");
		System.out.println("爱好:" + Arrays.toString(hobby));
				
		//getParameterMap()
		Map<String, String[]> map = request.getParameterMap();
		for (String key:map.keySet()) {
			String[] value = map.get(key);
			System.out.println(key+"    "+Arrays.toString(value));
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

get请求方式

<h1>request接收表单参数</h1>
<form action="/web01/RequestDemo2" method="get">
	用户名:<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/>
	籍贯:<select name="city">
		<option value="beijing">北京市</option>
		<option value="shanghai">上海市</option>
		<option value="shenzhen">深圳市</option>
	</select><br/>
	爱好:<input type="checkbox" name="hobby" value="basketball"/>篮球
	<input type="checkbox" name="hobby" value="football"/>足球
	<input type="checkbox" name="hobby" value="volleyball"/>排球<br/>
	自我介绍:<textarea name="info" rows="3" cols="8"></textarea><br/>
	<input type="submit" value="提交">
</form> 

 

http://localhost:8080/JavaWeb/RequestDemo02?username=%E6%9D%8E%E8%8C%82%E8%B4%9E&password=123456&sex=man&city=shanghai&hobby=basketball&hobby=football&info=%E5%A3%81%E7%AB%8B%E5%8D%83%E4%BB%9E%EF%BC%8C%E6%97%A0%E6%AC%B2%E5%88%99%E5%88%9A


/*
username:李茂贞, password:123456
爱好:[basketball, football]
username    [李茂贞]
password    [123456]
sex    [man]
city    [shanghai]
hobby    [basketball, football]
info    [壁立千仞,无欲则刚]

*/

post请求方式

<h1>request接收表单参数</h1>
<form action="/JavaWeb/RequestDemo02" 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/>
	籍贯:<select name="city">
		<option value="beijing">北京市</option>
		<option value="shanghai">上海市</option>
		<option value="shenzhen">深圳市</option>
	</select><br/>
	爱好:<input type="checkbox" name="hobby" value="basketball"/>篮球
	<input type="checkbox" name="hobby" value="football"/>足球
	<input type="checkbox" name="hobby" value="volleyball"/>排球<br/>
	自我介绍:<textarea name="info" rows="3" cols="8"></textarea><br/>
	<input type="submit" value="提交">
</form> 

http://localhost:8080/JavaWeb/RequestDemo02
/*
username:ææ·³é£, password:123456
爱好:[basketball, football]
username    [ææ·³é£]
password    [123456]
sex    [man]
city    [shenzhen]
hobby    [basketball, football]
info    [海纳ç¾å·ï¼æ容ä¹å¤§]

*/
  • Request对象接收中文乱码问题

/**
 * Request接收中文数据
 */
public class RequestDemo3 extends HttpServlet {
	/**
	 * 演示get方式处理中文乱码
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 接收数据:
		// request.setCharacterEncoding("UTF-8");
		/**
		 * 产生乱码原因:
		 * * get方式提交的数据在请求行的url后面,在地址栏上其实就已经进行了一次URL的编码了。
		 * 解决方案:
		 * * 将存入到request缓冲区中的值以ISO-8859-1的方式获取到,以UTF-8的方式进行解码。
		 */
		String name = request.getParameter("name");
		/*String encode = URLEncoder.encode(name, "ISO-8859-1");
		String decode = URLDecoder.decode(encode, "UTF-8");
		System.out.println("姓名:"+decode);*/
		String value = new String(name.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println("姓名:"+value);
	}

	/**
	 * 演示post方式处理中文乱码
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// 接收数据:
		/**
		 * 产生乱码的原因:
		 * * post方式提交的数据是在请求体中,request对象接收到数据之后,放入request的缓冲区中。缓冲区就有编码(默认ISO-8859-1:不支持中文).
		 * 解决方案:
		 * * 将request的缓冲区的编码修改了即可。
		 */
		// 设置缓冲区的编码
		request.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		System.out.println("姓名:"+name);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Toroidals

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值