使用Servlet接受服务器请求信息

HTTP请求示例

HttpServletRequest对象主要用于获取由客户端发送过来的请求头、参数、文件、数据等。Servlet存在的主要目的就是处理请求。Servlet规范中对此对象进行了增强,使其还可以与Web应用程序交互

GET/POST提交方法

  - 浏览器向Web服务器发送HTTP请求

  - 用户在网页上点击一个超连接

  - 用户提交在网页上填写好的表单

  - 用户在浏览器地址栏中输入URL地址并回车

  - 默认情况下都是使用HTTP协议的GET方法提交请求

  - 使用不同的HTTP请求定制浏览器行为

GET/POST提交方法区别

特征

GET方法

POST方法

提交数据类型

文本

文本、二进制文本

提交数据长度

不超过255个字符

没有限制

提交数据可见性

作为URL地址的一部分显示在浏览器地址栏

作为请求的消息体,不可见

提交数据缓存

缓存在浏览器URL历史状态中

不会被浏览器缓存

  - 请求一个静态页面或图形文件时使用GET方法,因为仅仅需要发送文件名;

  - 发送大数据的时候,使用POST方法;

  - 上传文件时,使用POST方法;

  - 发送用户名、密码或其他保密信息的时候使用POST方

HTTP请求方法与HttpServlet方法对应关系

HTTP请求方法类型

HttpServlet处理方法

GET

doGet()

HEAD

doHead()

POST

doPost()

PUT

doPut()

DELETE

doDelete()

OPTIONS

doOptions()

TRACE

doTrace()

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//your code
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//your code
}

  根据生命周期,这些方法的调用过程

    - 容器调用service(ServletRequest,ServletResponse)方法;

    - service(ServletRequest,ServletResponse)该方法再调用同一个Servlet类中的service(ServletRequest,ServletResponse)方法。

    - service(ServletRequest,ServletResponse)方法将分析HTTP请求,找到请求方法类型然后调用相应的处理方法

提示:如果在自定义的Servlet类中覆盖service方法,doXXX方法将不会自动调用。在绝大多数的情况下,我们只需要关心GET和POST方法就行了。

获取HTTP协议请求行

  - getMethod():获取HTTP的请求方法,例如GET、POST等

  - getRequestURI():获取请求的URI资源

- getRequestURL():获取请求的URL,包含协议名、服务器名或IP、端口号和请求资源但不包括查询字符串参数

- getQueryString():获取请求URL后面的查询字符串

- getProtocol():获取HTTP的协议名和版本号

- getContextPath():获取请求URI资源的上下文路径

- getServletPath():获取Servlet的映射路径

package test;

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 Test
*/
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.err.println("请求的方法:" + request.getMethod());
System.err.println("请求的URL:" + request.getRequestURI());
System.err.println("请求的URL:" + request.getRequestURL());
System.err.println("请求的查询方法:" + request.getQueryString());
System.err.println("请求的协议:" + request.getProtocol());
System.err.println("请求的上下文:" + request.getContextPath());
System.err.println("请求的Servlet的映射路径:" + request.getServletPath());
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }

HttpServletRequest访问HTTP请求行

获取HTTP协议请求头

  HTTP请求头用于告诉服务器客户端使用什么软件以及客户端想要服务器如何返回请求的信息

  HttpServletRequest对象的如下方法访问

    - getHeader(name):返回指定的请求头的值

    - getHeaders(name) :返回一个Enumeration(枚举)包含请求头中的所有值

- getHeaderNames():特定请求中接受到的所有请求头的名称

- getIntHeader(name):获取特定请求头的值,并将其转化为int类型

- getDateHeader(name):获取特定请求头的值,并将其转化为Date类型

获取所有请求头

package test;

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 Test
*/
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
@SuppressWarnings("rawtypes")
Enumeration $enum = request.getHeaderNames();
//通过遍历取出请求头信息并打印
while ($enum.hasMoreElements()) {
String headerName = (String) $enum.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName+":"+headerValue);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }

返回浏览器发送的所有请求头

检索浏览器

//获取请求头信息
String userAgent = request.getHeader("User-Agent");
// 判断正在使用的浏览器
if((userAgent != null) && (userAgent.indexOf("MSIE")!=-1) ){
  // 您正在使用MicroSoft IE浏览器
}else if((userAgent != null) && (userAgent.indexOf("Firefox")!=-1)){
  // 您正在使用FireFox火狐浏览器
}

获取请求消息体

  - 消息体可以是普通文本也可以是二进制数据

  - HttpServletRequest对象可以使用通用的方法来获取表单数据

获取表单数据

HttpServletRequest对象用下列方法以访问请求参数

- getParameter(parameterName):获取表单参数的值,参数名区分大小写,与HTML表单中出现的参数名一致,GET请求还是POST请求都可以采用相同的方式

- getParameterValues(parameterName):获取同一个参数名的多个参数值,返回字符串数组对象

- getParameterNames():以Enumeration (枚举)的方式返回请求中所有的表单参数名列表

<--HTML文件--!>
<form action="Register" method="post">
用户名:<input type="text" name="userName" />
<br/>
密码:<input type="password" name="passWord" />
<br/>
学历:<select name="education">
<option>小学</option>
<option>初中</option>
<option>高中</option>
<option>大专</option>
<option>本科</option>
</select>
<br/>
性别:<input type="radio" name="gender" id="man" checked="checked" value="男"/>
<label for="man">男</label>
<input type="radio" name="gender" id="woman" value="女"/>
<label for="woman">女</label>
<br/>
爱好:<input type="checkbox" name="hobby" id="PE" value="体育"/>
<label for="PE">体育</label>
<input type="checkbox" name="hobby" id="art" value="美术"/>
<label for="art">美术</label>
<input type="checkbox" name="hobby" id="music" value="音乐"/>
<label for="music">音乐</label>
<br/>
<button>提交</button>
</form>

