第四天的学习内容:http://www.cnblogs.com/tobecrazy/p/3454860.html

Response对象

response对象主要是向客户端浏览器发送二进制数据,如输出Cookie、设置HTTP文件头信息等方面内容

response主要功能和方法

  • getWrite()   获得PrintWrite类的对象实例,实现向浏览器输出信息
  • addCookie() 在客户端计算机磁盘上创建出Cookie对象实例,在Cookie对象实例可以保存客户端信息特征,然后采用request对象的getCookies()方法获取客户机所有Cookie对象
  • addHeader() 添加HTTP头文件信息,将信息传送到客户浏览器中
  • containsHeader() 判断指定名字的文件头是否存在,返回布尔型true / false
  • setHeader() 设置指定名字HTTP头文件的值,若该值存在则覆盖
  • sendRedirect() 重定向到由参数targetURL所指示的目标JSP页面或Servlet程序,不能向客户端输出信息
  • setContentType() 在相应中可以设置内容的文档数据类型和格式
  • setBufferSize() 设置Web容器的缓冲区大小,配合getBufferSize()方法返回该缓冲器信息

利用response对象实现向客户机种写入Cookie信息

Cookie或称Cookies,是指Web应用系统为了辨别访问者身份而存储在客户机中的一个文本文件,其中包含特定数据,比如登陆邮箱:

可以把用户名和密码放在客户机Cookie中,下次访问不需要再输入用户名密码

读取Cookie文件信息,使用Cookie类中的getName()和getValue()返回客户端的某一个特定Cookie对象名所对应的值。而利用response对象addCookie(cookie data )方法可以写入Cookie对象中所包装的数据。

实例:在系统首页中添加读写Cookie信息

在index jsp页面中添加如下代码

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <%@page import="java.util.Date" %>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. %>
  7.  
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <html>
  10. <head>
  11. <base href="<%=basePath%>">
  12.  
  13. <title>My JSP add Cookie information </title>
  14. <meta http-equiv="pragma" content="no-cache">
  15. <meta http-equiv="cache-control" content="no-cache">
  16. <meta http-equiv="expires" content="0">
  17. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  18. <meta http-equiv="description" content="This is my page">
  19. <!--
  20. <link rel="stylesheet" type="text/css" href="styles.css">
  21. -->
  22. </head>
  23.  
  24. <body>
  25. <%! String lastAccessTime=null; //the last time view this web site
  26. String nowAccessTime=null;
  27. Cookie mycookie=null;
  28. Cookie[] cookies=null;
  29. Date now=null;
  30. %>
  31. <%
  32. cookies=request.getCookies(); // use request class getCookie method to get cookies if there is no cookie info then add new
  33. now=new Date();
  34. if(cookies==null)
  35. {
  36. lastAccessTime=(now.getYear()+1900+"Year"+now.getMonth()+"Month"+now.getDay()+"Day"+now.getHours()+"Hour"+now.getMinutes()+"Minute"+now.getSeconds()+"Second");
  37. mycookie=new Cookie("lastAccessTime",lastAccessTime);
  38. mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
  39. response.addCookie(mycookie);
  40. }
  41. else
  42. for(int index=0;index<cookies.length;index++)
  43. {
  44. if(cookies[index].getName().equals("lastAccessTime"))
  45. {
  46. lastAccessTime=cookies[index].getValue();
  47. nowAccessTime=(now.getYear()+1900+"Year "+now.getMonth()+" Month "+now.getDay()+" Day "+now.getHours()+" Hour "+now.getMinutes()+" Minute "+now.getSeconds()+" Second");
  48. mycookie=new Cookie("lastAccessTime",nowAccessTime);
  49. mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
  50. response.addCookie(mycookie);
  51. break;
  52. }
  53. }
  54. out.print("the last time your visit this system is "+lastAccessTime);
  55.  
  56. %>
  57. </body>
  58. </html>

首先用request的getCookie获取一下cookie,如果没有cookie信息,使用response的addCookie增加cookie信息

