tomcat服务器与Http协议之请求(get请求、post请求)和响应

本文主要介绍了在Web开发中,Tomcat服务器如何处理HTTP协议的请求,包括GET和POST请求的方式,以及对应的HTTP响应过程。通过学习,读者可以深入理解Http协议的基础知识和在实际开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
1)web服务软件作用: 把本地资源共享给外部访问
2)tomcat服务器基本操作	:
	启动:  %tomcat%/bin/startup.bat 
	关闭: %tomcat%/bin/shutdown.bat

	访问tomcat主页:
		http://localhost:8080
3)web应用目录结构
	|- WebRoot   根目录
		|-静态资源(html+css+javascript+images+xml)  可以直接被浏览器访问到的
		|-WEB-INF                                  不可以直接被浏览器访问到
			|-classes     存放class字节码文件
			|-lib         存放jar包文件
			web.xml      web应用的配置文件,配置servlet
		
4)Servlet技术: 用java语言开发动态资源的技术
	开发一个Servlet程序的步骤:
		1)创建一个java类,继承HttpServlet类
		2)重写HttpServlet类的doGet方法
		3)把写好的servlet程序交给tomcat服务器运行!!!!
			3.1 把编译好的servlet的class文件拷贝到tomcat的一个web应用中。(web应用										的WEB-INF/classes目录下)		
			3.2 在当前web应用的web.xml文件中配置servlet
				<!-- servlet配置 -->
				<servlet>
					<servlet-name>HelloServlet</servlet-name>
					<servlet-class>gz.itcast.HelloServlet</servlet-class>
				</servlet>
				<!--  servlet的映射配置 -->
				<servlet-mapping>
					<servlet-name> HelloServlet </servlet-name>
					<url-pattern>/hello</url-pattern>
				</servlet-mapping>
		4)访问servlet
			http://localhost:8080/myweb/hello

1)http协议: 对浏览器客户端和服务器端之间数据传输的格式规范。
2)http请求:浏览器->服务器端
	格式: 
		请求行(请求方式(GET/POST) 请求资源(URI) http协议版本(http1.1))
		请求头(键值对形式存在。 host、user-agent、referer)
		一个空行
		实体内容(POST提交的参数)
	HttpServletRequest对象: 请求对象。获取请求信息。
	请求行:request.getMethod()   request.getRequestURI/getRequestURL()  request.getProtocol();
	请求头: request.getHeader("name")    request.getHeaderNames()  
	实体内容: request.getInputStream() 

	获取参数数据:(GET或POST)
		request.getParameter("name")  一个值的参数
		request.getParameterValues("name"); 多个值的参数
		request.getParameterNames()    所有参数
				
3)http响应: 服务器->浏览器端
	格式: 
		响应行(http协议版本 状态码 描述)
			常用的状态码: 200   302  404   500
		响应头( location(结合302状态码完成请求重定向功能)、 refresh(定时刷新)、content-type、							content-disiposition(以下载方式打开)) 
		一个空行
		实体内容
	HttpServletResponse对象: 响应对象。设置响应信息。
		响应行: response.setStatus();
		响应头: response.setHeader("name","value")
		实体内容: 
			(PrintWriter) response.getWriter().writer(); 字符内容
			(OutputStream)response.getOutputStream().writer();  字节内容			
*/

1 Web开发入门