表单提交信息

//Java代码,提交是post,所以该代码重写doPost()方法
//设置字符编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取表单信息
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
String education = request.getParameter("education");
String gender = request.getParameter("gender");
String[] hobbys = request.getParameterValues("hobby");
//打印获取的信息
System.err.println("userName:"+userName);
System.err.println("passWord:"+passWord);
System.err.println("education:"+education);
System.err.println("gender:"+gender);
System.err.print("hobby:");
if(hobbys!=null){
for(String hobby:hobbys){
System.err.print(hobby+"/");
}
}

表单信息打印结果

JavaWeb总结(五)的更多相关文章

  1. JavaWeb 后端 <五> 之 JSP 学习笔记

    一.JSP简介 1.也是SUN公司推出的开发动态web资源的技术,属于JavaEE技术之一.由于原理上是Servlet, 所以JSP/Servlet在一起. 二.HTML.Servlet和JSP 1. ...

  2. JavaWeb(五)之JSTL标签库

    前言 前面介绍了EL表达式,其实EL表达式基本上是和JSTL核心标签库搭配一起使用才能发挥效果的.接下来让我们一起来认识一下吧! 在之前我们学过在JSP页面上为了不使用脚本,所以我们有了JSP内置的行 ...

  3. JavaWeb学习 (五)————Servlet(一)

    一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...

  4. javaweb(十五)——JSP基础语法

    任何语言都有自己的语法,JAVA中有,JSP虽然是在JAVA上的一种应用,但是依然有其自己扩充的语法,而且在JSP中,所有的JAVA语句都可以使用. 一.JSP模版元素 JSP页面中的HTML内容称之 ...

  5. JavaWeb【五、内置对象】

    简介 Web容器创建的一组对象,不用new即可使用. 共有9种,out.request.response.session.application,五种比较常用,page.pageContent.exc ...

  6. javaweb实验五

    product类: package com.lab;public class Product { private int id;                // 商品编号    private S ...

  7. JavaWeb总结(五)—Cookie

    一.会话 1.提出问题 HTTP协议是一种无状态的协议.Web服务器本身不能识别哪些请求是同一浏览器发出的,浏览器的每一次请求都是孤立的.即使HTTP1.1支持持续连接,但当用户有一段时间没有提交请求 ...

  8. JavaWeb(五)Filter过滤器

    Filter过滤器 Fileter介绍 Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Serv ...

  9. javaweb笔记五

    JSP:java server page服务器脚本语言.(脚本===插件),是一种在html代码中,嵌入java代码的方式.解决servlet产生动态页面缺陷而产生的一门技术.js:客户端脚本语言js ...

  10. JavaWeb中五种转发方式(转)

    今天本来是想找一下在jsp中实现转发的方式的,无意中看到了一篇文章,然后稍微综合了把服务器端的转发也包括在内.   1. RequestDispatcher.forward() 是在服务器端起作用,当 ...

随机推荐

  1. LeetCode题解之Number of 1 Bits

    1.题目描述 2.问题分析 使用C++ 标准库的 bitset 类,将整数转换为 二进制,然后将二进制表示转换为字符串,统计字符串中 1 的个数即可. 3.代码 int hammingWeight(u ...

  2. 如何监视和更新 Azure 中的 Linux 虚拟机

    为确保 Azure 中的虚拟机 (VM) 正常运行,可以查看启动诊断.性能指标,并管理程序包更新. 本教程介绍如何执行下列操作: 在 VM 上启用启动诊断 查看启动诊断 在 VM 上启用诊断扩展 基于 ...

  3. Oracle EBS 验证应收是否等于加税

    --To validate whether a transaction's REC is equal to its REV plus TAX or not --验证应收是否等于收入加税 SELECT ...

  4. .Net Core+Vue.js+ElementUI 实现前后端分离

    .Net Core+Vue.js+ElementUI 实现前后端分离 Tags: Vue 架构 前端采用:Vue.js.Element-UI.axios 后端采用:.Net Core Mvc 本项目是 ...

  5. The operation names in the portType match the method names in the SEI or Web service implementation class.

    The Endpoint validation failed to validate due to the following errors: :: Invalid Endpoint Interfac ...

  6. C++实现一个Vector3空间向量类(转)

    转自:http://www.2cto.com/kf/201311/260139.html ector2,3,4类在DirectX中都有现成的可以调用,不过要实现其中的功能其实也不难,也都是一些简单的数 ...

  7. php各种主流框架的优缺点

    ThinkPHP ThinkPHP(FCS)是一个轻量级的中型框架,是从Java的Struts结构移植过来的中文PHP开发框架.它使用面向对象的开发结构和MVC模式,并且模拟实现了Struts的标签库 ...

  8. 通过 Chrome 调试运行在 IOS-safari 上的页面

    本文重点讨论如何在 Windows 系统中通过chrome 浏览器调试运行在 iPhone Safari 浏览器中的网页.如果你有一台 iMac/MacBook,可忽略该文档.iMac 环境下,直接通 ...

  9. 【整理】close 和 shutdown 的原理

    http://stackoverflow.com/questions/14740852/linux-socket-close-vs-shutdown shutdown(sd, SHUT_WR)  发送 ...

  10. CR与LF

    CR与LF CR(carriage return),中文名称"回车":LF(line feed),中文名称"换行".无论是初学编程的小白还是入行十年的资深,总会 ...