区分重定向与跳转方式的区别

  • 请求转发过程中客户端浏览器只向server端产生一次请求,而重定向是两次;
  • 请求转发时在浏览器的URL地址栏中的信息不会发生改变,仍然是原来的URL而重定向将会转向目标URL

使用HTTP请求转发:

使用转发由于只有一次请求,所以在一个页面的request.setAttribute 能够在跳转后的页面使用request.getAttribute获取其属性值

使用4个jsp页面和一个类文件

新建 login.jsp 设置登陆框,用户名密码。。。。。

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <%@ page isErrorPage="true" errorPage="error.jsp" %>
  3.  
  4. <%
  5. String path = request.getContextPath();
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7. %>
  8.  
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  10. <html>
  11. <head>
  12. <base href="<%=basePath%>">
  13.  
  14. <title>This is my first JSP page</title>
  15. <meta http-equiv="pragma" content="no-cache">
  16. <meta http-equiv="cache-control" content="no-cache">
  17. <meta http-equiv="expires" content="0">
  18. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  19. <meta http-equiv="description" content="This is my page">
  20. <!--
  21. <link rel="stylesheet" type="text/css" href="styles.css">
  22. -->
  23. </head>
  24.  
  25. <body>
  26.  
  27. <form method="post" action="response.jsp" >
  28. username:
  29. <input type="text" name="user" >
  30. <br>
  31. password:
  32. <input type="password" name="password">
  33. <br>
  34. userType:
  35. <select name="userType">
  36. <option value="user" >user</option>
  37. <option value="master"> master</option>
  38. </select>
  39.  
  40. <input type="submit" name="submit" />
  41. </form>
  42.  
  43. </body>
  44. </html>

新建response.jsp页面当用户名是:young并且密码是1234跳转到index.jsp否则跳转到error.jsp,引入userInfo类,使用其verifyID方法校验用户名密码

userinfo类代码:

  1. package mypackage;
  2.  
  3. public class userInfo {
  4.  
  5. /**
  6. * @param args
  7. * two parameters add get/set methods
  8. */
  9.  
  10. String userName=null;
  11. String passWord=null;
  12. public String getUserName() {
  13. return userName;
  14. }
  15. public void setUserName(String userName) {
  16. this.userName = userName;
  17. }
  18. public String getPassWord() {
  19. return passWord;
  20. }
  21. public void setPassWord(String passWord) {
  22. this.passWord = passWord;
  23. }
  24.  
  25. public boolean verifyID( )
  26. {
  27. if(userName.equals("young") && passWord.equals("1234"))
  28. {
  29. System.out.print("login successful\n");
  30. return true;
  31. }
  32. else
  33. {
  34. System.out.print("login failure\n");
  35. return false;
  36. }
  37.  
  38. }
  39.  
  40. }

代码如下:

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <jsp:useBean id="user" class="mypackage.userInfo" scope="session" ></jsp:useBean>
  3.  
  4. <%
  5. String path = request.getContextPath();
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7. %>
  8.  
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  10. <html>
  11. <head>
  12. <base href="<%=basePath%>">
  13.  
  14. <title>My JSP 'response.jsp' starting page</title>
  15.  
  16. <meta http-equiv="pragma" content="no-cache">
  17. <meta http-equiv="cache-control" content="no-cache">
  18. <meta http-equiv="expires" content="0">
  19. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  20. <meta http-equiv="description" content="This is my page">
  21. <!--
  22. <link rel="stylesheet" type="text/css" href="styles.css">
  23. -->
  24.  
  25. </head>
  26.  
  27. <body>
  28. <%!
  29. String targetPage=null;
  30. RequestDispatcher rd=null;
  31. %>
  32. <%
  33. user.setUserName(request.getParameter("user"));
  34. user.setPassWord(request.getParameter("password"));
  35.  
  36. if(user.verifyID())
  37. {
  38. request.setAttribute("userNameString",user.getUserName());
  39. targetPage="index.jsp";
  40. System.out.print(user.getUserName());
  41. }
  42. else
  43. {
  44. request.setAttribute("errorMSG","sorry,Login FAILED.\n");
  45. targetPage="error.jsp";
  46. }
  47. rd=request.getRequestDispatcher(targetPage);
  48. rd.forward(request,response);
  49. %>
  50. </body>
  51. </html>