/*
1.1 引入
	之前的程序: java桌面程序,控制台控制,socket gui界面。javase规范
	现在和以后的程序:java web程序。浏览器控制。javaee规范
1.2 软件的结构
	C/S (Client - Server  客户端-服务器端)
			典型应用:QQ软件 ,飞秋,红蜘蛛。
			特点:
				1)必须下载特定的客户端程序。
				2)服务器端升级,客户端升级。

	B/S (Broswer -Server 浏览器端- 服务器端)
			典型应用: 腾讯官方(www.qq.com)  163新闻网站, 传智官网(俗称:网站)
			特点:
				1)不需要安装特定的客户端(只需要安装浏览器即可!!)
				2)服务器端升级,浏览器不需要升级!!!!

			javaweb的程序就是b/s软件结构!!!
1.3 服务器
	从物理上来说,服务器就是一台PC机器。8核,8G以上,T来计算,带宽100M

	web服务器:PC机器安装一个具有web服务的软件,称之为web服务器
	数据库服务器:PC机器安装一个具有数据管理件服务的软件,称之为数据库服务器。
	邮件服务器:PC机器安装一个具有发送邮件服务的软件,称之为邮件服务器。
1.4 web服务软件
	web服务软件的作用:把本地的资源共享给外部访问。

1.5 常见的市面上web服务软件
	javase的规范,包含IO流,线程,集合,socket编程。。。。
	WebLogic: BEA公司的产品。 收费的。支持JavaEE规范。
	WebSphere: IBM公司的产品。收费的。支持JavaEE规范
	JBoss: Redhat公司的产品。收费的。支持JavaEE规范
	Tomcat: 开源组织Apache的产品。免费的。支持部分的JavaEE规范。(servlet、jsp。jdbc,但	
	ejb, rmi不支持)
*/	
2 Tomcat基本使用
/*
2.1 下载并安装
	1)到apache官网。www.apache.org     http://jakarta.apache.org(产品的主页)
	2)安装版:window (exe、msi) linux(rmp)
	   压缩版:window(rar,zip) linux(tar,tar.gz)学习时候使用
	3)运行和关闭tomcat
		3.1 启动软件
			a)找到%tomcat%/bin/startup.bat ,双击这个文件
			b)弹出窗口,显示信息(不要关闭次窗口)
			c)打开浏览器,输出以下地址
				http://localhost:8080
			d)看到一只猫画面,证明软件启动成功!

		3.3 关闭软件
			a)找到%tomcat%/bin/shutdown.bat,双击这个文件即可!
			c)打开浏览器,输出以下地址。看到“无法连接”(最好先清空浏览器缓存)
			
2.2 tomcat软件使用的常见问题
	1)闪退问题
	原因:tomcat软件是java语言开发的。 tomcat软件启动时,会默认到系统的环境变量中查找一个名称叫JAVA_HOME的变量。这个变量的作用找到tomcat启动所需的jvm。
	解决办法; 到环境变量中设置JAVA_HOME的变量
		JAVA_HOME= C:\Program Files\Java\jdk1.6.0_30  (注意别配置到bin目录下)
			
	2)端口占用的错误
	原因: tomcat启动所需的端口被其他软件占用了!
	解决办法: 
		a)关闭其他软件程序,释放所需端口
		b)修改tomcat软件所需端口
		   找到并修改%tomcat%/conf/server.xml文件			
			<Connector port="8081" protocol="HTTP/1.1" 
				connectionTimeout="20000" 
				redirectPort="8443" />

		3)CATALINA环境变量问题
			原因: tomcat软件启动后,除了查找JAVA_HOME后,还会再查找一个叫CATALINA_HOME变量,这个变量的作用是设置tomcat的根目录。
			解决办法:建议不要设置CATALINA_HOME变量。检查如果有的话,清除掉!!!

2.3 体验tomcat软件作用
	webapps目录: tomcat共享目录。需要共享的本地资源放到此目录中。
	
2.4 URL
	URL全名叫统一资源定位符,用于定位互联网的资源。

	问题: http://localhost:8081/myweb/test.html  看到文件?

	http://     协议。http协议。
	localhost   域名。为了找到IP地址。
					本地域名: localhost
					外部域名:www.baidu.com
	8081       端口。软件监听的
				8080: tomcat默认的端口
				3306:mysql数据库的端口
				1521: orace数据库的端口。
	/myweb:   web应用的名称。默认情况下,在webapps目录下找
	/test.html  : 资源名称。
*/
3 Tomcat的目录结构
/*
|-bin: 存放tomcat的命令。
		catalina.bat命令:
			startup.bat  -> catalina.bat start	
			shutdown.bat - > catalina.bat stop
|-conf: 存放tomcat的配置信息。其中server.xml文件是核心的配置文件。
|-lib:支持tomcat软件运行的jar包。其中还有技术支持包,如servlet,jsp
|-logs:运行过程的日志信息
|-temp: 临时目录
|-webapps:共享资源目录。web应用目录。(注意不能以单独的文件进行共享)
|-work:tomcat的运行目录。jsp运行时产生的临时文件就存放在这里
*/
4 Web应用的目录结构
/*
|- WebRoot: web应用的根目录
		|- 静态资源(html+css+js+image+vedio)
		|- WEB-INF : 固定写法。
			|-classes: (可选)固定写法。存放class字节码文件
			|-lib: (可选)固定写法。存放jar包文件。
			|-web.xml    

注意:
	1)WEB-INF目录里面的资源不能通过浏览器直接访问
	2)如果希望访问到WEB-INF里面的资源,就必须把资源配置到一个叫web.xml的文件中。
*/
5 手动开发动态资源
/*
5.1 静态资源和动态资源的区别
	静态资源: 当用户多次访问这个资源,资源的源代码永远不会改变的资源。
	动态资源: 当用户多次访问这个资源,资源的源代码可能会发生改变
	
5.2 动态资源的开发技术
	Servlet : 用java语言来编写动态资源的开发技术。

	Servlet特点:
		1)普通的java类,继承HttpServlet类,覆盖doGet方法
		2)Servlet类只能交给tomcat服务器运行!!!!(开发者自己不能运行!!!)

	Servlet手动编写步骤:
		1)编写一个servlet程序,继承HttpServlet(导入tomcat服务器lib包下的servlet架包)	
			public class HelloServlet extends HttpServlet{

				@Override
				protected void doGet(HttpServletRequest req, HttpServletResponse resp)
						throws ServletException, IOException {
					//解决中文乱码问题
					resp.setContentType("text/html;charset=utf-8");
					//向浏览器输出内容
					resp.getWriter().write("这是第一个servlet程序。当前时间为:"+new Date());
				}
			}

		2)找到HelloServlet类的bin目录下的class字节码,然后把拷贝到tomcat的一个web应用中WEB-INF/classes目录下。
		3)在当前web应用下的web.xml文件配置Servlet。
				
			<!-- 配置一个servlet程序 -->
			<servlet>
				<!-- servlet的内部名称 ,可以自定义-->
				<servlet-name>HelloServlet</servlet-name>
				<!-- servlet类名: 包名+简单类名-->
				<servlet-class>gz.itcast.d_servlet.HelloServlet</servlet-class>
			</servlet>

			<servlet-mapping>
				<!-- servlet的内部名称,和上面的名称保持一致!!!-->
				<servlet-name>HelloServlet</servlet-name>
				<!-- servlet的访问名称: /名称 -->
				<url-pattern>/hello</url-pattern>
			</servlet-mapping>

		4)启动tomcat服务器,运行访问
			访问servlet:  http://localhost:8080/myweb/ 
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * socket服务器端程序
 */
