request常用方法

import java.io.IOException;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  //HttpServletRequest的常用方法 http请求中的所有信息都封装在这个对象中
public class RequestDemo1 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  // 访问路径http://localhost:8080/day06/servlet/RequestDemo1?name=aaa  // /day06/servlet/RequestDemo1  System.out.println(request.getRequestURI());  // http://localhost:8080/day06/servlet/RequestDemo1  System.out.println(request.getRequestURL());  // name=aaa  System.out.println(request.getQueryString());  // 获取客户端ip  System.out.println(request.getRemoteAddr());  // 获取客户端主机名,这个主机名没有在DNS上注册的话还是获取ip  System.out.println(request.getRemoteHost());  // 获取客户端浏览器的端口  System.out.println(request.getRemotePort());  // 获取web服务器的ip  System.out.println(request.getLocalAddr());  // 获取web服务器的主机名,没有在DNS上注册还是获取ip  System.out.println(request.getLocalName());  // 获取请求方式  System.out.println(request.getMethod());  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  

request获取请求头和请求数据

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Map;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  import com.sun.org.apache.commons.beanutils.BeanUtils;
//HttpServletRequest获取请求头和请求数据
//请求数据一半来说要先检查再使用,检查非空和不是空格  public class RequestDemo2 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  System.out.println("---------获取请求数据方式1-------------");  // 获取指定的请求数据  String value = request.getParameter("username");  if (value != null && !value.trim().equals("")) {  System.out.println(value);  }  System.out.println("---------获取请求数据方式2-------------");  // 获取所有的请求数据  Enumeration e = request.getParameterNames();  while (e.hasMoreElements()) {  String paramName = (String) e.nextElement();  String value2 = request.getParameter(paramName);  System.out.println(paramName + "=" + value2);  }  System.out.println("---------获取请求数据方式3-------------");  // 获取所有的请求数据,同名的只能获取一次,就是第一次  String[] values = request.getParameterValues("username");  for (int i = 0; values != null && i < values.length; i++) {  System.out.println(values[i]);  }  System.out.println("---------获取请求数据方式4-------------");  // 这个特别实用,框架的模型驱动,这个Map的value肯定是String数组类型,因为有同名的请求数据  // 实际开发中是不会 request.getParameter("username");用这种方式的,都是要创建一个model的  Map<String, String[]> map = request.getParameterMap();  User user = new User();  try {  // 用map中的数据填充bean  BeanUtils.populate(user, map);  } catch (IllegalAccessException e1) {  e1.printStackTrace();  } catch (InvocationTargetException e1) {  e1.printStackTrace();  }  System.out.println(user.getPassword());  System.out.println("---------获取请求数据方式5-------------");  // request.getInputStream();是上传文件的时候获取数据的方式  // 普通数据是获取不到的  InputStream in = request.getInputStream();  int len = 0;  byte[] buffer = new byte[1024];  while ((len = in.read(buffer)) > 0) {  System.out.println(new String(buffer, 0, len));  }  }  // 获取请求头  private void test1(HttpServletRequest request) {  System.out.println("---------获取请求头方式1-------------");  // 拿到指定的请求头  System.out.println(request.getHeader("cache-control"));  System.out.println("---------获取请求头方式2-------------");  // 拿到所有指定的请求头  Enumeration e = request.getHeaders("cache-control");  while (e.hasMoreElements()) {  String headValue = (String) e.nextElement();  System.out.println(headValue);  }  System.out.println("---------获取请求头方式3-------------");  // 拿到所有请求头  Enumeration e1 = request.getHeaderNames();  while (e1.hasMoreElements()) {  String headerName = (String) e1.nextElement();  String headValue = request.getHeader(headerName);  System.out.println(headerName + "=" + headValue);  }  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  
public class User {  private String[] username;  public String[] getUsername() {  return username;  }  public void setUsername(String[] username) {  this.username = username;  }  public String getPassword() {  return password;  }  public void setPassword(String password) {  this.password = password;  }  private String password;
}  