新建error.jsp 这个页面会获取response.jsp传递过来的errorMSG

  1. <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6.  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  8. <html>
  9. <head>
  10. <base href="<%=basePath%>">
  11.  
  12. <title>My JSP 'error.jsp' starting page</title>
  13.  
  14. <meta http-equiv="pragma" content="no-cache">
  15. <meta http-equiv="cache-control" content="no-cache">
  16. <meta http-equiv="expires" content="0">
  17. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  18. <meta http-equiv="description" content="This is my page">
  19. <!--
  20. <link rel="stylesheet" type="text/css" href="styles.css">
  21. -->
  22.  
  23. </head>
  24.  
  25. <body>
  26. errorMSG<br>
  27. <%=request.getAttribute("errorMSG") %>
  28. </body>
  29. </html>

新建index.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <%@page import="java.util.Date" %>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. %>
  7.  
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <html>
  10. <head>
  11. <base href="<%=basePath%>">
  12.  
  13. <title>My JSP add Cookie information </title>
  14. <meta http-equiv="pragma" content="no-cache">
  15. <meta http-equiv="cache-control" content="no-cache">
  16. <meta http-equiv="expires" content="0">
  17. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  18. <meta http-equiv="description" content="This is my page">
  19. <!--
  20. <link rel="stylesheet" type="text/css" href="styles.css">
  21. -->
  22. </head>
  23.  
  24. <body>
  25. welcome <%=request.getAttribute("userNameString") %>
  26. <%! String lastAccessTime=null; //the last time view this web site
  27. String nowAccessTime=null;
  28. Cookie mycookie=null;
  29. Cookie[] cookies=null;
  30. Date now=null;
  31. %>
  32. <%
  33. cookies=request.getCookies(); // use request class getCookie method to get cookies if there is no cookie info then add new
  34. now=new Date();
  35. if(cookies==null)
  36. {
  37. lastAccessTime=(now.getYear()+1900+"Year"+now.getMonth()+"Month"+now.getDay()+"Day"+now.getHours()+"Hour"+now.getMinutes()+"Minute"+now.getSeconds()+"Second");
  38. mycookie=new Cookie("lastAccessTime",lastAccessTime);
  39. mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
  40. response.addCookie(mycookie);
  41. }
  42. else
  43. for(int index=0;index<cookies.length;index++)
  44. {
  45. if(cookies[index].getName().equals("lastAccessTime"))
  46. {
  47. lastAccessTime=cookies[index].getValue();
  48. nowAccessTime=(now.getYear()+1900+"Year "+now.getMonth()+" Month "+now.getDay()+" Day "+now.getHours()+" Hour "+now.getMinutes()+" Minute "+now.getSeconds()+" Second");
  49. mycookie=new Cookie("lastAccessTime",nowAccessTime);
  50. mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
  51. response.addCookie(mycookie);
  52. break;
  53. }
  54. }
  55. out.print("the last time your visit this system is "+lastAccessTime);
  56.  
  57. %>
  58. </body>
  59. </html>

登陆成功会显示: 可以看出,跳转后的页面URL仍然是跳转前的URL并未发生任何变化,由于只进行一次请求,所以request.setAttribute 和request.getAttribute能够正常工作

登陆失败:

而是用response.sendRedirect()会出现2次请求不能再是用request的对象包装和传递参数,可以使用session.setAttribute("NAME","VALUE")使用EL表达式语句${sesstionScope.userNameString}

从session会话对象中获取传递的参数,同时重定向后的URL为重定向页面的URL。