public class Server {

	public static void main(String[] args) throws Exception {
		//1.创建ServerSocket
		ServerSocket server = new ServerSocket(8080);
		
		System.out.println("服务器已经启动成功....");
		
		while(true){
			//2.接收客户端的连接
			Socket socket = server.accept();
			
			//3.读取本地的test.html文件
			FileInputStream in = new FileInputStream(new File("e:/web/test.html"));
			
			//4.构建数据输出通道
			OutputStream out = socket.getOutputStream();
			
			//5.发送数据
			byte[] buf = new byte[1024];
			int len = 0;
			while( (len=in.read(buf))!=-1 ){
				out.write(buf, 0, len);
			}
			
			//6.关闭资源
			out.close();
			in.close();
		}
		
	}

}

6 工具开发动态资源

/*
1)创建web project (javaweb工程)
2)在WebRoot下建立静态资源文件,
3)在src下建立动态资源文件
	3.1 new -> Servlet( servlet的代码生成器)
	3.2 写pacakge -> class名 -> 修改mapping  url 
4)关联tomcat服务器(不一定非要关联,关联的目的只是让服务器自动拷贝文件,可通过bat处理文件加载到任务栏一键拷贝到自己的服务器,参考地址:http://blog.youkuaiyun.com/tideseng/article/details/70237773)
	4.1 window-> Preferences - > MyEcplise -> servers -> Tomcat 6.x (注意一定要enable)
5)部署web project应用。(拷贝web应用到tomcat的webapps目录下)
6)启动tomcat服务器(没有关联服务器可将自己服务器的startup.bat文件添加到任务栏一键开启,并将conf目录下的context.xml文件中的Context标签后添加reloadable="true"让服务器自动加载重启)
7)访问servlethttp://localhost:8081/web/hello
*/