前台页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>  <head>  <title>给RequestDemo2发送请求数据</title>  </head>  <body>  <!-- 浏览器可以通过两种方式向服务器发送请求数据      超链接方式后面跟了中文要经过url编码后再提交 -->  <a href="/day06/servlet/RequestDemo2?username=xxx">点点</a><br/>  <form action="/day06/servlet/RequestDemo2" method="post">  用户名1:<input type="text" name="username"/><br/>  用户名2:<input type="text" name="username"/><br/>  密码:<input type="password" name="password"/><br/>  <input type="submit" value="提交"/>  </form>  </body>
</html>  

注:此程序还需用到commons-beanutils-1.9.0.jar和commons-logging-1.1.3.jar这两个jar包。

通过表单提交用户数据和用request获取表单提交数据

表单页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>收集用户数据,向RequestDemo3提交数据</title>
</head>  <body>  <form action="/day06/servlet/RequestDemo3" method="post">  用户名:<input type="text" name="username" />  <br />   密码:<input type="password" name="password" />  <br />   性别:  <input type="radio" name="gender" value="male" />男   <input type="radio" name="gender" value="female" />女  <br />   所在地:   <select name="city">  <option value="beijing">北京</option>  <option value="shanghai">上海</option>  <option value="shenzhen">深圳</option>  </select>  <br />   爱好:   <input type="checkbox" name="likes" value="sing" />唱歌   <input type="checkbox" name="likes" value="dance" />跳舞  <input type="checkbox" name="likes" value="basketball" />篮球  <input type="checkbox" name="likes" value="football" />足球  <br />   简介:  <textarea rows="6" cols="60" name="description"></textarea>  <br />   <input type="hidden" name="id" value="123456"/>  <input type="submit" value="提交" />  </form>
</body>
</html>  
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  import org.apache.commons.beanutils.BeanUtils;  //获取表单提交数据
public class RequestDemo3 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  test2(request);  }  // 实际开发项目时采用的model方式  private void test2(HttpServletRequest request) {  User user = new User();  Map<String, String[]> map = request.getParameterMap();  try {  BeanUtils.populate(user, map);  System.out.println(user.getUsername());  System.out.println(user.getPassword());  System.out.println(user.getGender());  System.out.println(user.getCity());  String[] likes = user.getLikes();  for (int i = 0; likes != null && i < likes.length; i++) {  System.out.println(likes[i]);  }  System.out.println(user.getDescription());  System.out.println(user.getId());  } catch (IllegalAccessException e) {  e.printStackTrace();  } catch (InvocationTargetException e) {  e.printStackTrace();  }  }  // 直接获取值得方法  private void test1(HttpServletRequest request) {  String username = request.getParameter("username");  System.out.println(username);  String password = request.getParameter("password");  System.out.println(password);  String gender = request.getParameter("gender");  System.out.println(gender);  String city = request.getParameter("city");  System.out.println(city);  String[] likes = request.getParameterValues("likes");  for (int i = 0; likes != null && i < likes.length; i++) {  System.out.println(likes[i]);  }  String description = request.getParameter("description");  System.out.println(description);  String id = request.getParameter("id");  System.out.println(id);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  
public class User {  private String username;  private String password;  private String gender;  private String city;  private String[] likes;  private String description;  private String id;  public String getUsername() {  return username;  }  public void setUsername(String username) {  this.username = username;  }  public String getPassword() {  return password;  }  public void setPassword(String password) {  this.password = password;  }  public String getGender() {  return gender;  }  public void setGender(String gender) {  this.gender = gender;  }  public String getCity() {  return city;  }  public void setCity(String city) {  this.city = city;  }  public String[] getLikes() {  return likes;  }  public void setLikes(String[] likes) {  this.likes = likes;  }  public String getDescription() {  return description;  }  public void setDescription(String description) {  this.description = description;  }  public String getId() {  return id;  }  public void setId(String id) {  this.id = id;  }
}  