java web 学习 --第五天(Java三级考试)的更多相关文章

  1. java web学习总结(五) -------------------servlet开发(一)

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

  2. java web 学习 --第九天(Java三级考试)

    第八天的学习内容如下:http://www.cnblogs.com/tobecrazy/p/3468458.html Java servlet 技术 Servlet是使用java servlet应用程 ...

  3. java web 学习 --第一天(Java三级考试)

    1.Servlet servlet是运行在web server或 application server端的Java程序,主要用于在服务器端产生动态内容. servlet 在服务器端主要有以下作用 读取 ...

  4. Java Web学习(十一)Java过滤器

    一.引言 上一篇文章学习了java三大器的拦截器,拦截器主要是针对于action请求进行拦截处理的,那么对于requst的一些信息如果在调用前,想先进行过滤和处理,那么就要使用到第二个神器,也就是本文 ...

  5. java web 学习 --第二天(Java三级考试)

    第一天的学习在这http://www.cnblogs.com/tobecrazy/p/3444474.html 2.jsp 基础知识 Jsp页面中的Java脚本主要有3部分:声明(Declaratio ...

  6. java web 学习十五(jsp基础语法)

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

  7. java web 学习 --第八天(Java三级考试)

    第七天的学习内容:http://www.cnblogs.com/tobecrazy/p/3464231.html EL表达式 EL : Expression Language 使用EL表达式可以减少& ...

  8. Java Web学习(五)session、cookie、token

    文章更新时间:2020/09/14 一.引言 动态网页兴起后,会话管理变成开发者需要考虑的一个问题,由于HTTP请求是无状态的,为了区分每个用户,此时引入了会话标识(sessionId)的概念,但是存 ...

  9. [原创]java WEB学习笔记36:Java Bean 概述,及在JSP 中的使用,原理

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

随机推荐

  1. cas单点登录 SSO 的实现原理

    原文出处: cutesource   欢迎分享原创到伯乐头条 单点登录SSO(Single Sign On)说得简单点就是在一个多系统共存的环境下,用户在一处登录后,就不用在其他系统中登录,也就是用户 ...

  2. vtk第一个程序

    首先 设置环境变量 解决方案资源管理器 选中项目名字 而不是ALL_BUILD 选项卡 项目-属性 右侧 附加依赖项->编辑 kernel32.libuser32.libgdi32.libwin ...

  3. mysql 调用外部程序

    一.下载 lib_mysqludf_sys: 下载地址:https://github.com/mysqludf/repositories 二.配置与使用: 1.解压之后,已经有了我们需要的 lib_m ...

  4. map 与 unordered_map

    两者效率对比: #include <iostream> #include <string> #include <map> #include <unordere ...

  5. jupyter notebook + pyspark 环境搭建

    安装并启动jupyter 安装 Anaconda 后, 再安装 jupyter pip install jupyter 设置环境 ipython --ipython-dir= # override t ...

  6. nyoj 236拦截导弹 简单动归(java)

    C/C++: #include<stdio.h> int main() { // freopen("250.txt","r",stdin); ],b ...

  7. QT中Sqlite的使用

    环境: 静态编译过sqlite 步骤: 1.C++链接器中加入Sqlite.lib,然后在测试一下是否能正常加载Sqlite驱动 #include<QtPlugin> Q_IMPORT_P ...

  8. 被拒原因——You have selected the Kids Category for your app, but it does not include the required privacy policy. Please update your app metadata to include a privacy policy URL and ensure that the URL yo

    对于一些孩子类的应用,必须加上隐私政策网址(URL),直接截个图吧! 就是你上架的时候,填写应用信息,里面有一个隐私政策网址(URL),望后者不掉坑里了!!!

  9. hdu.1429.胜利大逃亡(续)(bfs + 0101011110)

    胜利大逃亡(续) Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  10. java中堆和栈的区别

    从宏观上来讲,栈内存:存储基本数据类型.堆内存:存储实际的对象内容.说明白点就是new出来的东西. int a = 3; int b = 3; a = 4; 编译器首先会处理int a = 3;将a进 ...