7 Http协议入门

/*
7.1 什么是http协议
	http协议: 对浏览器客户端和服务器端之间数据传输的格式规范
	tcp/ip协议:关注的是客户端与服务器之间数据是否传输成功
	http协议:是在tcp/ip协议之上封装的一层协议,关注的是数据传输的格式是否规范
	
7.2 查看http协议的工具
	1)使用火狐的firebug插件(右键->firebug->网络)
	2)使用谷歌的“审查元素”
	3)使用系统自带的telnet工具(远程访问工具)				
		a)telnet localhost 8080 访问tomcat服务器
		b)ctrl+] 回车 可以看到回显
		c)输入请求内容							
			GET /myweb/hello HTTP/1.1
			Host: localhost:8080
			Connection: keep-alive
		d)回车,即可查看到服务器响应信息。

7.3 http协议内容			
	请求(浏览器-->服务器)
		GET /day09/hello HTTP/1.1
		Host: localhost:8080
		User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
		Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8
		Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
		Accept-Encoding: gzip, deflate
		Connection: keep-alive
	
	响应(服务器-->浏览器)
		HTTP/1.1 200 OK
		Server: Apache-Coyote/1.1
		Content-Length: 24
		Date: Fri, 30 Jan 2015 01:54:57 GMT

		this is hello servlet!!!
*/


8 Http请求