request乱码问题(数据提交以post方式和get方式)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>向RequestDemo4提交中文数据,解决乱码问题</title>
</head>  <body>  <!--post方式提交-->  <form action="/day06/servlet/RequestDemo4" method="post">  用户名:<input type="text" name="username" /> <input type="submit"  value="提交" />  </form>  <!--get方式提交-->  <form action="/day06/servlet/RequestDemo4" method="get">  用户名:<input type="text" name="username" /> <input type="submit"  value="提交" />  </form>  <!-- 超链接方式提交的中文,服务器想不乱码,也只能手工处理(貌似超链接提交要经过url编码)-->  <a href="/day06/servlet/RequestDemo4?username=中国">单击</a>
</body>
</html>  
import java.io.IOException;
import java.io.UnsupportedEncodingException;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//request乱码解决,除了下面的解决方式,还可以改服务器配置,但不要用那种方式
public class RequestDemo4 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  test2(request);  }  /* * get方式提交:由于get方式提交request.setCharacterEncoding(arg0);无效,所以乱码只能手工处理,拿到乱码的数据后 * ,按照ISO8859-1进行解码,然后按照UTF-8进行编码。 */  private void test2(HttpServletRequest request)  throws UnsupportedEncodingException {  String username = request.getParameter("username");  // get方式解决乱码,先把乱码按照原来的编码解码,返回数据的表示数字,然后按照想要的码表编码  username = new String(username.getBytes("ISO8859-1"), "UTF-8");  System.out.println(username);  }  /* * post方式提交:浏览器以当前页面的码表提交数据,当前页面的码表是程序员写程序时自己指定的。数据提交到request里面去, * 但是当request往外面取数据时用的是ISO8859 * -1码表,就会产生乱码所以要在取数据之前指定request的码表。request.setCharacterEncoding * (arg0);只对post方式起作用 */  private void test1(HttpServletRequest request)  throws UnsupportedEncodingException {  // 设置request码表  request.setCharacterEncoding("UTF-8");  String username = request.getParameter("username");  System.out.println(username);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  

request实现请求转发以及request域带数据给转发资源

MVC思想:

M model javabean
V view(jsp)
C Cotroller(servlet)
servlet把数据提交,javabean封装数据,然后jsp从javabean取出数据。

请求转发特点:
1. 客户端只发一次请求,而服务器有多个资源调用
2. 浏览器地址栏没有变化

import java.io.IOException;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  //request请求转发,以及使用request域把数据带给转发资源,实际开发中MVC设计模式,都是用request域把数据带给jsp的
public class RequestDemo5 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  String date = "aaaaaa";  // 将数据存到request域中  request.setAttribute("date", date);  // 请求转发,servletContext也可以实现请求转发  request.getRequestDispatcher("/message.jsp").forward(request, response);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>  <head>  </head>  <body>  ${date}   <!-- 实际开发中 是不允许jsp页面中出现java代码的,都是用自定义标签和EL表达式替换java代码 -->  <%  //request的getParameter方法得到的是请求数据,getAttribute方法得到的是request域里的数据  String message = (String)request.getAttribute("date");  out.write(message);  %>  </body>
</html>  

request请求转发forward方法的细节

import java.io.IOException;
import java.io.PrintWriter;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  //request请求转发时forward方法的细节,客户端只发一次请求,而服务器端有多个资源调用,地址栏不会发生变化
/* *  1.  forward方法用于将请求转发到RequestDispatcher对象封装的资源, *  2.  如果在调用forward方法之前,在servlet程序中写入的部分内容已经被真正的传送到了客户端(调用了flush或者close方法), *      forward方法将抛出IllegalStateException异常 *  3.  如果在调用forward方法之前向Servlet引擎的缓冲区(response)中写入了内容, *      只要写入到缓冲区的内容还没有被真正输出到客户端,forward方法就可以被正常执行, *      原来写入到缓冲区中的内容将被清空,但是,以写入到HttpServletResponse对象中的响应头字段信息保持有效 */
public class RequestDemo6 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  test3(request, response);  }  //细节3  private void test3(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException {  String date = "aaaaaa";  PrintWriter print = response.getWriter();  print.write(date);  //以下代码不会出现问题,但是上面的date是不能在页面输出的,页面中只能看见index.jsp的内容  request.getRequestDispatcher("/index.jsp").forward(request, response);  }  //细节2,转发了好多次,避免这个问题,forward之后要return  private void test2(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  String date = "aaaaaa";  if(true) {  //几百行代码  request.getRequestDispatcher("/index.jsp").forward(request, response);  //return;   //跳转之后一定要记得return  }  //几百行代码  // 以下代码将出现:java.lang.IllegalStateException: Cannot forward after response has been committed  //上面已经转发一次了  request.getRequestDispatcher("/index.jsp").forward(request, response);  }  //细节2  private void test1(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException {  String date = "aaaaaa";  PrintWriter print = response.getWriter();  print.write(date);  print.flush();//print.close();  // 以下代码将出现:java.lang.IllegalStateException: Cannot forward after response has been committed  request.getRequestDispatcher("/index.jsp").forward(request, response);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  