/*
GET /day09/hello HTTP/1.1              --请求行
Host: localhost:8080                   --请求头(多个key-value对象)
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8
Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
                                      --一个空行
name=eric&password=123456             --(可选)实体内容

8.1 请求行
	GET /day09/hello HTTP/1.1     
		#http协议版本
			http1.0:当前浏览器客户端与服务器端建立连接之后,只能发送一次请求,一次请求之后连接关闭。
			http1.1:当前浏览器客户端与服务器端建立连接之后,可以在一次连接中发送多次请求。(基本都使用1.1)(寻找资源等图片也是一次请求)
	#请求资源
		URL:  统一资源定位符。http://localhost:8080/day09/testImg.html。只能定位互联网资源。是URI							的子集。
		URI: 统一资源标记符。/day09/hello。用于标记任何资源。可以是本地文件系统,局域网的资源(//192.168.14.10/myweb/index.html),						可以是互联网。
	#请求方式
		常见的请求方式: GET 、 POST、 HEAD、 TRACE、 PUT、 CONNECT 、DELETE	

		常用的请求方式: GET  和 POST	

		表单提交:
			<form action="提交地址" method="GET/POST">	

			<form>

		GET  vs  POST 区别

		1)GET方式提交 
			a)地址栏(URI)会跟上参数数据。以?开头,多个参数之间以&分割。
				GET /day09/testMethod.html?name=eric&password=123456 HTTP/1.1
				Host: localhost:8080
				User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
				Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8
				Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
				Accept-Encoding: gzip, deflate
				Referer: http://localhost:8080/day09/testMethod.html
				Connection: keep-alive

			b)GET提交参数数据有限制,不超过1KB。
			c)GET方式不适合提交敏感密码。
			d)注意: 浏览器直接访问的请求,默认提交方式是GET方式
		2)POST方式提交
			a)参数不会跟着URI后面。参数而是跟在请求的实体内容中。没有?开头,多个参数之间以&分割。
				POST /day09/testMethod.html HTTP/1.1
				Host: localhost:8080
				User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
				Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8
				Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3
				Accept-Encoding: gzip, deflate
				Referer: http://localhost:8080/day09/testMethod.html
				Connection: keep-alive

				name=eric&password=123456

			b)POST提交的参数数据没有限制。
			c)POST方式提交敏感数据。
			
8.2 请求头
	Accept: text/html,image/*      		 -- 浏览器接受的数据类型
	Accept-Charset: ISO-8859-1     		 -- 浏览器接受的编码格式
	Accept-Encoding: gzip,compress  	 --浏览器接受的数据压缩格式
	Accept-Language: en-us,zh-       	 --浏览器接受的语言
	Host: www.it315.org:80          	 --(必须的)当前请求访问的目标地址(主机:端口)
	If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT  --浏览器最后的缓存时间
	Referer: http://www.it315.org/index.jsp      -- 当前请求来自于哪里
	User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)  --浏览器类型
	Cookie:name=eric                     -- 浏览器保存的cookie信息
	Connection: close/Keep-Alive         -- 浏览器跟服务器连接状态。close: 连接关闭  keep-alive:保存连接。
	Date: Tue, 11 Jul 2000 18:23:51 GMT  -- 请求发出的时间

8.3 实体内容
	只有POST提交的参数会放到实体内容中

8.4 HttpServletRequest对象
	HttpServletRequest对象作用是用于获取请求数据。

		核心的API:
			请求行: 
				request.getMethod();   请求方式
				request.getRequetURI()   / request.getRequetURL()   请求资源
				request.getProtocol()   请求http协议版本
			
			请求头:
				request.getHeader("名称")   根据请求头获取请求值
				request.getHeaderNames()    获取所有的请求头名称

			实体内容:
				request.getInputStream()   获取实体内容数据
				
8.5 service 和 doXX方法区别

8.6 案例-获取浏览器的类型(user-agent)

8.7 案例- 防止非法链接(referer)
	第1次  优快云/51CTO  ->  页面(点击下载) -> 弹出广告页面(点击此处下载) -> 开始下载  
	第2次  直接点击此处下载  ->  转回广告页面  ->  开始下载

		非法链接:							
			1)直接访问下载的资源
			2)不是从广告页面过来的链接

		referer: 当前请求来自于哪里。
		
8.8 传递的请求参数如何获取		
	GET方式: 参数放在URI后面
	POST方式: 参数放在实体内容中

	获取GET方式参数:
			request.getQueryString();
	获取POST方式参数:
			request.getInputStream();

	问题:但是以上两种不通用,而且获取到的参数还需要进一步地解析。
	所以可以使用统一方便的获取参数的方式:
		
	核心的API:
	request.getParameter("参数名");  根据参数名获取参数值(注意,只能获取一个值的参数)
	request.getParameterValue("参数名“);根据参数名获取参数值(可以获取多个值的参数)

	request.getParameterNames();   获取所有参数名称列表 
	
8.9 请求参数编码问题
	修改POST方式参数编码:
		request.setCharacterEncoding("utf-8");
	修改GET方式参数编码:
		手动解码:String name = new String(name.getBytes("iso-8859-1"),"utf-8");
	指定服务器编码:
		server.xml文件Connector标签—>URIEncoding="utf-8"
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

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

/**
 * 请求数据的获取
 */
public class RequestDemo1 extends HttpServlet {

	/**
	 * 1)tomcat服务器接收到浏览器发送的请求数据,然后封装到HttpServetRequest对象
	 * 2)tomcat服务器调用doGet方法,然后把request对象传入到servlet中。
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 3)从request对象取出请求数据。
		 */
		//t1(request);
		
		//t2(request); 	
	}
	
	// 为了接收POST方式提交的请求
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		/**
		 * 3.3 请求的实体内容
		 */
		InputStream in = request.getInputStream(); //得到实体内容
		byte[] buf = new byte[1024];
		int len = 0;
		while((len=in.read(buf))!=-1 ){
			String str = new String(buf,0,len);
			System.out.println(str);
		}
	}

	private void t2(HttpServletRequest request) {
		/**
		 * 3.2 请求头
		 */
		String host = request.getHeader("Host"); //根据头名称得到头的内容
		System.out.println(host);
		
		//遍历所有请求头
		Enumeration<String> enums = request.getHeaderNames(); //得到所有的请求头名称列表
		while(enums.hasMoreElements()){//判断是否有下一个元素
			String headerName = enums.nextElement(); //取出下一个元素
			String headerValue = request.getHeader(headerName);
			System.out.println(headerName+":"+headerValue);
		}
	}

	private void t1(HttpServletRequest request) {
		/**
		 * 3.1 请求行   格式:(GET /day09/hello HTTP/1.1)
		 */
		System.out.println("请求方式:"+request.getMethod());//请求方式
		System.out.println("URI:"+request.getRequestURI());//请求资源
		System.out.println("URL:"+request.getRequestURL());
		System.out.println("http协议版本:"+request.getProtocol());//http协议
	}

}
<html>
  <head>
    <title>testMethod.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <h3>GET方式提交</h3>
    <form action="testMethod.html" method="GET">
    	用户名:<input type="text" name="name"/><br/>
    	密码:<input type="password" name="password"/><br/>
    	<input type="submit" value="提交"/>
    </form>
    <hr/>
    
    <h3>POST方式提交</h3>
    <form action="/Web/RequestDemo1" method="POST">
    	用户名:<input type="text" name="name"/><br/>
    	密码:<input type="password" name="password"/><br/>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>
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 RequestDemo2 extends HttpServlet {
/**
 * 注意:tomcat服务器首先会调用servlet的service方法,然后在service方法中再根据请求方式来分别调用对应的doXX方法
 * (例如,如果是GET请求方式,在service方法中调用doGet方法)
 * 
 *   因为最常的请求方式是GET 和POST,所以编写servlet程序,只需要覆盖doGet和doPost即可!!!!
 */
	
	/*@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println(req.getMethod());
		System.out.println("service方法被调用");
		if ("GET".equals(req.getMethod())) {
			doGet(req, resp);
		} else if("POST".equals(req.getMethod())){
			doPost(req, resp);
		}
	}*/
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println(req.getMethod());
		System.out.println("service方法被调用");
		super.service(req, resp);
	}
	
	// 该方法用于接收浏览器的Get方式提交的请求
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("GET方式提交");
	}
	
	// 该方法用于接收浏览器的Post方式提交的请求
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("Post方式提交");
	}

}
案例-获取浏览器的类型
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 RequestDemo3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		//获取请求头: user-agent
		String userAgent = request.getHeader("user-agent");
		System.out.println(userAgent);
		
		//判断用户使用的浏览器类型
		if(userAgent.contains("Firefox")){
			response.getWriter().write("你正在使用火狐浏览器");
		}else if(userAgent.contains("Chrome")){
			response.getWriter().write("你正在使用谷歌浏览器");
		}else if(userAgent.contains("Trident")){
			response.getWriter().write("你正在使用IE浏览器");
		}else{
			response.getWriter().write("地球上没有这个浏览器,建议使用火狐浏览器");
		}
	}

}
案例- 防止非法链接
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 RequestDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		
		//得到referer头
		String referer = request.getHeader("referer");
		System.out.println("referer="+referer);
		
		/**
		 * 判断非法链接:
		 * 	1)直接访问的话referer=null
		 *  2)如果当前请求不是来自广告   
		 */
		if(referer==null || !referer.contains("/Web/adv.html")){
			response.getWriter().write("当前是非法链接,请回到首页。<a href='/Web/adv.html'>首页</a>");
		}else{
			//正确的链接
			response.getWriter().write("资源正在下载...");
		}
	
	}

}
获取GET方式和Post方式提交的参数
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 获取GET方式和Post方式提交的参数
 */