request使用RequestDispatcher的include方法实现页面包含

import java.io.IOException;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  //request使用RequestDispatcher的include方法实现页面包含
public class RequestDemo7 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  request.getRequestDispatcher("/head.jsp").include(request, response);  response.getWriter().write("aaaaaa");  request.getRequestDispatcher("/foot.jsp").include(request, response);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }
}  

工程中各类地址的写法

import java.io.IOException;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//web工程中各类地址的写法
//写地址最好以/开头,如果是给服务器用的,/代表当前的web应用;如果地址是给浏览器用的,/代表网站(webapps文件夹)
//相对路径的话单独问题单独解决  public class ServletUrlDemo extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  // 1.给服务器用  request.getRequestDispatcher("/").forward(request, response);  // 2.给浏览器用,让浏览器重定向  response.sendRedirect("/");  // 3.给服务器用  this.getServletContext().getRealPath("/");  // 4.给服务器用  this.getServletContext().getResourceAsStream("/");  // 5.  /* * //给浏览器用的 <a href="/">点击</a> //给浏览器用的 <form action="/"> *  * </form> */  // 要想获取url资源用/这个斜杠,获取硬盘上的资源,用\\斜杠  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  

request获取referer请求头实现防盗链

eg:有的资源你点出后会有广告,广告旁边是资源连接,有些人直接把资源连接发给别人,企图不看广告直接进入链接拿资源,为了防止盗链行为的发生,我们要检测用户访问url的情况来进行一系列措施。
需要实现的功能就是,当用户想要查看”机密文档”的时候,如果是直接输入机密文档的url,而不是广告的url,我们得先让他跳转到广告页面的url,看完广告后就可以让他看“机密文档”了。
模拟过程:用户输入机密文件的url(或者在其他网站),这时候进入Servlet,response的getHeader(“referer”)方法会得到来访地址,用此判断是否是从index.jsp网页的url来的,如果不是,跳入带广告的index.jsp,如果是就把机密文件的内容加载,然后显示给用户。

import java.io.IOException;  import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  //利用referer请求头实现防盗链
public class RequestDemo8 extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  // 获取请求是从哪里来的  String referer = request.getHeader("referer");  // 如果是直接输入的地址,或者不是从本网站访问的重定向到本网站的首页  if (referer == null || !referer.startsWith("http://localhost")) {  response.sendRedirect("/day06/index.jsp");  // 然后return,不要输出后面的内容了  return;  }  String date = "凤姐日记";  response.getWriter().write(date);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  doGet(request, response);  }  }  