public class RequestDemo5 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 设置参数查询的编码
		 * 该方法只能对请求实体内容的数据编码起作用。POST提交的数据在实体内容中,所以该方法对POST方法有效!
		 * GET方法的参数放在URI后面,所以对GET方式无效!!!
		 */
		request.setCharacterEncoding("utf-8"); // 默认按照iso-8859-1 字节转字符解码
		
	/*	System.out.println("GET方式");
		//接收GET方式提交的参数
		String value = request.getQueryString();
		System.out.println(value);*/
		
		
		/**
		 * 统一方便地获取请求参数的方法
		 */
		System.out.println(request.getMethod()+"方式");
		//getParameter(name): 根据参数名得到参数值(只能获取一个值的参数)
		String name = request.getParameter("name");
		
		/**
		 * 手动重新解码(iso-8859-1 字符串-> utf-8 字符串)
		 */
		/*if("GET".equals(request.getMethod())){
			name = new String(name.getBytes("iso-8859-1"),"utf-8");
		}*/
		
		String password = request.getParameter("password");
		
		/*if("GET".equals(request.getMethod())){
			password = new String(password.getBytes("iso-8859-1"),"utf-8");
		}*/
		
		System.out.println(name+"="+password);
		
		System.out.println("=============================");
		Enumeration<String> enums = request.getParameterNames();
		while( enums.hasMoreElements() ){
			String paramName = enums.nextElement();
			//String paramValue = request.getParameter(paramName);
			//System.out.println(paramName+"="+paramValue);
			//如果参数名是hobit多选项,则调用getParameterValues
			if("hobit".equals(paramName)){
				/**
				 * getParameterValues(name): 根据参数名获取参数值(可以获取多个值的同名参数)
				 */
				System.out.println(paramName+":");
				String[] hobits = request.getParameterValues("hobit");
				for(String h: hobits){
				/*	if("GET".equals(request.getMethod())){
						h = new String(h.getBytes("iso-8859-1"),"utf-8");
					}*/
					System.out.print(h+",");
				}
				System.out.println();
				//如果不是hobit,则调用getParameter
			}else{
				String paramValue = request.getParameter(paramName);
				/*
				if("GET".equals(request.getMethod())){
					paramValue = new String(paramValue.getBytes("iso-8859-1"),"utf-8");
				}*/
				
				System.out.println(paramName+"="+paramValue);
			}
		}
	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*System.out.println("POST方式");
		InputStream in = request.getInputStream();
		byte[] buf = new byte[1024];
		int len = 0;
		while(  (len=in.read(buf))!=-1 ){
			System.out.println(new String(buf,0,len));
		}*/
		
		/**
		 * 统一方便地获取请求参数的方法
		 */
		/*System.out.println("POST方式");
		//根据参数名得到参数值
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		System.out.println(name+"="+password);
		
		System.out.println("=============================");
		Enumeration<String> enums = request.getParameterNames();
		while( enums.hasMoreElements() ){
			String paramName = enums.nextElement();
			String paramValue = request.getParameter(paramName);
			System.out.println(paramName+"="+paramValue);
		}*/
		
		//一定调用doGet方式
		this.doGet(request, response);
	}

}

9 Http响应

/*
HTTP/1.1 200 OK             --响应行
Server: Apache-Coyote/1.1   --响应头(key-vaule)
Content-Length: 24 
Date: Fri, 30 Jan 2015 01:54:57 GMT
							--一个空行
this is hello servlet!!!    --实体内容

9.1 响应行
	#http协议版本
	#状态码: 服务器处理请求的结果(状态)
		常见的状态:
			200 :  表示请求处理完成并完美返回
			302:   表示请求需要进一步细化。
			404:   表示客户访问的资源找不到。
			500:   表示服务器的资源发送错误。(服务器内部错误)
	#状态描述
	
9.2 常见的响应头
	Location: http://www.it315.org/index.jsp   --表示重定向的地址,该头和302的状态码一起使用。
	Server:apache tomcat                 	   --表示服务器的类型
	Content-Encoding: gzip                 	   --表示服务器发送给浏览器的数据压缩类型
	Content-Length: 80                         --表示服务器发送给浏览器的数据长度
	Content-Language: zh-cn                    --表示服务器支持的语言
	Content-Type: text/html; charset=GB2312    --表示服务器发送给浏览器的数据类型及内容编码
	Last-Modified: Tue, 11 Jul 2000 18:23:51 GMT  --表示服务器资源的最后修改时间
	Refresh: 1;url=http://www.it315.org        --表示定时刷新
	Content-Disposition: attachment; filename=aaa.zip --表示告诉浏览器以下载方式打开资源(下载文件时用到)
	Transfer-Encoding: chunked
	Set-Cookie:SS=Q0=5Lb_nQ; path=/search      --表示服务器发送给浏览器的cookie信息(会话管理用到)
	Expires: -1                                --表示通知浏览器不进行缓存
	Cache-Control: no-cache
	Pragma: no-cache
	Connection: close/Keep-Alive               --表示服务器和浏览器的连接状态。close:关闭连接 keep-alive:保存连接

9.3 HttpServletResponse对象
	HttpServletResponse对象修改响应信息:

		响应行: 
				response.setStatus()  设置状态码
		响应头: 
				response.setHeader("name","value")  设置响应头
		实体内容:
				response.getWriter().writer();   发送字符实体内容
				response.getOutputStream().writer()  发送字节实体内容 

9.4 案例- 请求重定向(Location)

9.5 案例- 定时刷新(refresh)

9.6 案例-content-Type作用
*/
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 ResponseDemo1 extends HttpServlet {

	/**
	 * 1)tomcat服务器把请求信息封装到HttpServletRequest对象,且把响应信息封装到HttpServletResponse
	 * 2)tomcat服务器调用doGet方法,传入request,和response对象
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 3)通过response对象改变响应信息
		 */
		/**
		 * 3.1 响应行
		 */
		//response.setStatus(404);//修改状态码
		//response.sendError(404); // 发送404的状态码+404的错误页面
		
		/**
		 * 3.2 响应头
		 */
		response.setHeader("server", "JBoss");
		
		
		/**
		 * 3.3 实体内容(浏览器直接能够看到的内容就是实体内容)
		 */
		//response.getWriter().write("01.hello world"); //字符内容。
		response.getOutputStream().write("02.hello world".getBytes());//字节内容
		 

	}
	
	/**
	 * 4)tomcat服务器把response对象的内容转换成响应格式内容,再发送给浏览器解析。
	 */

}
案例- 请求重定向
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 ResponseDemo2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 需求: 跳转到adv.html
		 * 使用请求重定向: 发送一个302状态码+location的响应头
		 */
		/*response.setStatus(302);//发送一个302状态码
		response.setHeader("location", "/day09/adv.html"); //location的响应头
*/		
		
		//请求重定向简化写法
		response.sendRedirect("/day09/adv.html");
	}

}
案例- 定时刷新
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 ResponseDemo3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 定时刷新
		 * 原理:浏览器认识refresh头,得到refresh头之后重新请求当前资源
		 */
		//response.setHeader("refresh", "1"); //每隔1秒刷新次页面
		
		/**
		 * 隔n秒之后跳转另外的资源
		 */
		response.setHeader("refresh", "3;url=/day09/adv.html");//隔3秒之后跳转到adv.html
	}

}
案例- content-Type作用
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 案例- content-Type作用
 */
public class ResponseDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 设置响应实体内容编码
		 */
		response.setCharacterEncoding("utf-8");
		
		/**
		 * 1. 服务器发送给浏览器的数据类型和内容编码
		 */
		//response.setHeader("content-type", "text/html");
		response.setContentType("text/html;charset=utf-8");//和上面代码等价。推荐使用此方法
		//response.setContentType("text/xml");
		//response.setContentType("image/jpg");

		
		//response.getWriter().write("<html><head><title>this is tilte</title></head><body>中国</body></html>"); //需要提前指定码表
		response.getOutputStream().write("<html><head><title>this is tilte</title></head><body>中国</body></html>".getBytes("utf-8"));
		
		
		/*File file = new File("e:/mm.jpg");
		*//**
		 * 设置以下载方式打开文件
		 *//*
		response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
		*//**
		 * 下载图片
		 *//*
		*//**
		 * 发送图片
		 *//*
		FileInputStream in = new FileInputStream(file);
		byte[] buf = new byte[1024];
		int len = 0;
		
		//把图片内容写出到浏览器
		while( (len=in.read(buf))!=-1 ){
			response.getOutputStream().write(buf, 0, len);
		}*/
	}

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值