方立勋_30天掌握JavaWeb_request相关推荐

  1. 方立勋_30天掌握JavaWeb_Servlet Filter(过滤器)未完

    Filter简介 Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片 ...

  2. 方立勋_30天掌握JavaWeb_自定义标签

    自定义标签主要用于移除Jsp页面中的java代码. 使用自定义标签移除jsp页面中的java代码,只需要完成以下两个步骤: 编写一个实现Tag接口的Java类(标签处理器类). 编写标签库描述符(tl ...

  3. 方立勋_30天掌握JavaWeb_JSP

    JSP运行原理 JSP全称是Java Server Pages,它和servle技术一样,都是SUN公司定义的一种用于开发动态web资源的技术. JSP这门技术的最大的特点在于,写jsp就像在写htm ...

  4. 方立勋_30天掌握JavaWeb_response

    response的outStream输出数据的问题 原因: 解决方法一: //程序以什么码表输出了,程序就一定要控制浏览器以什么码表打开 response.setHeader("Conten ...

  5. 方立勋_30天掌握JavaWeb_Servlet事件监听器

    监听器 监听器就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行. 监听器典型案例:监听wind ...

  6. 方立勋_30天掌握JavaWeb_自己编写jdbc框架、dbutils框架(未完)

    元数据:数据库.表.列的定义信息. Connection.getDatabaseMetaData() DataBaseMetaData对象 getURL():返回一个String类对象,代表数据库的U ...

  7. 方立勋_30天掌握JavaWeb_JDBC、连接池、JNDI(三)

    使用数据库连接池优化程序性能 缺点:用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长.假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大的 ...

  8. 方立勋_30天掌握JavaWeb_JDBC、存储过程、事务(二)

    使用JDBC处理大数据 在实际开发中,程序需要把大文本或二进制数据保存到数据库. 基本概念:大数据也称之为LOB(Large Objects),LOB又分为: clob和blob 1. clob用于存 ...

  9. 方立勋_30天掌握JavaWeb_jdbc实现客户关系管理(未完)

    搭建开发环境 1.1 导入开发包 jstl开发包 mysql驱动 beanutils开发包 log4j 1.2 建立程序包 cn.itcast.domain cn.itcast.dao cn.itca ...

最新文章

  1. 书评与访谈:the Scrumban [R]Evolution
  2. LR中的吞吐量与响应时间
  3. Singleton模式
  4. Python 2.7 学习笔记
  5. Golang 编程 — Go Micro 微服务框架
  6. 【学术相关】如何避免博士延期毕业?
  7. Boost:用成员函数测试bind <void>
  8. 百度代码规范 -- PHP
  9. 1号店案例html源码_手把手教一起写jQuery版mini源码,分析jQuery的优势
  10. 《设计模式详解》行为型模式 - 中介者模式
  11. 轻量级的实现复制文本到剪贴板功能的 js
  12. JSON3-翻译(不当之处,请指正)
  13. 【Java】 环境变量如何配置?
  14. php+log+iis,利用nxlog以syslog方式发送iis日志
  15. 【现代控制理论基础】二、线性控制系统的运动分析
  16. python小玩意——抠图换背景
  17. Javascript异常(exception)处理机制详解 JS、异常Error属性
  18. 服装网上销售“美国版”——互动+体验=成功
  19. Spring-setter注入和构造器注入
  20. css如何载入多种字体,在css中包含多种字体的正确方法

热门文章

  1. 用户用户组及权限管理
  2. 一个生产的shell脚本
  3. MyEclipse中快捷键
  4. 关于程序工作者的规划与思考
  5. mysqldump主要参数探究
  6. 4.1 [单选]两化融合中的两化是指 - 关于两化融合(主讲:凌捷)笔记
  7. Outlook通过RPC/RPC Over HTTPS访问Exchange邮箱
  8. 软件史上最伟大的十大程序员(图文)
  9. 一家企业为何使用多家公司的防火墙
  10. CT流程与CT图像的windowing操作(转载+整理)